node加密

var crypto = require('crypto');

//md5加密

exports.md5 = function (str) {

var md5sum = crypto.createHash('md5');
md5sum.update(str);
str = md5sum.digest('hex');
return str;
}

//aes192加密

exports.encrypt = function (str, secret) {
var cipher = crypto.createCipher('aes192', secret);
var enc = cipher.update(str, 'utf8', 'hex');
enc += cipher.final('hex');
return enc;
}

//aes192解密

exports.decrypt = function (str, secret) {
var decipher = crypto.createDecipher('aes192', secret);
var dec = decipher.update(str, 'hex', 'utf8');
dec += decipher.final('utf8');
return dec;
}

//aes-128-cbc加密和解密

let str = 'aaaaaaaa';

const crypto = require('crypto');
let key = "08281690909";
let iv = "0828164343434";
let encipher = crypto.createCipheriv('aes-128-cbc', key, iv);
let encoded = encipher.update(str,'utf8','hex');
encoded += encipher.final('hex')
console.log('加密'+encoded);//da4941c6e797895527305b6b6ca28b37

let decipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
let decoded = decipher.update(encoded,'hex','utf8')
decoded += decipher.final('utf8')
console.log('解密'+decoded)

//aes-128-cbc
exports.wxPaValidate = function(sessionKey, encryptedData, iv) {
const sessionKeyVal = new Buffer(sessionKey, 'base64')
const encryptedDataVal = new Buffer(encryptedData, 'base64')
const ivVal = new Buffer(iv, 'base64')
try {
// 解密
var decipher = crypto.createDecipheriv('aes-128-cbc', sessionKeyVal, ivVal)
// 设置自动 padding 为 true,删除填充补位
decipher.setAutoPadding(true)
var decoded = decipher.update(encryptedDataVal, 'binary', 'utf8')
decoded += decipher.final('utf8')
decoded = JSON.parse(decoded)
} catch (err) {
throw new Error('Illegal Buffer')
}
if (decoded.watermark.appid !== appId) {
throw new Error('Illegal Buffer')
}
return decoded
}

上一篇:mysql的下载安装


下一篇:【Android】 onSaveInstanceState()恢复数据