Using pycrypto, how to import a RSA public key and use it to encrypt a string?

user21916 picture user21916 · Jan 24, 2014 · Viewed 72.4k times · Source

The RSA public key:

pubkey = 'MIGfMA0GCSqGSIb3DQEBA3UAA4GNADCBiQKBgQC35eMaYoJXEoJt5HxarHkzDBEMU3qIWE0HSQ77CwP/8UbX07W2XKwngUyY4k6Hl2M/n9TOZMZsiBzer/fqV+QNPN1m9M94eUm2gQgwkoRj5battRCaNJK/23GGpCsTQatJN8PZBhJBb2Vlsvw5lFrSdMT1R7vaz+2EeNR/FitFXwIDAQAB'

how to import it and use it to encrypt a string?

I tried the following code but RSA.construct() raises exception (TypeError: must be long, not str).

from Crypto.PublicKey import RSA
from Crypto.Util import asn1
from base64 import b64decode

keyDER = b64decode(pubkey)
seq = asn1.DerSequence()
seq.decode(keyDER)
keyPub = RSA.construct((seq[0], seq[1]))
print keyPub.encrypt('mysecret', 32)

Thanks.

Answer

Chet picture Chet · Nov 18, 2014

I too had trouble with this. I got it working like this:

key = RSA.generate(2048)

binPrivKey = key.exportKey('DER')
binPubKey =  key.publickey().exportKey('DER')

privKeyObj = RSA.importKey(binPrivKey)
pubKeyObj =  RSA.importKey(binPubKey)

msg = "attack at dawn"
emsg = pubKeyObj.encrypt(msg, 'x')[0]
dmsg = privKeyObj.decrypt(emsg)

assert(msg == dmsg)

If you're writing to files, you may find it easier to deal with hex strings instead of binary strings. I'm using these helper functions a lot

def bin2hex(binStr):
    return binascii.hexlify(binStr)

def hex2bin(hexStr):
    return binascii.unhexlify(hexStr)