node.JS的crypto加密模块使用方法详解(MD5,AES,Hmac,Diffie-Hellman加密)

2020-06-17 07:55:46易采站长站整理

Hmac算法也是一种哈希算法,它可以利用MD5或SHA1等哈希算法。不同的是,Hmac还需要一个密钥:

crypto.createHmac(algorithm, key)

创建并返回一个 hmac 对象,用指定的算法和秘钥生成 hmac 图谱。

它是可读写的流 stream 。写入的数据来用计算 hmac。当写入流结束后,使用 read() 方法来获取计算后的值。也支持老的 update 和 digest 方法。

参数 algorithm 取决于平台上 OpenSSL 版本所支持的算法,参见前面的 createHash。key是 hmac 算法中用的 key

hmac.update(data)

根据 data 更新 hmac 对象。因为它是流式数据,所以可以使用新数据调用多次。

hmac.digest([encoding])

计算传入数据的 hmac 值。encoding可以是 ‘hex’, ‘binary’ 或 ‘base64’,如果没有指定encoding ,将返回 buffer。

[注意]调用 digest() 后不能再用 hmac 对象


var crypto = require('crypto');

var hmac = crypto.createHmac('sha256', 'match');

hmac.update('Hello, world!');

hmac.update('Hello, nodejs!');

//e82a58066cae2fae4f44e58be1d589b66a5d102c2e8846d796607f02a88c1649

console.log(hmac.digest('hex'));

crypto的AES加密

AES是一种常用的对称加密算法,加解密都用同一个密钥。crypto模块提供了AES支持,但是需要自己封装好函数,便于使用:

crypto.createCipher(algorithm, password)

使用传入的算法和秘钥来生成并返回加密对象。

algorithm 取决于 OpenSSL,例如’aes192’等。password 用来派生 key 和 IV,它必须是一个’binary’ 编码的字符串或者一个buffer。

它是可读写的流 stream 。写入的数据来用计算 hmac。当写入流结束后,使用 read() 方法来获取计算后的值。也支持老的update 和 digest 方法。

cipher.update(data[, input_encoding][, output_encoding])

根据 data 来更新哈希内容,编码方式根据 input_encoding 来定,有 ‘utf8’, ‘ascii’ or ‘binary’。如果没有传入值,默认编码方式是’binary’。如果data 是 Buffer,input_encoding 将会被忽略。

output_encoding 指定了输出的加密数据的编码格式,它可用是 ‘binary’, ‘base64’ 或 ‘hex’。如果没有提供编码,将返回 buffer 。

返回加密后的内容,因为它是流式数据,所以可以使用不同的数据调用很多次。

cipher.final([output_encoding])

返回加密后的内容,编码方式是由 output_encoding 指定,可以是 ‘binary’, ‘base64’ 或 ‘hex’。如果没有传入值,将返回 buffer。

[注意]cipher 对象不能在 final() 方法之后调用。


var crypto = require('crypto');
function aesEncrypt(data, key) {