Read the public and private keys under python to do encryption and decryption example details

  • 2020-05-27 06:05:51
  • OfStack

Read the public and private keys under python to do encryption and decryption example details

One application mode in RSA is public key encryption and private key decryption (the other is private key signature and public key check). The following is an example of an application under Python.

So let's say I have a public key file, rsa_pub.pem, and I'm going to read the public key and encrypt it.


from M2Crypto import RSA,BIO

  fp = file('rsa_pub.pem','rb');
  pub_key_str = fp.read();
  fp.close();

  mb = BIO.MemoryBuffer(pub_key_str);
  pub_key = RSA.load_pub_key_bio(mb);

  data = '12345678';
  en_data = pub_key.public_encrypt(data,RSA.pkcs1_padding);

  ...

The private key file rsa_private.pem reads the private key and USES it for decryption


from M2Crypto import RSA,BIO

  private_key_str = file('rsa_private.pem','rb').read();
  private_key = RSA.load_key_string(private_key_str);
  data = 'sdfdjslfjaskldfjdsklfjsd';
  de_data = private_key.private_decrypt(data,RSA.pkcs1_padding);

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: