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 233

#compress the data first

blob = zlib.compress(blob)

#In determining the chunk size, determine the private key length

used in bytes

#and subtract 42 bytes (when using PKCS1_OAEP). The data will be

encrypted

#in chunks

chunk_size = 470

offset = 0

end_loop = False

encrypted = bytearray()

while not end_loop:

#The chunk

chunk = blob[offset:offset + chunk_size]

add

file

#If the data chunk is less than the chunk size, then we need to

#padding with " ". This indicates that we reached the end of the

#so we end loop here

if len(chunk) % chunk_size != 0:

end_loop = True

#chunk += b" " * (chunk_size - len(chunk))

chunk += bytes(chunk_size - len(chunk))

#Append the encrypted chunk to the overall encrypted file

encrypted += rsa_key.encrypt(chunk)

#Increase the offset by chunk size

offset += chunk_size

#Base 64 encode the encrypted file

return base64.b64encode(encrypted)

# RSA Decryption Function

def decrypt_blob(encrypted_blob, private_key):

# Import the private key and use for decryption using PKCS1_OAEP

rsakey = RSA.importKey(private_key)

rsakey = PKCS1_OAEP.new(rsakey)

# Base 64 decode the data

encrypted_blob = base64.b64decode(encrypted_blob)

# In determining the chunk size, determine the private key length

used in bytes.

# The data will be decrypted in chunks

chunk_size = 512

offset = 0

decrypted = bytearray()

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

Saved successfully!

Ooh no, something went wrong!