Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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.

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
                A good answer will always have an explanation of what was done and why it was done in such a manner, not only for the OP but for future visitors to SO. Please add some description to make others understand. :)
– Rucha Bhatt Joshi
                Sep 22, 2017 at 3:57
                I am getting in keyPub = RSA.importKey(keyDER) -> RSA.py:588 -> ValueError: RSA key format is not supported
– Dima Lituiev
                Dec 15, 2017 at 19:36
                If you're getting the "RSA key format not supported", you might have to skip the part where it does the b64decode.
– Yeahprettymuch
                Oct 27, 2021 at 16:59
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)
                This issues an error: /usr/local/lib/python3.6/site-packages/Crypto/PublicKey/RSA.py in encrypt(self, plaintext, K) --> 372 NotImplementedError: Use module Crypto.Cipher.PKCS1_OAEP instead
– Dima Lituiev
                Dec 15, 2017 at 19:26
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAybVqRvfYvWbLsB98BqkD
lWd0/5y6SyhHt6/r6M0l7JXBweqMvxVt7XmI2yqPL56YxzcgQ8ycDkoqHJ+XozgP
iRnLNpYRlCzsiaOElbmQcnrI8iOb9Ahm6j0cbBB1S8VNvD+u9RQJt53zPxPj8/Dq
f1oNGFXOM8udNYWZaRCukLs/TumsAn0a+BF4639WtFiUvTWdVhlyvCQTs49ytRkH
rXH30RkB528RIvTGeW8xBTV4NaiTIzAEKCVSPagLr4Hzbb9b5+bODic/zkLGQazy
/NKOFgiB7kD2+WEMcuhTr5noeXau0PDAhgmrBhzzWOjUwwaO+ACvJLkPXZfjhy7P
+wIDAQAB
-----END PUBLIC KEY-----

You shouldn't b64decode the externKey and the string should start with "-----BEGIN PUBLIC KEY-----" and "-----END PUBLIC KEY-----".

Works for me after adding -----BEGIN PUBLIC KEY----- and -----END PUBLIC KEY----- and should read key from file, str is not working – Cloud Jan 8, 2017 at 8:20
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_PKCS1_v1_5
def encrypt_data(data):
    with open("/path/to/public.pem", "rb") as k:
        key = RSA.importKey(k.read())
    cipher = Cipher_PKCS1_v1_5.new(key)
    return cipher.encrypt(data.encode())
def decrypt_data(data):
    with open("path/to/private.pem", "rb") as k:
        key = RSA.importKey(k.read())
    decipher = Cipher_PKCS1_v1_5.new(key)
    return decipher.decrypt(data, None).decode()
message = "hello world!"
encrypted = encrypt_data(message)
decrypted = decrypt_data(message)
                This was the first method that I tried, it would raise "ValueError: RSA key format is not supported".  Then I tried the method (from stackoverflow.com/questions/10569189/…) in my question, it doesn't work either.
– Romstar
                Jan 26, 2014 at 3:31

my env: win10x64 python3.6.4 pycrypto2.6.1

here's my code, encrypt end decrypt, the key was from someone's blog.(if U occured with "ValueError: RSA key format is not supported", check the key format, it should be warpped with some thing like "-----BEGIN XXXX KEY-----")

pubkey = """-----BEGIN PUBLIC KEY-----
-----END PUBLIC KEY-----"""
prvkey = """-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----"""
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_PKCS1_v1_5
msg = "test"
print("raw msg->", msg)
keyPub = RSA.importKey(pubkey) # import the public key
cipher = Cipher_PKCS1_v1_5.new(keyPub)
#print(cipher.encrypt.__doc__)
cipher_text = cipher.encrypt(msg.encode()) # now we have the cipher
print("cipher text->", cipher_text)
keyPriv = RSA.importKey(prvkey) # import the private key
cipher = Cipher_PKCS1_v1_5.new(keyPriv)
#print(cipher.decrypt.__doc__)
decrypt_text = cipher.decrypt(cipher_text, None).decode()
print("decrypted msg->", decrypt_text)
assert msg == decrypt_text # check that
print("test passed")

the output:

raw msg-> test
cipher text-> b'\xb0]\x1f@B\x8b\xb5\xbf\x891:\t4D\x80$\xc0y\xaa\xb4\x86t/|\xeaM%\xf06\x14,\x9e?\x86R\x83\xd72\xe5\xfdsr:\x99\xe7v\xd9]&\xbc\x85\xd3\x16\x80\x19q\xe7\xb1\x89\xff/\x12\xe5\xb3\x9cu\x1f\x04x\xa5\xdfl\xcd\xae_\xba\x1b\x97\x9fa\xcf9O\xbfB\xf6\xd1N\xf5|<\xbf^\x84R\xecSo\x9a*\xf7\x8d\x8e\xbe0Q\xcd\x14\x13\xf98x\xe7\xd8x\x19\xaf\x98\xefu\xa8\xb1\xd3\xfa\xf2N\xca\xb5'
decrypted msg-> test
test passed

