前言
nodejs提供了crypto这个npm包,常用的加密算法都可以由crypto包提供的接口实现
各种加密算法实现
const assert = require('assert');
const crypto = require('crypto');
const key = 'dvyYRQlnPRCMdQSe';
/*
* @brief 加密数据
* @param[in] encodeParam<obj> 加密相关参数
* @return 密文
*/
function crypto_encode(encodeParam) {
try {
let plain = encodeParam.plaintext.toString();
//encrypt
const iv = new Buffer(encodeParam.iv ? encodeParam.iv : 0);
const cipher = crypto.createCipheriv(encodeParam.algorithm, encodeParam.key, iv);
cipher.setAutoPadding(encodeParam.autoPadding) //default true
let ciphertext = cipher.update(plain, 'utf8', 'base64');
ciphertext += cipher.final('base64');
console.log("crypto data success: algorithm(%s),plaintext(%s),ciphertext(%s)",
encodeParam.algorithm, plain, ciphertext);
return ciphertext;
} catch (err) {
console.log("crypto data failed: " + err);
return null;
}
}
/*
* @brief 解密数据
* @param[in] decodeParam<obj> 解密相关参数
*/
function decrypt_decode(decodeParam) {
try {
let ciphertext = decodeParam.ciphertext.toString();
//decrypt
const iv = new Buffer(decodeParam.iv ? decodeParam.iv : 0);
const decipher = crypto.createDecipheriv(decodeParam.algorithm, decodeParam.key, iv);
decipher.setAutoPadding(decodeParam.autoPadding); //default true
let plaintext = decipher.update(ciphertext, 'base64', 'utf8');
plaintext += decipher.final('utf8');
console.log("decrypt data success: algorithm(%s),plaintext(%s),ciphertext(%s)",
decodeParam.algorithm, plaintext, ciphertext);
return plaintext;
} catch (err) {
console.log("decrypto data failed: " + err);
return null;
}
}
//aes-128-cbc,zeroPadding
let encodeParam = {
algorithm : 'aes-128-cbc',
iv : 'face0123456789ai',
autoPadding : false,
key : 'dvyYRQlnPRCMdQSe'
}
let plaintext = '1234qwerASDF!'; //加密后67JJSiiX5/PrNDFFO/2vxw==
let buffer_length = plaintext.length + key.length - (plaintext.length % key.length);
encodeParam.plaintext = new Buffer(buffer_length);
encodeParam.plaintext.write(plaintext);
let ciphertext = crypto_encode(encodeParam);
//3des-ecb
crypto_encode({
algorithm : 'des-ede3', //3des-ecb
autoPadding : true,
key : 'gxmy_201906110102sangfor',
plaintext : 'zhangsan',
iv : null
})
//des-ecb
crypto_encode({
algorithm : 'des-ecb',
autoPadding : true,
key : '01234567',
plaintext : '1234567812345678',
iv : null
})