'RSA public key size python

I need help using RSA encryption and decryption in Python. I tried to generate a public key and a private key by using RSA 2048, then send the public key as hex to a destination. However, I faced a problem, the generated public key size is greater than 2048 bit. I used the following script. Could I know why the key size is greater than 2048 bit?

import Crypto
from Crypto.PublicKey import RSA

key = RSA.generate(2048)

binPrivKey = key.exportKey('DER')
binPubKey = key.publickey().exportKey('DER')

print(binPubKey.encode('hex'))


Solution 1:[1]

An RSA public key consists of two components: the modulus and the public exponent. The size of the modulus determines the key size. It is therefore 2048 bits if that's the size given to the key pair generator. The public exponent can be any value and could be up to 2048 bits as well. However, it is usually small. Nowadays it is commonly set to the value 65537, which is 010001 in hexadecimals. It is a special number called the fifth prime of Fermat, usually indicated by "F4" (zero based indexation).

The public key structure should contain both components. The encoded key size is generally larger than the key size for any asymmetric primitive such as RSA. Besides that is may contain overhead (to identify the location of the modulus and exponent) and information about the key itself (for instance an OID that indicates that it is indeed an RSA public key).


To know more about this you could take a look at the PKCS#1 and X.509 certificate specifications. The latter specifies a structure called SubjectPublicKeyInfo which is PEM encoded in the answer of squeamish ossifrage. You can parse it online here.

SEQUENCE (2 elem)
    SEQUENCE (2 elem)
        OBJECT IDENTIFIER1.2.840.113549.1.1.1 rsaEncryption (PKCS #1)
        NULL
    BIT STRING (1 elem)
        SEQUENCE (2 elem)
            INTEGER (2048 bit) 229584378117493781267359049573867661726440328315282498307064019352014…
            INTEGER 65537

Here the first number is the modulus and the second is the public exponent.


So in short there is a difference between key size, encoded key size and key strength.


Notes:

  • An RSA key pair of 2048 bits only provides a key strength of 112 bits (i.e. 112 bits of security), while AES-128 provides about 127 bits of security. In general you should try to use a 3072 bit key instead.
  • The private key often contains the parameters for the Chinese Remainder Theorem and the public exponent on top of the 2048 bit modulus and 2048 bit private exponent, so it will be even larger.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1