I am trying to encrypt an image file, but when I try to execute my code, I get the error:
TypeError: Object type <class 'str'> cannot be passed to C code
I will really appreciate any help on how to fix this error, I'm a beginner in using python.
Here is my code:
from PIL import Image
#from PIL.Image import core as image
import os
import sys
from Crypto.Cipher import AES
Block_size=16
IV_size=16
def encrypt_file(input_file,output_file,cipher_mode):
input_img=Image.open('/content/Linux-icon.png')
key="770A8A65DA156D24EE2A093277530142"
if cipher_mode=='CBC':
mode=AES.MODE_CBC
#elif cipher_mode=='CBC':
# mode=AES.MODE_CBC
else:
mode=AES.MODE_CFB
i=os.urandom(IV_size)
aes=AES.new(key,mode,i)
img_str=input_img.tostring()
#Pad the image string to the input block size
img_pad_lenght=Block_size-len(img_str)/Block_size
img_str+=img_pad_lenght*"~"
#generate the encrypted image string
encrypted_img_str=aes.encrypt(encode(img_str))
#create an image from the encrypted string
encrypted_img=Image.frombuffer('RGB',input_img.size, encrypted_img_str,'raw','RGB',0,1)
#create and save the output image
encrypted_img.save('/content/Linux-icon1.png','PNG')
print("Encrypted using AES in " + cipher_mode + " mode and saved to \"" + output_filename + "\"!")
Thanks in advance
Your code have some issues read the code comments. As a side note: try to encrypt
BMP
images in ECB mode to see why it's bad to use encryption in ECB mode.