整站优化快速排名,.net做网站,宁波seo网络推广优质团队,网站推广营销运营方式crypto模块的目的是为了提供通用的加密和哈希算法。用纯JavaScript代码实现这些功能不是不可能#xff0c;但速度会非常慢。
Nodejs用C/C实现这些算法后#xff0c;通过cypto这个模块暴露为JavaScript接口#xff0c;这样用起来方便#xff0c;运行速度也快。
只要密钥发…crypto模块的目的是为了提供通用的加密和哈希算法。用纯JavaScript代码实现这些功能不是不可能但速度会非常慢。
Nodejs用C/C实现这些算法后通过cypto这个模块暴露为JavaScript接口这样用起来方便运行速度也快。
只要密钥发生了变化那么同样的输入数据也会得到不同的签名因此可以把Hmac理解为用随机数“增强”的哈希算法。
const crypto require(crypto);// 创建哈希算法 md5 sha1等以 md5 为例
const hash crypto.createHash(md5);
// Hmac 也是一种哈希算法但它还需要一个密钥
const hmac crypto.createHmac(sha256, secret-key);// update 方法将一段字符进行哈希转换可任意多次调用update():
hash.update(Hello, world!);
hash.update(Hello, nodejs!);
hmac.update(Hello, nodejs!);// hex 以十六进制数据的形式进行展示也可以使用 base64 格式进行展示
console.log(hash.digest(hex));
console.log(hmac.digest(base64));update()方法默认字符串编码为UTF-8也可以传入Buffer。
AES是一种常用的对称加密算法加解密都用同一个密钥。crypto模块提供了AES支持但是需要自己封装好函数。
const crypto require(crypto);
// 加密
function encrypt(key, iv, data) {let decipher crypto.createCipheriv(aes-128-cbc, key, iv);// decipher.setAutoPadding(true);return decipher.update(data, binary, hex) decipher.final(hex);
}
// 解密
function decrypt(key, iv, crypted) {crypted Buffer.from(crypted, hex).toString(binary);let decipher crypto.createDecipheriv(aes-128-cbc, key, iv);return decipher.update(crypted, binary, utf8) decipher.final(utf8);
}
// key, iv必须是16个字节
let key 1234567890123456;
let iv 1234567890123456;
let data hello world;
let crypted encrypt(key, iv, data);
console.log(加密结果,crypted);
let decrypted decrypt(key, iv, crypted);
console.log(解密结果,decrypted);