Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RSA Public-Key: (49 bit) - `public_encrypt': data too large for key size #420

Closed
TW-D opened this issue Mar 9, 2021 · 1 comment
Closed

Comments

@TW-D
Copy link

TW-D commented Mar 9, 2021

Hello to you, I don't think I understand the reason for the "data too large for key size" error when encrypting a message like 'abcd' (4 bytes) with a 49 bits RSA public key when the key length (n) is ~7 bytes.

require('openssl')

PUBLIC_MODULUS_N = OpenSSL::BN.new(379381098436349)
PUBLIC_EXPONENT_E = OpenSSL::BN.new(11)

PRIME_P = OpenSSL::BN.new(18464531)
PRIME_Q = OpenSSL::BN.new(20546479)

PRIVATE_EXPONENT_D = OpenSSL::BN.new(68978374440971)

rsa = OpenSSL::PKey::RSA.new()
rsa.set_key(PUBLIC_MODULUS_N, PUBLIC_EXPONENT_E, PRIVATE_EXPONENT_D)
rsa.set_factors(PRIME_P, PRIME_Q)

PUBLIC_KEY = rsa.public_key()
if (PUBLIC_KEY.public?())
    pp(PUBLIC_KEY.n().num_bytes())
    pp(PUBLIC_KEY.to_text())
    pp(PUBLIC_KEY.to_pem())
    # pp(OpenSSL::PKey::RSA.constants())
    # [:PKCS1_OAEP_PADDING, :NO_PADDING, :PKCS1_PADDING, :SSLV23_PADDING]
    pp(PUBLIC_KEY.public_encrypt('abcd')) # => ERROR: data too large for key size
end

pp('')

if (rsa.private?())
    pp(rsa.n().num_bytes())
    pp(rsa.to_text())
    pp(rsa.to_pem())
end

Thank you for your help.

@rhenium
Copy link
Member

rhenium commented Mar 10, 2021

OpenSSL::PKey::RSA#public_encrypt by default uses PKCS #1 v1.5 encryption scheme (https://ruby.github.io/openssl/OpenSSL/PKey/RSA.html#method-i-private_encrypt). The scheme adds 11 octets of padding at the minimum, so it will not work with a 49-bits RSA key.

@rhenium rhenium closed this as completed Mar 10, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants