Search code examples
pythonencodinghexrsapycrypto

python convert RSA key (in PEM format) to hex string


I would like to convert my RSA keys to a hex string, but am unsure on how to do this.

I generate my keys like this:

def generate_RSA(self, bits=1024):
        new_key = RSA.generate(bits, e=65537)
        self.public_key = new_key.publickey().exportKey("PEM")
        public_key_file = open('public_key.key', 'w')
        public_key_file.write(self.public_key)
        public_key_file.close()

        self.private_key = new_key.exportKey("PEM")
        private_key_file = open('private_key.key', 'w')
        private_key_file.write(self.private_key)
        private_key_file.close()

This gives for example

-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCqMROLBpbqrHi4WC4XAElMXoNh 0EMODB763pcTiwpOLc72K8DqQ48BuVwKXit9uvWz1pth/2aJfXZuX2awQEPCmeUe XtDca/ljksnq/3xo7Ph0/zoeKyJbLziLYjOgn22rxtJ9cVV7kFFm2whxFAGP0h6N QcFrMSUaRA2x2riQNwIDAQAB -----END PUBLIC KEY-----

Which is fine, but I would like to (1) strip the header and footer of the PEM file and (2) send the RSA key in hex form, basically a string like this (random):

00a9e885395f47d47a9b58560d3f14254efa0692464756f9c0b7a046f328674a1951e1d008679d44e556bea3c747ae485e41ab0f9b24ab9cca99b8097a03e1c0e5455b983f432e5f02d6a87ba27af412efae3db9e219e9dc2627a74c1840b85048e251cee2b1abcbabf7c41de7bb5091c68ac1ac7d91f48afcea1c4bf6683c4011

How can I achieve this?


Solution

  • What you probably need is a DER encoded, I really don't know much about Python but you could probably use something like

    new_key.publickey().exportKey("DER")
    

    which would give you a DER encoded key, binary format most likely, what you do afterwards is transform that binary to hex and there you go.