在Node.js中,負責安全的模組是crypto。本文主要跟大家分享了Node.js非對稱加密方法以及程式碼實例講解,對此有興趣的朋友參考學習下吧,希望能幫助到大家。
在Node.js中,負責安全的模組是crypto。非對稱加密中,公鑰加密,私鑰解密,加上解密對應的API分別如下。
加密函數:
crypto.publicEncrypt(key, buffer)
解密函數:
crypto.privateDecrypt(privateKey, buffer)
假設有如下utils.js
// utils.js const crypto = require('crypto'); // 加密方法 exports.encrypt = (data, key) => { // 注意,第二个参数是Buffer类型 return crypto.publicEncrypt(key, Buffer.from(data)); }; // 解密方法 exports.decrypt = (encrypted, key) => { // 注意,encrypted是Buffer类型 return crypto.privateDecrypt(key, encrypted); };
測試程式碼app.js:
const utils = require('./utils'); const keys = require('./keys'); const plainText = '你好,我是程序猿小卡'; const crypted = utils.encrypt(plainText, keys.pubKey); // 加密 const decrypted = utils.decrypt(crypted, keys.privKey); // 解密 console.log(decrypted.toString()); // 你好,我是程序猿小卡
附上公鑰、私鑰keys.js:
exports.privKey = `-----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDFWnl8fChyKI/Tgo1ILB+IlGr8ZECKnnO8XRDwttBbf5EmG0qV 8gs0aGkh649rb75I+tMu2JSNuVj61CncL/7Ct2kAZ6CZZo1vYgtzhlFnxd4V7Ra+ aIwLZaXT/h3eE+/cFsL4VAJI5wXh4Mq4Vtu7uEjeogAOgXACaIqiFyrk3wIDAQAB AoGBAKdrunYlqfY2fNUVAqAAdnvaVOxqa+psw4g/d3iNzjJhBRTLwDl2TZUXImEZ QeEFueqVhoROTa/xVg/r3tshiD/QC71EfmPVBjBQJJIvJUbjtZJ/O+L2WxqzSvqe wzYaTm6Te3kZeG/cULNMIL+xU7XsUmslbGPAurYmHA1jNKFpAkEA48aUogSv8VFn R2QuYmilz20LkCzffK2aq2+9iSz1ZjCvo+iuFt71Y3+etWomzcZCuJ5sn0w7lcSx nqyzCFDspQJBAN3O2VdQF3gua0Q5VHmK9AvsoXLmCfRa1RiKuFOtrtC609RfX4DC FxDxH09UVu/8Hmdau8t6OFExcBriIYJQwDMCQQCZLjFDDHfuiFo2js8K62mnJ6SB H0xlIrND2+/RUuTuBov4ZUC+rM7GTUtEodDazhyM4C4Yq0HfJNp25Zm5XALpAkBG atLpO04YI3R+dkzxQUH1PyyKU6m5X9TjM7cNKcikD4wMkjK5p+S2xjYQc1AeZEYq vc187dJPRIi4oC3PN1+tAkBuW51/5vBj+zmd73mVcTt28OmSKOX6kU29F0lvEh8I oHiLOo285vG5ZtmXiY58tAiPVQXa7eU8hPQHTHWa9qp6 -----END RSA PRIVATE KEY----- `; exports.pubKey = `-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDFWnl8fChyKI/Tgo1ILB+IlGr8 ZECKnnO8XRDwttBbf5EmG0qV8gs0aGkh649rb75I+tMu2JSNuVj61CncL/7Ct2kA Z6CZZo1vYgtzhlFnxd4V7Ra+aIwLZaXT/h3eE+/cFsL4VAJI5wXh4Mq4Vtu7uEje ogAOgXACaIqiFyrk3wIDAQAB -----END PUBLIC KEY----- `;
相關推薦:
#以上是Node.js非對稱加密方法的實現的詳細內容。更多資訊請關注PHP中文網其他相關文章!