07.07.2023 Views

Implementing-cryptography-using-python

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

232 Chapter 8 ■ Cryptographic Applications and PKI

If you try to encrypt larger messages, you will get an exception because the

key length limits the maximum message length. In the next section, we will

craft a more robust solution using the same concepts we just applied. Our next

recipe will demonstrate how to encrypt and decrypt a wide variety of data

using the PKI infrastructure.

Constructing BLOB Encryption and

Decryption with RSA Certificates

In the previous section, you were able to encrypt and decrypt data using a PKI

infrastructure, but the size of the message was limited. Examine the following

Python demo, which will take an image and encrypt it using RSA and then

decrypt it. It works with larger amounts of data by encrypting the image in

key-size chunks. The resulting code will produce both an encrypted image and

a decrypted image that should match the original:

#ch8_RSA_blob.py

import zlib

import base64

from Crypto.PublicKey import RSA

from Crypto.Cipher import PKCS1_OAEP

from pathlib import Path

# Generate new key pair function

def generate_new_key_pair():

# Generate a public/private key pair using 4096 bits key length

(512 bytes)

new_key = RSA.generate(4096, e=65537)

# The private key in PEM format

private_key = new_key.exportKey("PEM")

# The public key in PEM Format

public_key = new_key.publickey().exportKey("PEM")

private_key_path = Path('private.pem')

private_key_path.touch(mode=0o600)

private_key_path.write_bytes(private_key)

public_key_path = Path('public.pem')

public_key_path.touch(mode=0o664)

public_key_path.write_bytes(public_key)

# RSA Encryption Function

def encrypt_blob(blob, public_key):

#Import the public key and use for encryption using PKCS1_OAEP

rsa_key = RSA.importKey(public_key)

rsa_key = PKCS1_OAEP.new(rsa_key)

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

Saved successfully!

Ooh no, something went wrong!