07.07.2023 Views

Implementing-cryptography-using-python

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 8 ■ Cryptographic Applications and PKI 231

Constructing Simple Text Encryption and

Decryption with RSA Certificates

In the next code listing, we’ll use the RSA certificates we created in the previous

section to encrypt and decrypt a simple message: To be encrypted. The module

uses the RSA encryption protocol according to PKCS#1 OAEP, and the scheme

is more properly known as RSAES-OAEP. At the receiver side, decryption can

be done using the private part of the RSA key:

from Crypto.Cipher import PKCS1_OAEP

from Crypto.PublicKey import RSA

message = b'To be encrypted'

key = RSA.importKey(open('public_key.pem').read())

cipher = PKCS1_OAEP.new(key)

ciphertext = cipher.encrypt(message)

print (ciphertext)

key = RSA.importKey(open('private_key.pem').read())

cipher = PKCS1_OAEP.new(key)

plaintext = cipher.decrypt(ciphertext)

print (plaintext)

Figure 8.3 shows the results of the previous code. The message entered is “To

be encrypted.” You will see the RSA encrypted output followed by the decryption

back to plaintext.

Figure 8.3: RSA decrypt

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!