node 加解密方法(des/aes)
日期: 2018-10-11 浏览量: 7696
node.js 加解密方法实现
1. des 加解密方法
//密钥构造器 des
function keyGenerator(key) {
if (!key) throw new Error('密钥key不能为空');
if (key.length == 8) return Buffer.from(key, 'utf8');
if (key.length >= 16) return HexString2Bytes(key.substr(0, 16));
throw new Error('无效密钥,必须是8位字符或大于等于16位字符');
}
// DES 加密 解密
exports.des = {
encrypt: function (text, key) {
let cipher = crypto.createCipheriv("des-ecb", keyGenerator(key), new Buffer(0))
let encrypt = cipher.update(text, 'utf8', 'base64'
encrypt += cipher.final('base64')
return encrypt
},
decrypt: function (encrypt, key) {
let decipher = crypto.createDecipheriv("des-ecb", keyGenerator(key), new Buffer(0))
let text = decipher.update(encrypt, 'base64', 'utf8')
text += decipher.final('utf8')
return text
}
}
2. aes 加解密方法
//生成加密key aes
exports.create_secret_key = () => {
return new Buffer(crypto.pseudoRandomBytes(16)).toString('base64')
}
//AES 加密-解密
exports.aes = {
/**
* AES 加密
* @param text 明文
* @param base64key 秘钥,base64格式
*/
encrypt: function (text, base64key) {
let buffer = Buffer.from(base64key, 'base64')
let cipher = crypto.createCipheriv("aes-128-cbc", buffer, new Buffer(16))
let encrypt = cipher.update(text, 'utf8', 'base64')
encrypt += cipher.final('base64')
return encrypt
},
/**
* AES 解密
* @param text 密文
* @param base64key 秘钥,base64格式
*/
decrypt: function (encrypt, base64key) {
let buffer = Buffer.from(base64key, 'base64')
let decipher = crypto.createDecipheriv("aes-128-cbc", buffer, new Buffer(16))
let text = decipher.update(encrypt, 'base64', 'utf8')
text += decipher.final('utf8')
return text
}
}
人活着,其实就是一种心态,你若觉得快乐,幸福无处不在;你为自己悲鸣,世界必将灰暗。
阅读排行
最新文章
联系方式
- 邮箱:m18811126599@163.com
- QQ:896956692