[英]"TypeError: Object type <class 'str'> cannot be passed to C code when encrypting an image
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 TypeError: Object 类型 <class 'str'> 无法传递给 C 代码
I will really appreciate any help on how to fix this error, I'm a beginner in using python.我将非常感谢有关如何解决此错误的任何帮助,我是使用 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.附带说明:尝试在 ECB 模式下加密BMP
图像,看看为什么在 ECB 模式下使用加密不好。
# deleted non needed imports
from PIL import Image
import os
from Crypto.Cipher import AES
Block_size = 16
IV_size = 16
def encrypt_file(input_file,output_file,cipher_mode):
# use function input file name not a fixed one
input_img = Image.open(input_file)
# must be in bytes
key = b"770A8A65DA156D24EE2A093277530142"
if cipher_mode=='CBC':
mode = AES.MODE_CBC
else:
mode = AES.MODE_CFB
iv = os.urandom(IV_size)
aes = AES.new(key, mode, iv)
img_str = input_img.tobytes()
# To get padding needed use mod operator
img_pad_lenght = Block_size - (len(img_str) % Block_size)
# Add padding of null bytes
img_str += img_pad_lenght * b"\0"
print(len(img_str))
# There is no built in encode function in python encode is a string method
# must be applied to a string
encrypted_img_str = aes.encrypt(img_str)
encrypted_img = Image.frombuffer('RGB', input_img.size, encrypted_img_str, 'raw', 'RGB', 0, 1)
encrypted_img.save(output_file, 'PNG')
# there is no variable as outputfilename only output_file
print("Encrypted using AES in " + cipher_mode + " mode and saved to \"" + output_file + "\"!")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.