Java: Why does a 512-bit RSA KeyPairGenerator return 65 byte keys?
cryptography, java, rsa
Solution
getPrivateExponent() returns a BigInteger and the toByteArray() method returns a byte array, which always includes a sign bit. If the most significant bit in the 512 bit exponent is set, BigInteger will add an extra 513th 0 bit to specify that the number is positive and not a 511 bit negative number with the 512nd bit set to 1. For 513 bits, 65 bytes are required for the encoding.
If you look into the content of the returned byte array, the first byte will always be 0 if you get a 65 element array.
Problem
this is somewhat a newbie question probably. I'm generating keypairs with Java: ``` KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN"); keyGen.initialize(512, random); KeyPair keyPair = keyGen.genKeyPair(); RSAPrivateKey privateKey = (RSAPrivateKey)keyPair.getPrivate(); ``` Now I always thought that privateKey.getModulus() and privateKey.getPrivateExponent() form the "private key" and that they are as big as the keysize (512 bits) passed to the Key Generator. However, privateKey.getPrivateExponent().toByteArray() returns sometimes a 64 byte (as I expected), sometimes a 65 byte array. Why sometimes 65 bytes? Am I missing something here?