当前位置: 首页 > news >正文

node.js内置模块之---crypto 模块

crypto 模块的作用

在 Node.js 中,crypto 模块提供了多种加密功能,包括哈希、对称加密、非对称加密和数字签名等。通过 crypto 模块,可以进行各种加密和解密操作,保护敏感数据的安全性。

crypto 模块

1. 哈希算法(Hashing)

哈希函数(如 SHA、MD5 等)用于将输入数据映射为一个固定长度的字符串(哈希值)。它是单向的,不可逆的,通常用于数据完整性验证。

  • createHash(algorithm):创建一个哈希对象,algorithm指定使用的哈希算法(例如'sha256','md5')。
  • update(data):向哈希对象添加数据,可以调用多次。
  • digest(encoding):返回哈希值,encoding可以是'hex''base64''binary'
示例:生成 SHA-256 哈希值
const hash = crypto.createHash('sha256');
hash.update('Hello, world!');
const result = hash.digest('hex');
console.log(result);  // 输出 SHA-256 哈希值
2、加密与解密(Encryption and Decryption)
对称加密

对称加密使用相同的密钥进行加密和解密。crypto 模块支持多种对称加密算法,如 AES(AES-128、AES-256)等。

  • createCipheriv(algorithm, key, iv):创建加密对象,algorithm是加密算法,key是密钥,iv是初始化向量(IV)。
  • update(data, inputEncoding, outputEncoding):将明文数据输入并指定编码,返回加密数据。
  • final(outputEncoding):返回最后的加密数据。
示例:使用 AES-256-CBC 加密和解密
const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32);  // 32 字节的密钥
const iv = crypto.randomBytes(16);   // 16 字节的初始化向量

// 加密
const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update('Hello, world!', 'utf8', 'hex');
encrypted += cipher.final('hex');
console.log('Encrypted:', encrypted);

// 解密
const decipher = crypto.createDecipheriv(algorithm, key, iv);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
console.log('Decrypted:', decrypted);
非对称加密

非对称加密使用一对密钥——公钥和私钥。公钥用于加密,私钥用于解密。

  • generateKeyPairSync(type, options):同步生成公钥和私钥对,type指定密钥类型(如'rsa'),options指定密钥的参数。
  • publicEncrypt(publicKey, data):使用公钥对数据进行加密。
  • privateDecrypt(privateKey, data):使用私钥对数据进行解密。
示例:使用 RSA 非对称加密
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
  modulusLength: 2048,  // 公钥的位数
});

// 使用公钥加密
const encrypted = crypto.publicEncrypt(publicKey, Buffer.from('Hello, world!'));
console.log('Encrypted:', encrypted.toString('hex'));

// 使用私钥解密
const decrypted = crypto.privateDecrypt(privateKey, encrypted);
console.log('Decrypted:', decrypted.toString());
3. HMAC(Hash-based Message Authentication Code)

HMAC 是一种基于哈希的消息认证码,用于验证消息的完整性和真实性。它结合了哈希函数和密钥,能够防止中间人攻击。

  • createHmac(algorithm, key):创建 HMAC 对象,algorithm指定哈希算法(如'sha256'),key是密钥。
  • update(data):向 HMAC 对象输入数据。
  • digest(encoding):返回 HMAC 的结果,通常是'hex''base64'编码。
示例:生成 HMAC
const secret = 'my-secret-key';
const hmac = crypto.createHmac('sha256', secret);
hmac.update('Hello, world!');
const result = hmac.digest('hex');
console.log('HMAC:', result);
4. 随机数生成(Random Number Generation)

crypto 提供了生成安全随机数的功能,用于生成随机密码、令牌等。

  • randomBytes(size):生成指定字节数的随机数据。
示例:生成随机字节
const randomBytes = crypto.randomBytes(16);  // 生成16个随机字节
console.log(randomBytes.toString('hex'));   // 输出十六进制字符串
5. 数字签名(Digital Signature)

数字签名用于验证数据的完整性和身份认证,通常用于公钥基础设施(PKI)中。它使用私钥对数据签名,使用公钥验证签名。

  • createSign(algorithm):创建一个签名对象,algorithm指定哈希算法。
  • createVerify(algorithm):创建一个验证签名对象,algorithm指定哈希算法。
  • sign(privateKey, encoding):使用私钥对数据进行签名。
  • verify(publicKey, signature, encoding):使用公钥验证签名。
示例:生成签名
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
  modulusLength: 2048,
});

// 生成签名
const sign = crypto.createSign('SHA256');
sign.update('Hello, world!');
const signature = sign.sign(privateKey, 'hex');
console.log('Signature:', signature);

// 验证签名
const verify = crypto.createVerify('SHA256');
verify.update('Hello, world!');
const isVerified = verify.verify(publicKey, signature, 'hex');
console.log('Verified:', isVerified);  // true 或 false
6. 密钥对生成(Key Pair Generation)

非对称加密中,公钥和私钥的生成可以通过 crypto.generateKeyPairSync 方法。

  • generateKeyPairSync(type, options):生成公钥和私钥对,type指定加密算法类型(如'rsa'),options包含密钥的相关参数。
  • export(options):将密钥导出为 PEM 格式。
示例:生成 RSA 密钥对
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
  modulusLength: 2048,
});

console.log('Private Key:', privateKey.export({ type: 'pkcs1', format: 'pem' }));
console.log('Public Key:', publicKey.export({ type: 'pkcs1', format: 'pem' }));

相关文章:

  • redis缓存的应用
  • MySQL很久没碰,复习一下
  • 【从零开始学习计算机科学】数字逻辑(一)绪论
  • 从多智能体变成一个具有通过场景生成多个决策路径 并在实施的过程中优化决策路径 openmanus 致敬开源精神中的每一个孤勇者
  • 电子档案图片jpg格式表单化审核
  • 国内免费使用 Claude 3.7 Sonnt,GPT-4o,DeepSeek-R1联网极速响应
  • AI预测体彩排3新模型百十个定位预测+胆码预测+杀和尾+杀和值2025年3月7日第12弹
  • 【数字电子技术基础】 逻辑函数的公式化简法
  • 算法——链表
  • 案例1_2:点亮8个灯【改进版】
  • 鸿蒙开发:弹性布局Flex
  • Ebook2Audiobook 一键将电子书转有声读物;CVPR 首届跨域小样本对象检测挑战赛数据集上线
  • LINUX网络基础 [四] 自定义协议+序列反序列化
  • 【LLms】关键词提取
  • 基于websocket搭建聊天室
  • 深度学习基础--CNN经典网络之“DenseNet”简介,源码研究与复现(pytorch)
  • no space left on device,内存不足/inode不足
  • PyTorch模型优化设计一个高效的神经网络架构实例
  • 下载Hugging Face模型的几种方式
  • EPLAN常见功能使用
  • 做电路方案设计的网站/长沙seo全网营销
  • 铜陵市建设工程管理局网站/网站推广计划书范文
  • 带注册登录的网站模板/优化大师win7
  • 集团网站建设公司/关键词搜索爱站网
  • 应聘ui设计师自我介绍/seo数据
  • 怎样做网站管理/网络营销中心