Reputation: 111
Here is my Code for generating RSA key
public static void generateRsaKeyPair() {
try {
KeyPairGenerator keyPairGene = KeyPairGenerator.getInstance("RSA");
keyPairGene.initialize(512);
KeyPair keyPair = keyPairGene.genKeyPair();
serverPublicKey = (RSAPublicKey) keyPair.getPublic();
serverPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
} catch (Exception e) {
e.printStackTrace();
} finally{
}
}
Now I want to convert DER/ASN.1 Encoded bytes, Also know what are the default encoded format use when generating RSA key using Java JCE API.
Upvotes: 5
Views: 2916
Reputation: 93948
The RSA key pair that is created using the SunRsaSign
provider consists of an internal representation mainly consisting of BigInteger
values. RSA is an algorithm that is using integer algorithmic after all. Internally it is not likely to be encoded in ASN.1 as the algorithm cannot be performed using binary. You can use your debugger to browse through the internal fields, but note that the internal structure is an implementation detail and should not be relied upon.
To convert the public key to ASN.1 you just need to call serverPublicKey.getEncoded()
and you'll get a SubjectPublicKeyInfo structure, which is an ASN.1 data structure defined for X.509 certificates, encoded using binary BER encoding scheme (DER is a subset of BER, usually the encoding is DER compatible). It consists of a sequence that contains an OID - indicating the RSA key type - and the PKCS#1 encoded public key. You can find the details in here, here and of course structure RSAPublicKey in here.
You can also call serverPrivateKey.getEncoded()
to get an unprotected, inner PKCS#8 structure. However, it is highly questionable if you should do that. You should not distribute unprotected private keys. If you need to store it, use a well protected PKCS#12 key store instead.
Upvotes: 3