"Error: error:0406C06E:rsa routines:RSA_padding_add_PKCS1_type_1:data too large for key size"
当我这样做时,我收到错误:
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个密钥的公共解密).我正在使用单个密钥进行测试.
RSA通过模幂运算来工作.这意味着任何加密的东西通常都具有与模数一样多的位(这是两个素数的乘积).
RSA需要填充方案才能安全.默认RSA_PKCS1_OAEP_PADDING
位于node.js. 此填充方案在加密前向明文添加42个字节,但现在新的明文(first_result
)大于模数,并且无法以可恢复的方式对其进行加密.
您有两种选择:
使用混合加密或
禁用填充以用于以后的迭代.
让我们尝试禁用填充:
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);