获取错误“数据对于密钥大小来说太大”与Crypto Node.js [英] Getting error "data too large for key size" with Crypto Node.js

查看:1100
本文介绍了获取错误“数据对于密钥大小来说太大”与Crypto Node.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到错误错误:错误:0406C06E:rsa例程:RSA_padding_add_PKCS1_type_1:关键字大小的数据太大当我这样做:

I'm getting the error "Error: error:0406C06E:rsa routines:RSA_padding_add_PKCS1_type_1:data too large for key size" when I do:

var crypto = require('crypto');
var fs = require('fs');

var first_keys = {
    public_key: fs.readFileSync('tests/public.key'),
    private_key: fs.readFileSync('tests/private.key')
}

var first_result = crypto.privateEncrypt({
    key: first_keys.private_key
}, new Buffer("Hello World!"));

var second_result = crypto.privateEncrypt({
    key: first_keys.private_key
}, first_result);

var second_plaintext = crypto.publicDecrypt({
    key: first_keys.public_key
}, second_result);

var first_plaintext = crypto.publicDecrypt({
    key: first_keys.public_key
}, second_plaintext);

if(first_plaintext == new Buffer("Hello World!"))
    console.log("Hello World!");

我知道这很奇怪,但是我正在创建一个需要这个工作来进行n次迭代的过程(n密钥的私有加密和n个密钥的公开解密)。我正在使用单个密钥进行测试。

I know it is weird, but I'm creating a process that requires this to work for n iterations (private encrypting for n keys and public decrypting for n keys). I'm using a single key for testing purposes.

推荐答案

RSA通过进行模幂运算。这意味着任何被加密的东西通常会具有与模数(这是两个素数的乘积)一样多的位。

RSA works by doing modular exponentiation. This means that anything that is encrypted will usually have as many bits as the modulus (which is the product of the two primes).

RSA需要一个填充方案才能安全。 node.js中的默认值为 RSA_PKCS1_OAEP_PADDING 这种填充方案在加密之前添加42个字节到明文,但是现在新的明文( first_result )大于模数,它将无法在可恢复的加密方式。

RSA needs a padding scheme to be secure. The default is RSA_PKCS1_OAEP_PADDING in node.js. This padding scheme adds 42 bytes to the plaintext before encryption, but now the new plaintext (first_result) is larger than the modulus and it will not be able to encrypt it in a recoverable manner.

您有两个选项:


  • 使用混合加密

  • 禁用填充以供稍后的迭代。

我们试试禁用填充:

var first_result = crypto.privateEncrypt({
    key: first_keys.private_key
}, new Buffer("Hello World!"));

var second_result = crypto.privateEncrypt({
    key: first_keys.private_key,
    padding: constants.RSA_NO_PADDING
}, first_result);

var second_plaintext = crypto.publicDecrypt({
    key: first_keys.public_key,
    padding: constants.RSA_NO_PADDING
}, second_result);

var first_plaintext = crypto.publicDecrypt({
    key: first_keys.public_key
}, second_plaintext);

这篇关于获取错误“数据对于密钥大小来说太大”与Crypto Node.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