MD5和SHA1
MD5是一种常用的哈希算法,用于给任意数据一个“签名”。这个签名通常用一个十六进制的字符串表示:
const crypto = require('crypto'); const hash = crypto.createHash('md5'); // 可任意多次调用update(): hash.update('Hello, world!'); hash.update('Hello, nodejs!'); console.log(hash.digest('hex'));复制代码
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! 可以看出,加密后的字符串通过解密又得到了原始内容。
廖老师的 http://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/001434501504929883d11d84a1541c6907eefd792c0da51000
个人博客: www.liangtongzhuo.com