1

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.

4
  • Is your key encrypted? (You can check by opening the file in a text editor) Commented Feb 11, 2014 at 18:35
  • It's not. It looks like -----BEGIN PRIVATE KEY----SOME BASE 64 ENCODED TEXT-----END PRIVATE KEY----- Commented Feb 11, 2014 at 18:37
  • Have you tried save_key_der? Commented Feb 11, 2014 at 18:54
  • Yeah, that does the same thing as save_key_der_bio, but to a file. The contents of that file are the same as when I save to a bio and read that bio. Commented Feb 11, 2014 at 18:57

2 Answers 2

4

I would do this:

from Crypto.PublicKey import RSA

key = RSA.importKey(open("privatekey.pem").read())
der = key.publickey().exportKey("DER")
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, much simpler than my answer. Thanks!
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.