Node.js內置模塊之加密crypto

'use strict'
//crypto(kri:pto)意爲加密
const cons = require('crypto');
//聲明爲const 表示該變量不可修改
//Hash算法
var hash = cons.createHash('md5')//'sha1', 'md5', 'sha256', 'sha512'等
hash.update("hello world")
console.log(hash.digest('hex'));

//Hmac算法,需要一個密鑰
var hmac = cons.createHmac('sha1','secret-key');
hmac.update('hello world');
console.log(hmac.digest('hex'));
//AES是一種常用的對稱加密算法,加解密都用同一個密鑰。crypto模塊提供了AES支持,但是需要自己封裝好函數,便於使用:
//加密  cipher意爲暗號
function aesCrypto(data,key){
    //創建一個加了祕鑰的暗號
   const cipher =  cons.createCipher('aes192',key);
   //將暗號轉換成十六進制
   var aes = cipher.update(data,'utf-8','hex');
   aes+=cipher.final('hex');
   return aes;
}
//解密
function aesDecrypto(data,key){
    const dcipher = cons.createDecipher('aes192',key);
    var daes = dcipher.update(data,'hex','utf-8');
    daes+=dcipher.final('utf-8');
    return daes;
}
var data = '這是一個祕密,需要加密';
var key = 'passworld';
var encrypted = aesCrypto(data, key);
var decrypted = aesDecrypto(encrypted, key);


console.log('加密後: ' + encrypted);
console.log('解密後: ' + decrypted);
//注意到AES有很多不同的算法,如aes192,aes-128-ecb,aes-256-cbc等,AES除了密鑰外還可以指定IV(Initial Vector),
//不同的系統只要IV不同,用相同的密鑰加密相同的數據得到的加密結果也是不同的。
//加密結果通常有兩種表示方法:hex和base64,這些功能Nodejs全部都支持,
//但是在應用中要注意,如果加解密雙方一方用Nodejs,另一方用Java、PHP等其它語言,需要仔細測試。
//如果無法正確解密,要確認雙方是否遵循同樣的AES算法,字符串密鑰和IV是否相同,加密後的數據是否統一爲hex或base64格式。


輸出如下:
5eb63bbbe01eeed093cb22bb8f5acdc3
b84b002077152646a6da921cf58121705150a967
加密後: 7b095fe521e9bb0031ccaea19106d26ccf9f0bc2a771228ee9878a10af510b71
解密後: 這是一個祕密,需要加密

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章