【发布时间】:2021-07-08 04:52:09
【问题描述】:
我需要压缩一个文件,在不解压的情况下读取文件内容并加密内容。
样本文件*
Hello,Encrypt me!
Python
import gzip
import shutil
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
#Compressing file
with open('SampleFile','rb') as f_in:
with opne('SampleFile.gz','wb') as f_out:
with gzip.GzipFile('SampleFile','wb',fileobj=f_out) as f_out:
shutil.copyfileobj(f_in,f_out)
#Reading Contents
file_rd = gzip.open("SampleFile.gz","rb")
file_content = file_rd.read()
print(file_content)
print(type(file_content))
#Encryption
def encrypt(key,iv,text):
try:
print("Inside encryption")
aes = AES.new(key = base64.decode(bytes(key,'utf-8')), mode = AES.MODE_CBC, IV=base64.decode(bytes(iv,'utf-8')))
res = base64.encode(aes.encrypt(pad(bytes(text,'utf-8'),AES.block_size)))
return res
except Exception as e:
print(e)
return None
key ="##Mykey##"
iv = "##Myiv##"
encryption = encrypt(key,iv,file_content)
print(encryption)
加密时,它给我一个错误 TypeError:encoding without a string argument 我在网上查了一下,发现了大部分与字节相关的答案(编码是字节函数的参数)。 我什至尝试过:
file_content = bytes(file_content,encoding = 'utf-8')
我该如何解决这个问题? 提前致谢。
【问题讨论】:
-
您能否提供更详细的错误信息?
-
``` 错误:res = base64.encode(aes.encrypt(pad(bytes(text,'utf-8'),AES.block_size))) 类型错误:没有字符串参数的编码` `` 这是完整的错误信息。 @Karl Knechtel @R。马罗拉希
标签: python file encryption byte aes