NodeJS加密解密及node-rsa加密解密用法詳解
要用nodejs開發(fā)接口,實現(xiàn)遠程調用,如果裸奔太危險了,就在網上找了一下nodejs的加密,感覺node-rsa挺不錯的,下面來總結一下簡單的rsa加密解密用法
初始化環(huán)境
新建一個文件夾 node-rsa-demo , 終端進入,運行下面命令初始化
cd node-rsa-demo npm init # 一路回車即可 npm install --save node-rsa
生成公鑰私鑰
在 node-rsa-demo 下新建一個文件 index.js 寫上如下代碼
var NodeRSA = require('node-rsa') var fs = require('fs') function generator() { var key = new NodeRSA({ b: 512 }) key.setOptions({ encryptionScheme: 'pkcs1' }) var privatePem = key.exportKey('pkcs1-private-pem') var publicPem = key.exportKey('pkcs1-public-pem') fs.writeFile('./pem/public.pem', publicPem, (err) => { if (err) throw err console.log('公鑰已保存!') }) fs.writeFile('./pem/private.pem', privatePem, (err) => { if (err) throw err console.log('私鑰已保存!') }) } generator();
先在 node-rsa-demo 文件夾下新建一個文件夾 pem 用來存放密鑰的,然后執(zhí)行 node index.js ,會發(fā)現(xiàn)在 pem 文件夾下生成了兩個文件
- private.pem
- public.pem
加密
加密 hello world 這個字符串
function encrypt() { fs.readFile('./pem/private.pem', function (err, data) { var key = new NodeRSA(data); let cipherText = key.encryptPrivate('hello world', 'base64'); console.log(cipherText); }); } //generator(); encrypt();
然后執(zhí)行 node index.js 終端里會輸出一串類似
fH1aVCUceJYVvt1tZ7WYc1Dh5dVCd952GY5CX283V/wK2229FLgT9WfRNAPMjbTtwL9ghVeYD4Lsi6yM1t4OqA== 的base64字符串,這就是用私鑰加密后的密文了
解密
把上一步加密獲得的密文復制粘貼到下面要解密的方法內
function decrypt() { fs.readFile('./pem/public.pem', function (err, data) { var key = new NodeRSA(data); let rawText = key.decryptPublic('fH1aVCUceJYVvt1tZ7WYc1Dh5dVCd952GY5CX283V/wK2229FLgT9WfRNAPMjbTtwL9ghVeYD4Lsi6yM1t4OqA==', 'utf8'); console.log(rawText); }); } //generator(); //encrypt(); decrypt();
執(zhí)行 node index.js
會發(fā)現(xiàn)又拿到 hello world
了
參考
https://github.com/rzcoder/node-rsa
PS:下面通過一段代碼看下nodejs加密解密
nodejs是通集成在內核中的crypto模塊來完成加密解密。
常用加密解密模塊化代碼:
/** * Created by linli on 2015/8/25. */ var crypto = require('crypto'); //加密 exports.cipher = function(algorithm, key, buf) { var encrypted = ""; var cip = crypto.createCipher(algorithm, key); encrypted += cip.update(buf, 'binary', 'hex'); encrypted += cip.final('hex'); return encrypted }; //解密 exports.decipher = function(algorithm, key, encrypted) { var decrypted = ""; var decipher = crypto.createDecipher(algorithm, key); decrypted += decipher.update(encrypted, 'hex', 'binary'); decrypted += decipher.final('binary'); return decrypted };
此處,只針對可逆加密。
總結
以上所述是小編給大家介紹的NodeJS加密解密及node-rsa加密解密用法詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
相關文章
npm報錯:npm?WARN?config?global?'--global',?&apo
這篇文章主要給大家介紹了關于npm報錯:npm?WARN?config?global?'--global',?'--local'?are?deprecated.?Use?`--location=global`?instead.的解決方法,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2022-08-08Node.js中的Buffer對象及創(chuàng)建方式
node.js提供了一個Buffer對象來提供對二進制數據的操作,Buffer?類的實例類似于整數數組,但?Buffer?的大小是固定的、且在?V8?堆外分配物理內存。本文給大家介紹Node.js中的Buffer對象及創(chuàng)建方式,感興趣的朋友一起看看吧2022-01-01Node.js使用bcrypt-pbkdf實現(xiàn)密碼加密
在這個數字時代,保護用戶密碼的重要性不言而喻,作為一名資深的前端開發(fā)工程師和技術博客作者,今天我將帶你詳細了解如何在 Node.js 環(huán)境中利用 bcrypt-pbkdf 模塊進行密碼的哈希處理,確保你的應用安全性得到有效提升,需要的朋友可以參考下2024-05-05