Node-RSA可能不正确的密钥

时间:2019-03-14 07:11:00

标签: javascript node.js encryption rsa

前端:Barrett.js, BigInt.js, RSA.js

后端:Node.js,Node-RSA


我尝试使用node-rsa的指数(e)和模数(n)在页面上生成publicKey。然后使用publicKey加密我的字符串。最后,我使用私钥来解密页面中的字符串,但是失败了。我在解密期间收到类似'Error的错误(可能是错误的密钥)。原始错误:错误:数据或密钥不正确'

如果有人能帮助我,我将不胜感激!

下面的代码很简单:

// rsa.pug

h2 n: 
#J_ComN #{n}
h2 e: 
#J_ComE #{e}
h2 Message:
#J_Message Hello RSA!

script(src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js")
script(src="/javascripts/rsa/Barrett.js")
script(src="/javascripts/rsa/BigInt.js")
script(src="/javascripts/rsa/RSA.js")
script(src="/javascripts/rsa.js")
// Front-end codes

var comN = document.getElementById('J_ComN').innerHTML; // n
var comE = document.getElementById('J_ComE').innerHTML; // e
var Message = document.getElementById('J_Message').innerHTML;

setMaxDigits(130); // 1024bits=130,2048bits=260
var publicKey = new RSAKeyPair(comE, '', comN); // n + e -> public key
console.log('publicKey:', publicKey);

var encodedMessage = encodeURIComponent(Message);
console.log('After encodeURIComponent:', encodedMessage);
var encryptedData = encryptedString(publicKey, encodedMessage);
console.log('After encrypting:', encryptedData);


$.ajax({
    url: '/rsa/encrypt',
    method: 'POST',
    data: {
        encryptedData: encryptedData
    }
}).then(function (res) {
    debugger;
}, function () {

});
// Back-end codes

const NodeRSA = require('node-rsa'); // Node RSA

const key = new NodeRSA({
    b: 1024
});
key.setOptions({
    encryptionScheme: 'pkcs1' // 'pkcs1_oaep' or 'pkcs1'. Default 'pkcs1_oaep'
});

const publicComponents = key.exportKey('components-public');
console.log('publicComponents: ', publicComponents);
// { n: <Buffer 00 bc ... >, e: 65537 }

const express = require('express');
const router = express.Router();

// rsa page
router.get('/', function (req, res, next) {

    var n = publicComponents.n.toString('hex'); // n -> hex
    var e = publicComponents.e.toString(16); // e -> hex


    res.render('rsa', {
        n: n,
        e: e
        // n: publicComponents.n,
        // e: publicComponents.e
    });
});

// decrypt the encrypted data
router.post('/encrypt', function (req, res, next) {
    var body = req.body;
    var encryptedData = body.encryptedData;

    console.log('Encrypted data:', encryptedData);

    // 'buffer', 'binary', 'hex' or 'base64'. Default 'buffer'.
    const decrypted = key.decrypt(encryptedData, 'utf8');
    console.log('decrypted: ', decrypted);

});

0 个答案:

没有答案