Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 741
user21916 Avatar asked Jan 24 '14 08:01

user21916


People also ask

How do I import my RSA key?

Importing an RSA Key Container You can use the Aspnet_regiis.exe tool with the –pi switch to import an RSA key container from an XML file. You must also specify whether the imported key container is a machine-level or user-level key container.

How do I use Pycrypto in Python?

For local Python files on your system, you can place the code in a . py file and the paths to local modules are provided in the paths: key in the <py-env> tag. Then the Python file will be imported into the HTML with the <py-env> tag. You should place this tag in the the <head> tag, above the <body> tag.


2 Answers

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_PKCS1_v1_5
from base64 import b64decode,b64encode

pubkey = 'MIGfMA0GCSqGSIb3DQEBA3UAA4GNADCBiQKBgQC35eMaYoJXEoJt5HxarHkzDBEMU3qIWE0HSQ77CwP/8UbX07W2XKwngUyY4k6Hl2M/n9TOZMZsiBzer/fqV+QNPN1m9M94eUm2gQgwkoRj5battRCaNJK/23GGpCsTQatJN8PZBhJBb2Vlsvw5lFrSdMT1R7vaz+2EeNR/FitFXwIDAQAB'
msg = "test"
keyDER = b64decode(pubkey)
keyPub = RSA.importKey(keyDER)
cipher = Cipher_PKCS1_v1_5.new(keyPub)
cipher_text = cipher.encrypt(msg.encode())
emsg = b64encode(cipher_text)
print emsg
like image 110
user9527 Avatar answered Oct 17 '22 14:10

user9527


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)
like image 17
Chet Avatar answered Oct 17 '22 14:10

Chet