node.js-crypto板块使用
最近项目,经常用到了加密板块,这里收集了一下常规的用法
var crypto = require('crypto');
exports.encrypt = function (str, secret) {
var cipher = crypto.createCipher('aes192', secret);
var enc = cipher.update(str, 'utf8', 'hex');
enc += cipher.final('hex');
return enc;
};
exports.decrypt = function (str, secret) {
var decipher = crypto.createDecipher('aes192', secret);
var dec = decipher.update(str, 'hex', 'utf8');
dec += decipher.final('utf8');
return dec;
};
exports.md5 = function (str) {
var md5sum = crypto.createHash('md5');
md5sum.update(str);
str = md5sum.digest('hex');
return str;
};
exports.randomString = function (size) {
size = size || 6;
var code_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var max_num = code_string.length + 1;
var new_pass = '';
while (size > 0) {
new_pass += code_string.charAt(Math.floor(Math.random() * max_num));
size–;
};