nodejs和java交互 AES-128-CBC加密解密
var crypto = require('crypto');
const IV = Buffer.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
/**
* aes 128 cbc加密 PKCS5Padding填充
* @param data 原始数据
* @param key 密钥 设备AccessCode前16个字符
* @returns 密文Buffer
*/
function aes_128_cbc_encrypt(data, key){
var encipher = crypto.createCipheriv('aes-128-cbc', Buffer.from(key, 'ascii'), IV);
var crypted = encipher.update(data, 'utf8', 'binary');
crypted += encipher.final('binary');
return Buffer.from(crypted, 'binary');
}
/**
* aes 128 cbc解密,返回解密后的字符串
* @param crypted 密文
* @param key 密钥 设备AccessCode前16个字符
* @returns 明文
*/
function aes_128_cbc_decrypt(crypted, key){
var buf = new Buffer(crypted, 'hex');
var decipher = crypto.createDecipheriv('aes-128-cbc', Buffer.from(key, 'ascii'), IV);
var decoded = decipher.update(buf, 'binary', 'utf8');
decoded += decipher.final('utf8');
return decoded;
}
module.exports = {
encrypt:aes_128_cbc_encrypt,
decrypt:aes_128_cbc_decrypt
}