time: 2020.12.22
author: heyunjiang
之前做前端 open-api 预签名时,用到了这个模块,使用的是 md5 摘要加密实现方式,这里对 crypto 模块做个总结,目的
Hash 类用于创建数据的 hash 摘要
const crypto = require('crypto');
const hash = crypto.createHash('sha256');
hash.update('要创建哈希摘要的数据');
hash.digest('hex')
问题:hash 摘要是什么东西?
答:输出是 string | buffer,摘要也可说是数字签名
HMAC 类用于创建加密的 HMAC 摘要,格式跟 hash 摘要一样
const crypto = require('crypto');
const hmac = crypto.createHmac('sha256', '密钥');
hmac.update('要创建 hmac 的数据');
hmac.digest('hex')
Sign 是用于生成签名
const crypto = require('crypto');
// 生成私钥、公钥
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
});
const sign = crypto.createSign('SHA256');
sign.update('要生成签名的数据');
sign.end();
const signature = sign.sign(privateKey); // 私钥加密生成数字签名
const verify = crypto.createVerify('SHA256');
verify.update('要生成签名的数据');
verify.end();
verify.verify(publicKey, signature); // 公钥解密做验证