Getting error “data too large for key size” with Crypto Node.js

给你一囗甜甜゛ 提交于 2019-12-03 20:23:45

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 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.

You have two options:

Let's try disabling padding:

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!