【问题标题】:How to fix encoding without a string argument when encrypting files?加密文件时如何在没有字符串参数的情况下修复编码?
【发布时间】: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


【解决方案1】:

错误消息中指出了问题的原因:您提供给bytes()text(实际上是file_content)不是str(它已经是bytes 类型从您使用'rb' 阅读的方式来看)。

尝试删除bytes(),它应该可以工作:

res = base64.encode(aes.encrypt(pad(text, AES.block_size)))

【讨论】:

    猜你喜欢
    • 2011-05-18
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多