Node.js 加密
Node.js加密
Node.js加密模块支持加密。它提供了加密功能,其中包括用于开放SSL的哈希HMAC,加密,解密,签名和验证功能的一组包装器。
什么是散列
散列是固定长度的位字符串,即从任意源数据块中以程序方式和确定性方式生成。
什么是HMAC
HMAC代表基于哈希的消息身份验证代码。这是一个将哈希算法应用于数据和密钥的过程,从而导致单个最终哈希。
使用哈希和HMAC的加密示例
文件: crypto_example1.js
const crypto = require('crypto');
const secret = 'abcdefg';
const hash = crypto.createHmac('sha256', secret)
.update('Welcome to lidihuo')
.digest('hex');
console.log(hash);
打开Node.js命令提示符并运行以下代码:
使用密码的加密示例
文件: crypto_example2.js
const crypto = require('crypto');
const cipher = crypto.createCipher('aes192', 'a password');
var encrypted = cipher.update('Hello lidihuo', 'utf8', 'hex');
encrypted += cipher.final('hex');
console.log(encrypted);
打开Node.js命令提示符并运行以下代码:
使用解密程序的解密示例
文件: crypto_example3.js
const crypto = require('crypto');
const decipher = crypto.createDecipher('aes192', 'a password');
var encrypted = '4ce3b761d58398aed30d5af898a0656a3174d9c7d7502e781e83cf6b9fb836d5';
var decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
console.log(decrypted);
打开Node.js命令提示符并运行以下代码: