Skip to content

Instantly share code, notes, and snippets.

@stringang
Last active November 27, 2018 03:03
Show Gist options
  • Save stringang/184624dd1963b6b657ec0ff394cf8243 to your computer and use it in GitHub Desktop.
Save stringang/184624dd1963b6b657ec0ff394cf8243 to your computer and use it in GitHub Desktop.
AES 加密解密
/**
* 加密/解密计算
* 将 123456 进行 aes-128-ecb 加密(128bit 等于 16Byte)
* created by gang on 2018/11/26
* https://segmentfault.com/a/1190000011041123
*/
const CryptoJS = require('crypto-js');
let key = '033d2ea8e63ac051';
/**
* 转换成 16 字节数组
* 当 key 不足 16 字节时需要填充
*/
const aakey = CryptoJS.enc.Utf8.parse(fillKey(key)); // key 小于 16 字节
const aakey = CryptoJS.enc.Utf8.parse(Buffer.from(key)); // key 等于 16 字节
const aakey = CryptoJS.enc.Utf8.parse(key); // 直接转换成 16 字节数组
// 根据 key 的大小自动选择 AES-128/AES-256
const cipher = CryptoJS.AES.encrypt('123456', aakey, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
// ECB 不需要 offset
iv: '',
});
console.log('cipher', cipher.toString());
// 解密
const decipher = CryptoJS.AES.decrypt(cipher.toString(), aakey, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
iv: '',
});
const resultDecipher = CryptoJS.enc.Utf8.stringify(decipher);
console.log(resultDecipher);
/**
* key 不足 16 字节,进行填充
* @param key
* @returns {Buffer}
*/
function fillKey(key) {
const filledKey = Buffer.alloc(128 / 8);
const keys = Buffer.from(key);
if (keys.length <= filledKey.length) {
filledKey.map(function (b, i) {
filledKey[i] = keys[i];
})
}
return filledKey;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment