带有RSA enc / dec的node-forge包错误

时间:2015-11-10 20:44:19

标签: node.js encryption meteor cryptography rsa

我在meteor.js网络应用上使用node-forge npm。我试图根据这个例子对一些纯文本进行RSA加密:https://github.com/digitalbazaar/forge#rsa

问题到了,当我想要解密密文时,我想要取回明文,说明加密块无效。

在示例之后,我必须加密字符串中的字节,以便完成所有操作,但我不明白为什么它在解密时失败了?任何猜测?

rsaEncrypt:function(pubPem,privPem,plainText){

console.log(plainText);

var str = plainText;
var bytes = [];

for (var i = 0; i < str.length; ++i) {
  bytes.push(str.charCodeAt(i));
}

console.log("BAJTOVI:");
console.log(bytes);

var publicKey = pki.publicKeyFromPem(pubPem);
console.log(publicKey);

var encrypted = publicKey.encrypt(bytes);
console.log("Encryption: ");
console.log(encrypted);

var privateKey = pki.privateKeyFromPem(privPem);
var decrypted = privateKey.decrypt(encrypted);

console.log("Decryption: ");
console.log(decrypted);

function bin2String(decrypted) {
  var result = "";
  for (var i = 0; i < decrypted.length; i++) {
    result += String.fromCharCode(parseInt(decrypted[i], 2));
  }
  return result;
}
console.log("OPET TEXT:");
console.log(result);

return decryted;

},

我从服务器得到的问题:

Exception while invoking method 'rsaEncrypt' Error: Encryption block is invalid.
I20151110-21:22:05.279(1)?     at Object._decodePkcs1_v1_5 [as decode] (/Users/mrcina/Meteor Projects/cryptonic/.meteor/local/isopacks/npm-container/npm/node_modules/node-forge/js/rsa.js:1446:11)
I20151110-21:22:05.279(1)?     at Object.key.decrypt (/Users/mrcina/Meteor Projects/cryptonic/.meteor/local/isopacks/npm-container/npm/node_modules/node-forge/js/rsa.js:1083:19)
I20151110-21:22:05.279(1)?     at [object Object].Meteor.methods.rsaEncrypt (server/methods.js:49:32)
I20151110-21:22:05.279(1)?     at maybeAuditArgumentChecks (livedata_server.js:1698:12)
I20151110-21:22:05.279(1)?     at livedata_server.js:708:19
I20151110-21:22:05.279(1)?     at [object Object]._.extend.withValue (packages/meteor/dynamics_nodejs.js:56:1)
I20151110-21:22:05.279(1)?     at livedata_server.js:706:40
I20151110-21:22:05.279(1)?     at [object Object]._.extend.withValue (packages/meteor/dynamics_nodejs.js:56:1)
I20151110-21:22:05.280(1)?     at livedata_server.js:704:46
I20151110-21:22:05.280(1)?     at tryCallTwo (/Users/mrcina/.meteor/packages/promise/.0.5.1.1wnrf8h++os+web.browser+web.cordova/npm/node_modules/meteor-promise/node_modules/promise/lib/core.js:45:5)

这一行: var decrypted = privateKey.decrypt(加密);

1 个答案:

答案 0 :(得分:2)

Forge不使用整数数组来表示字节;它使用二进制编码的字符串。尝试将代码简化为以下内容:

rsaEncrypt:function(pubPem,privPem,plainText){

  console.log(plainText);

  var publicKey = pki.publicKeyFromPem(pubPem);
  console.log(publicKey);

  var encrypted = publicKey.encrypt(forge.util.encodeUtf8(plainText));
  console.log("Encryption: ");
  console.log(encrypted);

  var privateKey = pki.privateKeyFromPem(privPem);
  var decrypted = forge.util.decodeUtf8(privateKey.decrypt(encrypted));

  console.log("Decryption: ");
  console.log(decrypted);

  return decrypted;
}