crypto实现加密node
本文转自:http://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/001434501504929883d11d84a1541c6907eefd792c0da51000算法
crypto模块的做用是为了实现通用的加密和哈希算法。用纯JavaScript实现加密也是能够的,可是比较麻烦且速度很慢, 可是node就使用底层的C/C++实现了加密和哈希算法而后封装起来暴露出接口,供js调用 。 crypto能够实现MD5和SHA1等等等等,由于crypto是封装了不少种加密算法的模块。安全
MD5和SHA1函数
MD5是一种经常使用的哈希算法,用于给任意数据一个签名,这个签名用一个16进制字符串表示 。测试
const crypto = require('crypto'); const hash = crypto.createHash('md5'); // 可任意屡次调用update(): hash.update('Hello, world!'); hash.update('Hello, nodejs!'); console.log(hash.digest('hex')); // 7e1977739c748beac0c0fd14fd26a544
update()方法默认字符串编码为UTF-8,也能够传入Buffer。ui
若是要计算SHA1来进行签名,只须要将MD5改成SHA1便可。this
还有更安全的SHA256和SHA512。 (注意: SHA1最后是数字1,而不是字母L)。编码
Hmac加密
Hmac也是一种哈希算法,不一样的是,这种算法除了MD5和SHA1的类似之处外,还须要一个额外的密钥。spa
const crypto = require('crypto'); const hmac = crypto.createHmac('sha256', 'secret-key'); hmac.update('Hello, world!'); hmac.update('Hello, nodejs!'); console.log(hmac.digest('hex')); // 80f7e22570...
只要密钥发生了变化,那么一样的输入数据也会获得不一样的签名,所以,能够把Hmac理解为用随机数“加强”的哈希算法。
AES
AES是一种经常使用的对称加密算法,加解密都用同一个密钥。crypto模块提供了AES支持,可是须要本身封装好函数,便于使用:
const crypto = require('crypto'); function aesEncrypt(data, key) { const cipher = crypto.createCipher('aes192', key); var crypted = cipher.update(data, 'utf8', 'hex'); crypted += cipher.final('hex'); return crypted; } function aesDecrypt(encrypted, key) { const decipher = crypto.createDecipher('aes192', key); var decrypted = decipher.update(encrypted, 'hex', 'utf8'); decrypted += decipher.final('utf8'); return decrypted; } var data = 'Hello, this is a secret message!'; var key = 'Password!'; var encrypted = aesEncrypt(data, key); var decrypted = aesDecrypt(encrypted, key); console.log('Plain text: ' + data); console.log('Encrypted text: ' + encrypted); console.log('Decrypted text: ' + decrypted);
运行结果以下:
Plain text: Hello, this is a secret message! Encrypted text: 8a944d97bdabc157a5b7a40cb180e7... Decrypted text: Hello, this is a secret message!
能够看出加密后的字符通过解密由获得了原来的内容。
注意到AES有不少不一样的算法,如aes192
,aes-128-ecb
,aes-256-cbc
等,AES除了密钥外还能够指定IV(Initial Vector),不一样的系统只要IV不一样,用相同的密钥加密相同的数据获得的加密结果也是不一样的。加密结果一般有两种表示方法:hex和base64,这些功能Nodejs所有都支持,可是在应用中要注意,若是加解密双方一方用Nodejs,另外一方用Java、PHP等其它语言,须要仔细测试。若是没法正确解密,要确认双方是否遵循一样的AES算法,字符串密钥和IV是否相同,加密后的数据是否统一为hex或base64格式
。。。