const crypto = require('crypto');
// AES-256-ECB加密
function aes(cryptoFn, body, key, encoding) {
const cipher = crypto[cryptoFn]('aes-256-ecb', new Buffer(key), new Buffer(''));
cipher.setAutoPadding(true);
let ciph = cipher.update(body, encoding.input, encoding.output);
ciph += cipher.final(encoding.output);
return ciph;
}
// 加密
function encrypt(key, data, method = 'aes') {
const jsonStr = JSON.stringify(data);
if (method == 'base64') {
return Buffer.from(jsonStr, 'utf8').toString('base64');
}
return aes('createCipheriv', jsonStr, key, {
input: 'utf8',
output: 'base64',
});
}
// 解密
function decrypt(key, data, method = 'aes') {
if (method == 'base64') {
return Buffer.from(data, 'base64').toString('utf8');
}
return aes('createDecipheriv', data, key, {
input: 'base64',
output: 'utf8',
});
}
// DES-CBC加密
function des(cryptoFn, body, key, iv, encoding) {
const cipher = crypto[cryptoFn]('des', new Buffer(key), new Buffer(iv));
let ciph = cipher.update(body, encoding.inout, encoding.output);
ciph += cipher.final(encoding.output);
return ciph;
}
Node.js 之 Crypto 模块加解密
最新推荐文章于 2024-05-07 21:34:58 发布