If you want to import an external key using RSA.importkey( ), you have two options:

  • Read key from file:

     file = open('external.pem','r')
     external_key = file.read()
     key = RSA.import_key(external_key)
    

    and your external key format must be something like this:

     -----BEGIN PUBLIC KEY-----
     MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsDcmhF1kqsMw9HAUc231
     IEr3OwVwocSM4JPUGVSTBDcM9tGoflx8UoN4M9EJrdCcVicZEt709L13jhUxo/hX
     jUDqyQ6U+zyOYhoSwQpHKju2bwn6HMC8iq/ZwNqRFiqa23O2L8WSjZq4J/U1wWZ9
     Zh7f0E5w8GZDkngceQI8nBWFPSAeQNAh0b4Vy1SYKapPrvUJdS9LsT3V9B2k2Nm1
     4lUOtfufpWP5xjoC3MwOxgBsPJsuqpe7sZddG4YzQi3IuMAcc+C/ms9mA7OX5yxt
     xgU3tAIzzBHgvwn9vANNJPzJMaOcm9kKMVJYXLHfg37IfIk1oV+/3BxMQ26ErNcC
     9wIDAQAB
     -----END PUBLIC KEY-----
    

    In Linux (I don't know about Windows) you can check it by this command:

     less exteralkey.pem
    
  • If you wanna hardcode your key into your code, your key must be like this:

     pubkey = "-----BEGIN PUBLIC KEY-----\n\
     MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsDcmhF1kqsMw9HAUc231\n\
     IEr3OwVwocSM4JPUGVSTBDcM9tGoflx8UoN4M9EJrdCcVicZEt709L13jhUxo/hX\n\
     jUDqyQ6U+zyOYhoSwQpHKju2bwn6HMC8iq/ZwNqRFiqa23O2L8WSjZq4J/U1wWZ9\n\
     Zh7f0E5w8GZDkngceQI8nBWFPSAeQNAh0b4Vy1SYKapPrvUJdS9LsT3V9B2k2Nm1\n\
     4lUOtfufpWP5xjoC3MwOxgBsPJsuqpe7sZddG4YzQi3IuMAcc+C/ms9mA7OX5yxt\n\
     xgU3tAIzzBHgvwn9vANNJPzJMaOcm9kKMVJYXLHfg37IfIk1oV+/3BxMQ26ErNcC\n\
     9wIDAQAB\n\
     -----END PUBLIC KEY-----"
    

    then you can import it:

     key = RSA.importkey(pubkey)
    

    Note: if you do not add "\n" to the end of each line of your RSA key the RSA.importkey( ) will raise an error:

    RSA key format is not supported

    Note 2: I used "\" to indicate that statement is continued on the next line.

    Please, avoid using "SMS language" (u, ur idk) in Stoack Overflow answers. The require a minimum quality level. I've edited it. – Roberto Caboni Jul 31, 2020 at 11:49

    ubuntu@ubuntu:~$ sudo pip3 list|grep crypto

    cryptography 2.8

    cryptography-vectors 2.8

    pycrypto 2.6.1

    from Crypto.PublicKey import RSA
    from Crypto.Cipher import PKCS1_v1_5 as Cipher_PKCS1_v1_5
    def encrypt_data(data):
        with open("/home/echague/.ssh/id_rsa.pub", "rb") as k:
            key_pub = RSA.importKey(k.read())
        cipher = Cipher_PKCS1_v1_5.new(key_pub)
        return cipher.encrypt(data.encode())
    def decrypt_data(data):
        with open("/home/echague/.ssh/id_rsa", "rb") as k:
            key_priv = RSA.importKey(k.read())
        decipher = Cipher_PKCS1_v1_5.new(key_priv)
        return decipher.decrypt(data, None).decode()
    message = "hello world!"
    encrypted = encrypt_data(message)
    decrypted = decrypt_data(encrypted)
    print(message)
    print(encrypted)
    print(decrypted)
                    Would you please be able to improve your answer by adding some comments to it explaining what it does?
    – pfabri
                    Oct 26, 2021 at 9:12
            

    Thanks for contributing an answer to Stack Overflow!

    • Please be sure to answer the question. Provide details and share your research!

    But avoid

    • Asking for help, clarification, or responding to other answers.
    • Making statements based on opinion; back them up with references or personal experience.

    To learn more, see our tips on writing great answers.

  •