crypto模块的目的是提供通用的加密和哈希算法,用纯javascript代码实现这些功能不是不可能,但是速度会非常慢,node用c/c++实现这些算法后,通过crypto模块暴露为js接口,这样用起来方便,速度也快。
MD5是一种常用的哈希算法,用于给任意数据一个‘签名‘,这个签名通常用一个十六进制的字符串表示:
const crypto =
require('crypto');
const hash =
crypto.createHash('md5');
//可任意多次调用
hash.update('hello word');
hash.update('hello node');
console.log(hash.digest('hex'));
Hmac算法也是一种哈希算法,它可以利用MD5或SHA1等哈希算法。不同的是Hmav还需要一个密匙:
const hmac =
crypto.createHmac('sha256','secret-key');
hmac.update('hello word');
hmac.update('hello node');
console.log(hmac.digest('hex'))