[node] crypto
#
const crypto = require('crypto');
散列算法(哈希算法)
使用hash对象的update方法创建一个摘要  
update方法有两个参数,第一个为一个Buffer对象或者一个字符串,指定内容,第二个为指定的内容所需使用的编码格式,可指定参数值为:utf8、ascii、binary  
如果不使用第二个参数,则第一个参数必须是一个Buffer对象  
使用hash对象的digest方法来输出摘要内容,使用一个可选参数,用于指定输出摘要的编码格式,可指定的参数值为:hex、binary、base64  
如果省略该参数,将返回一个Buffer对象  
let data = '233'; let hasher = crypto.createHash('sha256'); let encrypt = hasher.update(data); let hashmsg = hasher.digest('hex') console.log(hashmsg); console.log(hashmsg.length);
HMAC算法(将散列算法与一个密钥结合在一起)
#
//var pem = fs.readFileSync('key.pem'); //var key = pem.toString('ascii'); //let hmac = crypto.createHmac('sha1',key); //let s = fs.readStream('./app.js'); //s.on('data',function(d){ // hmac.update(d); //}); //s.on('end',function(){ // var d = hmac.digest('hex'); // console.log(d); //}); let hmac = crypto.createHmac('sha1', 'secret'); let hmacdata = '233'; hmac.update(hmacdata); let d = hmac.digest('hex'); console.log(d);
salt
#
let keyss = '123'; let result1 = crypto.pbkdf2Sync(keyss, 'SALT', 100, 20, 'sha512'); console.log(result1.toString('hex')); let result2 = crypto.pbkdf2Sync(keyss, 'SALT', 100, 20, 'sha512'); console.log(result2.toString('hex'));
对称加密
#加密解密
const ciphers = crypto.getCiphers(); //console.log(ciphers); // ['aes-128-cbc', 'aes-128-ccm', ...] let cipher = crypto.createCipher('aes-256-cbc', 'InmbuvP6Z8') let text = "233"; let crypted = cipher.update(text, 'utf8', 'hex') crypted += cipher.final('hex') console.log(crypted); let decipher = crypto.createDecipher('aes-256-cbc', 'InmbuvP6Z8') let dec = decipher.update(crypted, 'hex', 'utf8') dec += decipher.final('utf8') console.log(dec);
 
                    
                     
                    
                 
                    
                 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号