Reputation: 487
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
Upvotes: 1
Views: 1650
Reputation: 2131
You are asking not for the key, but for an encoded representation of it. That's why it is named getEncoded()
.
Standard encoding for all crypto stuff is ASN.1 DER, and according to the specific standards for RSA keys, there's version, algorithm identifier, and the key integer itself to be present in the encoding.
Your question is similar to asking "when I store a picture in a GIF, why is the size not the number of pixels multiplied with byte per pixel?". Encoding is more complex than just the raw data.
Adding a quote on details, to make this answer more useful:
PrivateKeyInfo ::= SEQUENCE {
version Version,
algorithm AlgorithmIdentifier,
PrivateKey BIT STRING
}
AlgorithmIdentifier ::= SEQUENCE {
algorithm OBJECT IDENTIFIER,
parameters ANY DEFINED BY algorithm OPTIONAL
}
with AlgorithmIdentifier for RSA being the OID 1.2.840.113549.1.1.1 in OID format.
See also Java JDK docs, e.g. Key interface JavaDoc.
Upvotes: 0
Reputation: 1895
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.
Upvotes: 2