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.

258 Chapter 9 ■ Mastering Cryptography Using Python

Modifying the Helper File

The helper file will be growing quite a bit now. In addition to using it to create

the private and public key files, we also use it for reading the key files and

performing our encryption and decryption process. You’ve seen code examples

of this in a number of chapters, but if you would like to review the topic again,

check out Chapter 5.

PyCrypto is being used in this example to expose the PKCS1_OAEP module.

The only difference between the encryption and decryption methods is the use

of specific keys:

# Chat Encryption Helper - ch9_crypto_chat.py

import os, base64, json

from Crypto.Cipher import PKCS1_OAEP, AES

from Crypto.PublicKey import RSA, ECC

from binascii import hexlify, unhexlify

from base64 import b64encode, b64decode

# encryption method used by all calls

def encrypt(message, usePKI, useDH, dhSecret):

if usePKI == True:

message = encrypt_rsa(message)

return message

# decryption method used by all calls

def ch9_decrypt(message, usePKI, useDH, dhSecret):

if usePKI == True:

message = ch9_decrypt_rsa(message)

return message

# generate RSA certs

def gen_rsa_certs():

#ch8_Generate_RSA_Certs.py

from Crypto.PublicKey import RSA

#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")

fd = open("client_private_key.pem", "wb")

fd.write(private_key)

fd.close()

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

Saved successfully!

Ooh no, something went wrong!