I am trying to learn how to sign messages using the RSA algorithm with SHA256 in Java. When I generated a 2048-bit KeyPair, I found that both the public and private key were 294 bytes. Here is my code for finding the size of the keys:
import java.security.*;
public class RSATesting
{
public static void main(String[] args) throws Exception
{
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048, new SecureRandom());
KeyPair pair = generator.generateKeyPair();
byte[] publicKeyBytes=pair.getPublic().getEncoded();
System.out.println(publicKeyBytes.length);
byte[] privateKeyBytes=pair.getPublic().getEncoded();
System.out.println(privateKeyBytes.length);
}
}
Why are the keys not 256 bytes?
Thanks
RSA keys aren't like AES keys.
AES keys are some random bytes. RSA keys are numbers. The RSA modulus (N
) defines the lenght.
Your key is 294 bytes long, because of getEncoded();
. It returns a formatted key and not the real lenght.