在node中生成一個公鑰和私鑰css
const NodeRSA = require("node-rsa");
const 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('pkcs8-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();
複製代碼
const fs = require("fs")
app.get("/getPublicKey",(req,res)=>{
let publicKey = fs.readFileSync('./pem/public.pem', 'utf-8');
res.send({ 'status': 0, 'msg': '公鑰獲取成功', 'resultmap': publicKey });
})
複製代碼
<body>
<input type="text" name="pwd">
<button>提交</button>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
//在node包中下載jsencrypt,以後引入便可
<script src="./js/jsencrypt.js"></script>
<script>
let str = ""
$.ajax({
type: "get",
url: "http://localhost:3030/getPublicKey",
success: function (response) {
str = response.resultmap
}
});
//使用公鑰加密
function _getPublicKey(password) {
let encryptor = new JSEncrypt();
encryptor.setPublicKey(str)
return encryptor.encrypt(password)
}
$("button").on("click",function(){
let pwd = $("[name=pwd]").val();
//加密後的密碼
let deCode = _getPublicKey(pwd);
$.ajax({
type: "post",
url: "http://localhost:3030/login",
data: {
pwd:deCode
},
success: function (response) {
console.log(response)
}
});
})
</script>
</body>
複製代碼
//後臺利用的是私鑰解密,這個是後臺解密的方法
let deCode = (password) => {
const _priKey = fs.readFileSync(path.resolve(__dirname, './pem/private.pem'));
let jsencrypt = new JSEncrypt()
jsencrypt.setPrivateKey(_priKey.toString())
return jsencrypt.decrypt(password)
}
複製代碼
備註:這裏只是對使用方法作了一個簡單的總結;前端是爲了作測試使用了jQuery,在vue中也可使用前端