nodejs的crypto加密解密简单使用

nodejs的crypto加密使用

简单记录一下使用的node加密解密,不是很了解,欢迎指导

pbkdf2Sync

nodeAPI网址

const crypto = require('crypto')
// crypto.pbkdf2Sync()是用来同步生成加密解密密匙的函数
const key = crypto.pbkdf2Sync(pwd, salt, iterations, KEY_SIZE, 'sha1')
// pwd是自定义的作为密匙的字符串
// salt(文档没太看懂,不过也是个字符串,用来生成密匙的)
// iterations 是设置迭代次数的,次数越高生成的密匙越安全
// KEY_SIZE是设置字节长度的(16 或32之类的)
// 'sha1'(这个暂时没搞懂是啥,应该是用来指定什么模式的)

加密

const algorithm = 'aes-128-cbc'
const VIPARA = '1269571869323221'
const UTF_8 = 'utf-8'
const cipherEncoding = 'base64'
// 加密
	//crypto.createCipheriv生成一个cipher对象
const cipher = crypto.createCipheriv(algorithm, key, VIPARA)
// algorithm这个是用来指定算法的,
// key就是派生的密匙
//  VIPARA是初始化向量,可以空

let encStr = cipher.update(content, UTF_8, cipherEncoding)
// content是你要加密的内容
// 第二个参数指定的是输入的编码格式
// 第三个参数指定的是输出的编码格式
encStr  += cipher.final(cipherEncoding)
// cipherEncoding输出的编码格式
console.log('加密', encStr )

解密

// crypto.createDecipheriv这个是生成decipher 对象的
const decipher = crypto.createDecipheriv(algorithm, key, VIPARA)
// algorithm这个是用来指定算法模式的,
// key就是派生的密匙
//  VIPARA是初始化向量,不需要的话可以空
let decstr = decipher.update(jeimi, cipherEncoding, UTF_8)
// jeimi是你要解密的内容
// 第二个参数指定的是输入的编码格式
// 第三个参数指定的是输出的编码格式
decstr += decipher.final(UTF_8)

console.log('解密 ', decstr )
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
RSA(Rivest-Shamir-Adleman)是一种非对称加密算法,它使用公钥和私钥来加密解密数据。在Node.js中,我们可以使用`crypto`模块来实现RSA加密解密。 首先,我们需要生成RSA密钥对。可以使用以下代码生成一个新的RSA密钥对: ```javascript const crypto = require('crypto'); const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048, publicKeyEncoding: { type: 'pkcs1', format: 'pem' }, privateKeyEncoding: { type: 'pkcs1', format: 'pem' } }); console.log('公钥:'); console.log(publicKey); console.log('私钥:'); console.log(privateKey); ``` 生成的公钥和私钥将以PEM格式显示。 接下来,我们可以使用生成的公钥进行加密,私钥进行解密。以下是一个示例: ```javascript const crypto = require('crypto'); // 加密 function encrypt(data, publicKey) { const buffer = Buffer.from(data, 'utf8'); const encrypted = crypto.publicEncrypt(publicKey, buffer); return encrypted.toString('base64'); } // 解密 function decrypt(encryptedData, privateKey) { const buffer = Buffer.from(encryptedData, 'base64'); const decrypted = crypto.privateDecrypt(privateKey, buffer); return decrypted.toString('utf8'); } // 使用示例 const plaintext = 'Hello, RSA!'; const encrypted = encrypt(plaintext, publicKey); console.log('加密后的数据:', encrypted); const decrypted = decrypt(encrypted, privateKey); console.log('解密后的数据:', decrypted); ``` 请注意,这只是一个基本示例,实际使用时可能需要处理更复杂的数据和错误处理。 希望这可以帮助到你!如有任何问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值