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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With