Why is my RSA 2048 public key 294 bytes long?

If I do this:

KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair kp = kpg.genKeyPair();
Key publicKey = kp.getPublic();
byte [] pubKey = publicKey.getEncoded();
System.out.println("Size: " + pubKey.length);

      

My output is 294. Shouldn't the RSA 2048 output be 256 bytes long?

+3


source to share


2 answers


An RSA key does not consist of random bytes such as an AES key; it consists of numbers. The RSA key size is determined by the module, but it also requires a public metric (usually the fourth Fermat number or some other small prime). Thus, when getEncoded()

both are returned in an ASN.1 DER encoded encoded byte array that is typically found in X5.09 certificates called SubjectPublicKeyInfo.



If you want to extract the key size use ((RSAPublicKey) publicKey).getModulus().bitLength()

. To look at the structure, use openssl asn1parse

or use an online decoder like this .

+5


source


  publicKey.getEncoded();

      

This will return an encoded key in a standard format with some overhead (for example, an algorithm identifier).



If you really want the source material, you can use RSAPublicKey

and call getModulus()

and getPublicExponent()

(gives you BigInteger

s).

+2


source







All Articles