X.509 SubjectPublicKeyInfo to CryptoAPI PUBLICKEYBLOB & .NET XML key Converter

RSA public keys are encoded into standard X.509 certificates in ASN.1 encoded SubjectPublicKeyInfo format. Java 2 provides convenient creation of this encoded form (PublicKey.getEncoded()). However, in Windows CryptoAPI, RSA public keys are typically exported and imported in the specialized PUBLICKEYBLOB format. Also, .NET 1.1+ uses XML-encoded public and private key strings to construct RSACryptoServiceProvider objects.

PubConvert.java is a simply utility Java class which reads an X.509 encoded SubjectPublicKeyInfo file, instantiates an RSAPublicKey instance using an RSA Keyfactory, extracts the RSA public key components and writes:

      java   PubConvert  SubjectPublicKeyInfo_File
Since Java generally reads/writes multi-byte data in big-endian format, and ASN.1 octets are always in big-endian order, but the PUBLICKEYBLOB has members formatted in little-endian order, the parsing in Java must reformat the data and reverse byte arrays. However, XML RSA keys are encoded in big-endian format so byte reversal is not necessary.

The class contains two static method:

   private static byte[]  subjectpublickeyinfoToPublickeyblob(byte[] encodedPubkey,  int keyspec) 
   private static String  subjectpublickeyinfoToXMLRSAPubKey(byte[] encodedPubkey) 

The PUBLICKEYBLOB file is constructed according to the PUBLICKEYBLOB specification. The modulus data extracted in Java might contain a most significant (first byte) of zero, which must be removed before writing the PUBLICKEYBLOB and b64 encoding for the XML representation.

See also:
Pempublic: X.509 SubjectPublicKeyInfo Decoder
CryptoAPI PUBLICKEYBLOB to Java PublicKey Converter