crypto

crypto模塊目的是為了提供通用的加密和希哈算法。純js實現這些功能太困難,速度非常慢。nodejs用C實現這些算法之后,通過cypto這個模塊暴露為JS接口,方便,有效。

1.

MD5和SHA1:采用十六進制的字符串表示。

update()方法默認字符串編碼為UTF-8.

要計算SHA1,只需要把‘md5’改成‘sha1’

const crypto =require('crypto');

const hash = crypto.createHash('md5');

// 可任意多次調用update():

hash.update('Hello, world!');

hash.update('Hello, nodejs!');

console.log(hash.digest('hex'));

2.

Hmac算法,可以利用上面的算法,但是它還需要一個密鑰,只要密鑰發(fā)生變化,同樣的數據會得到不同的簽名。

constcrypto =require('crypto');

consthmac = crypto.createHmac('sha256','secret-key');

hmac.update('Hello, world!');

hmac.update('Hello, nodejs!');

console.log(hmac.digest('hex'));

3.

ASE對稱加密算法,加解密都用同一個密鑰。

const? crypto =require('crypto');

function aesEncrypt(data, key){

constcipher = crypto.createCipher('aes192', key);

var? crypted = cipher.update(data,'utf8','hex');? ??

crypted += cipher.final('hex');

return? crypted;

}

functionaesDecrypt(encrypted, key){

const? decipher = crypto.createDecipher('aes192', key);

var? ? decrypted = decipher.update(encrypted,'hex','utf8');??

? decrypted += decipher.final('utf8');

return decrypted;

}

var data ='Hello, this is a secret message!';

var key ='Password!';

var encrypted = aesEncrypt(data, key);

var decrypted = aesDecrypt(encrypted, key);

console.log('Plain text: '+ data);

console.log('Encrypted text: '+ encrypted);

console.log('Decrypted text: '+ decrypted);

如果運行出來,我們就會發(fā)現,將加密的消息又返回了。

4.

Diffie-Hellman算法是一種密鑰交換協議,可以讓對方不泄漏密鑰的情況下商量出一個密鑰。


參考鏈接:https://www.liaoxuefeng.com/

代碼均來自廖雪峰教程。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容