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

后端 未结 7 1065
孤街浪徒
孤街浪徒 2020-12-28 10:06

The RSA public key:

pubkey = \'MIGfMA0GCSqGSIb3DQEBA3UAA4GNADCBiQKBgQC35eMaYoJXEoJt5HxarHkzDBEMU3qIWE0HSQ77CwP/8UbX07W2XKwngUyY4k6Hl2M/n9TOZMZsiBzer/fqV+QNPN1m9M94eU

相关标签:
7条回答
  • 2020-12-28 11:00

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

    1. 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
      
    2. 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.

    0 讨论(0)
提交回复
热议问题