服务器生成RSA公钥和私钥并将其存储在会话中。通过服务器调用,客户端html页面接收到公钥。现在我想使用它加密数据。我尝试使用jsencrypt,但它无法识别我的服务器生成的公钥。在设置公钥后调用加密时会返回false。我认为密钥长度为2048位,但编码不确定。如何使用此密钥加密数据?任何帮助都将不胜感激。
Sample public key generated by server: 9995362445e0a98f4da3019f6f3eb960f938056972408675c0b3f642ad5943709f8e8031f00bba6ed24bad1e8e2b099cd154b5eb5b64b310d179b39abb4392442cdb8ad3fe8bc6e3088bd63089d405fb134c633de62b741e4c5bd615b90e096ec3bb16f71ef54825febc5662a96c093db986225825a1cc63d4dc19e2abbbfb1cb9d3a5e41f757ce3f82481a5caf92207ffe4c37e8acc43835dce49cf61a6b113384d333050b6ac59ef78a182bae114b08729e84cbad659eb8bace0481aa51a370daac09f97d779be245ce95af85a285d0ea170da732f9eef2e43a21f5586014ea00259ef09498356eaf2d4e492f0f8978ca167c3f690b35045a8dd1c7ccf4347
编辑:如许多人建议的那样,我尝试使用加密:
let crypto;
try {
crypto = require('crypto');
} catch (err) {
console.log('crypto support is disabled!');
}
var encryptStringWithRsaPublicKey = function(toEncrypt, publicKey) {
var buffer = Buffer.from(toEncrypt,'utf8');
var encrypted = crypto.publicEncrypt(publicKey, buffer);
return encrypted.toString("base64");
};
console.log(encryptStringWithRsaPublicKey('MyText','9995362445e0a98f4da3019f6f3eb960f938056972408675c0b3f642ad5943709f8e8031f00bba6ed24bad1e8e2b099cd154b5eb5b64b310d179b39abb4392442cdb8ad3fe8bc6e3088bd63089d405fb134c633de62b741e4c5bd615b90e096ec3bb16f71ef54825febc5662a96c093db986225825a1cc63d4dc19e2abbbfb1cb9d3a5e41f757ce3f82481a5caf92207ffe4c37e8acc43835dce49cf61a6b113384d333050b6ac59ef78a182bae114b08729e84cbad659eb8bace0481aa51a370daac09f97d779be245ce95af85a285d0ea170da732f9eef2e43a21f5586014ea00259ef09498356eaf2d4e492f0f8978ca167c3f690b35045a8dd1c7ccf4347'));
它抛出以下错误:
Uncaught TypeError: Cannot read property '2' of null
at push../node_modules/parse-asn1/fixProc.js.module.exports (fixProc.js:19)
at parseKeys (index.js:27)
at Object.publicEncrypt (publicEncrypt.js:30)
at encryptStringWithRsaPublicKey (App.js:20)
at Module.<anonymous> (App.js:23)
at Module../src/App.js (App.js:727)
at __webpack_require__ (bootstrap:781)
at fn (bootstrap:149)
at Module../src/index.js (index.css?f3f6:45)
at __webpack_require__ (bootstrap:781)
at fn (bootstrap:149)
at Object.0 (test.css?2a93:45)
at __webpack_require__ (bootstrap:781)
at checkDeferredModules (bootstrap:45)
at Array.webpackJsonpCallback [as push] (bootstrap:32)
at main.chunk.js:1