SoFunction
Updated on 2024-11-18

Example of reading public and private keys for encryption and decryption in python.

Example of reading public and private keys for encryption and decryption in python.

In RSA there is an application mode is public key encryption, private key decryption (another is private key signature, public key signature verification). The following is an example of an application in Python.

Suppose I have a public key file, rsa_pub.pem, and I want to read this public key and use it for encryption.

from M2Crypto import RSA,BIO

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

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

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

  ...

Private key file rsa_private.pem, read private key and use 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);

Thanks for reading, I hope this helps, and thanks for supporting this site!