Showing posts with label PEM. Show all posts
Showing posts with label PEM. Show all posts

Tuesday, May 15, 2012

Different formats for RSA keys


RSA keys can be saved into different formats: PEM, DER, Microsoft PUBLICKEYBLOB and Microsoft PRIVATEKEYBLOB. It might be challenging to convert the keys from one format to another.


The keys contain those big numbers used for encryption.
·         Private key contains: modulus, private exponent, public exponent, prime 1, prime 2, exponent 1, exponent 2 and coefficient.
·         Public key contains only modulus and public exponent.

  • DER format is based on Abstract Syntax Notation One (ASN.1). You can use ASN.1 Editor to view its structure and contents.
  • PEM format from OpenSSL is based64 encoded format of DER format
  • PRIVATEKEYBLOB and PUBLICKEYBLOB are C-style structure defined by Microsoft.

OpenSSL is a nice tool to convert the keys from one format to another. Here are some examples:

#convert private key from PEM to DER
openssl.exe rsa -inform PEM -in test.pem -outform DER -out test.der
#convert private key from DER to PEM
openssl.exe rsa -inform DER -in test.DER -outform PEM -out test1.pem
#convert public key from PEM to DER
openssl.exe rsa -inform  PEM -pubin  -in testPub.pem -outform DER -out testPub.der
#convert public key from DER to PEM
openssl.exe rsa -inform  DER -pubin  -in testPub.der -outform PEM -out testPub.pem
#convert public key from PEM to PUBLICKEYBLOB
openssl.exe rsa -inform  "PEM" -pubin  -in testPub.pem -outform "MS\ PUBLICKEYBLOB" -out testPub.pblob
#convert private key from PEM to PRIVATEKEYBLOB
openssl.exe rsa -inform  "PEM"   -in test.pem -outform "MS\ PRIVATEKEYBLOB" -out test.pblob

Here is a python script to convert keys from PEM to DER format:
import base64
fileName="c:\\temp\\testPub.pem"
fileContent=""
with open(fileName, 'r') as f:
    fileContent=f.readlines()
fileContent.pop()
fileContent.pop(0)
s=''.join(fileContent)
s=s.replace('\n','')
data =base64.b64decode(s)
print data.encode('hex')