Search code examples
pythonrsaprivate-keypycryptom2crypto

Printing .pem key DER form in python


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.


Solution

  • I would do this:

    from Crypto.PublicKey import RSA
    
    key = RSA.importKey(open("privatekey.pem").read())
    der = key.publickey().exportKey("DER")