Reputation: 5446
I would like to print out the binary form (not sure if this is how I would refer to it) of a .pem key using python. To clarify, I want to do in python what this unix command would print out:
cat privateKey.pem | openssl rsa -pubout -outform DER
I can't just call this command using subprocess because I want it to work on Windows. I've looked at the M2Crypto and PyCrypto libraries, and with the M2Crypto library I am able to load the key using
from M2Crypto import RSA
rsaKey = RSA.load_key('privateKey.pem')
But I don't see any methods of rsaKey that print out the binary form.
Edit:
Here's what I have so far:
import M2Crypto
key = M2Crypto.RSA.load_key('key.pem')
bio = M2Crypto.BIO.MemoryBuffer()
key.save_key_der_bio(bio)
der = bio.read()
But der
isn't the same as what openssl printed out. I piped the output of openssl into hexdump to compare them.
Upvotes: 1
Views: 5361
Reputation: 7786
I would do this:
from Crypto.PublicKey import RSA
key = RSA.importKey(open("privatekey.pem").read())
der = key.publickey().exportKey("DER")
Upvotes: 4
Reputation: 5446
I figured it out. So the unix command
cat privateKey.pem | openssl rsa -pubout -outform DER
Is actually printing out the DER form of the public key. Here is what I had to do, using the M2Crypto library:
import M2Crypto
privatekey = M2Crypto.RSA.load_key('privatekey.pem')
bio = M2Crypto.BIO.MemoryBuffer()
privatekey.save_pub_key_bio(bio)
pubkey = bio.read()
pubkey = ''.join(pubkey.split('\n')[1:-2]) # remove -----BEGIN PUB KEY... lines and concatenate
der = base64.b64decode(pubkey)
This is the form that I wanted. For some reason, if I did
pubkey = M2Crypto.RSA.load_pub_key_bio(bio)
pubkey.save_key_der_bio(bio)
der = bio.read()
It gave me the wrong answer.
Upvotes: 1