1.nodejs中aes的使用
var crypto = require('crypto');
/**
* 加密方法
* @param key 加密key
* @param iv 向量
* @param data 需要加密的数据
* @returns string
*/
var encrypt = function (key, iv, data) {
var cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
var crypted = cipher.update(data, 'utf8', 'binary');
crypted += cipher.final('binary');
crypted = new Buffer(crypted, 'binary').toString('base64');
return crypted;
};
/**
* 解密方法
* @param key 解密的key
* @param iv 向量
* @param crypted 密文
* @returns string
*/
var decrypt = function (key, iv, crypted) {
crypted = new Buffer(crypted, 'base64').toString('binary');
var decipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
var decoded = decipher.update(crypted, 'binary', 'utf8');
decoded += decipher.final('utf8');
return decoded;
};
var key = '751f621ea5c8f930';
console.log('加密的key:', key.toString('hex'));
var iv = '2624750004598718';
console.log('加密的iv:', iv);
var data = "Hello, nodejs. 演示aes-128-cbc加密和解密";
console.log("需要加密的数据:", data);
var crypted = encrypt(key, iv, data);
console.log("数据加密后:", crypted);
var dec = decrypt(key, iv, crypted);
console.log("数据解密后:", dec);
2、浏览器中使用
下载第三方库Crypto-js.js git地址:https://github.com/brix/crypto-js
引入src下的crypto-js.js,加密代码如下:
var key = "12345678" //秘钥必须为:8/16/32位
var message = "123456";
//加密
var encrypt = CryptoJS.AES.encrypt(message, CryptoJS.enc.Utf8.parse(key), {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
console.log("value: "+encrypt);
//解密
var decrypt = CryptoJS.AES.decrypt(encrypt, CryptoJS.enc.Utf8.parse(key), {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
console.log("value: "+decrypt.toString(CryptoJS.enc.Utf8));
参考: