Created
December 21, 2017 16:47
-
-
Save ismailakkila/3a351fe9baff14d0a35dd6a4ca8b72ec to your computer and use it in GitHub Desktop.
ch9_encrypt_blob.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ch9_encrypt_blob.py | |
from Crypto.PublicKey import RSA | |
from Crypto.Cipher import PKCS1_OAEP | |
import zlib | |
import base64 | |
#Our 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) | |
#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 in encrypted | |
#in chunks | |
chunk_size = 470 | |
offset = 0 | |
end_loop = False | |
encrypted = "" | |
while not end_loop: | |
#The chunk | |
chunk = blob[offset:offset + chunk_size] | |
#If the data chunk is less then the chunk size, then we need to add | |
#padding with " ". This indicates the we reached the end of the file | |
#so we end loop here | |
if len(chunk) % chunk_size != 0: | |
end_loop = True | |
chunk += " " * (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) | |
#Use the public key for encryption | |
fd = open("public_key.pem", "rb") | |
public_key = fd.read() | |
fd.close() | |
#Our candidate file to be encrypted | |
fd = open("img.jpg", "rb") | |
unencrypted_blob = fd.read() | |
fd.close() | |
encrypted_blob = encrypt_blob(unencrypted_blob, public_key) | |
#Write the encrypted contents to a file | |
fd = open("encrypted_img.jpg", "wb") | |
fd.write(encrypted_blob) | |
fd.close() |
If for some reason it would be relevant for others in the future... In Python3 you cannot convert bytes object to str implicitly.
So basically to solve that error about "concatenate str (not "bytes") to str", you must declare the variables as bytes
- encrypted = b""
- chunk += b" " * (chunk_size - len(chunk))
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Any idea to solve this error