Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why my RSA 2048 Public Key is 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 value is 294. Shouldn't RSA 2048 output be 256 bytes long?

like image 270
João Rodrigues Avatar asked Oct 28 '14 00:10

João Rodrigues


1 Answers

An RSA key does not consist of random bytes like for instance an AES key; it consists of numbers. The key size of RSA is defined by the modulus, but it also requires a public exponent (usually the fourth number of Fermat or another small prime). So with getEncoded() both are returned embedded into an ASN.1 DER encoded byte array. It uses an encoding that is usually present in X5.09 certificates called "SubjectPublicKeyInfo".

If you want to extract the key size, use ((RSAPublicKey) publicKey).getModulus().bitLength() instead. To have a look at the structure, use openssl asn1parse or use an online decoder such as this.

like image 147
Maarten Bodewes Avatar answered Sep 28 '22 16:09

Maarten Bodewes