nodejs aee对称加解密
程序员文章站
2024-03-14 15:43:04
...
'use strict';
const crypto = require('crypto');
const key = "2018201820182018",
iv = "1234567887654321";
/**
* Decryption 解密
* @param data String - JSON字符串
* @return utf8
*/
function AES_decryption(data) {
let cipherChunks = [];
let decipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
decipher.setAutoPadding(true);
cipherChunks.push(decipher.update(data, 'base64', 'utf8'));
cipherChunks.push(decipher.final('utf8'));
return cipherChunks.join('');
}
/**
* Encryption 加密
* @param data String - 加密的是JSON字符串
* @return base64
*
*/
function AES_encryption(data) {
let cipherChunks = [];
let cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
cipher.setAutoPadding(true);
cipherChunks.push(cipher.update(data, 'utf8', 'base64'));
cipherChunks.push(cipher.final('base64'));
return cipherChunks.join('');
}
let res1 = AES_encryption('abcd');
console.log(res1); // 8lCuwh5+vZrZmU1J9c9Alw==
// 8lCuwh5+vZrZmU1J9c9Alw==
let res2 = AES_decryption("8lCuwh5+vZrZmU1J9c9Alw==");
console.log(res2); // abcd