【问题标题】:How to convert bytes to string for encrypting? [duplicate]如何将字节转换为字符串进行加密? [复制]
【发布时间】:2021-06-07 09:44:57
【问题描述】:

我正在使用cryptography.fernet 加密文本文件,然后使用write 函数将其写入我的文件中,但我收到错误write() argument must be a str not a byte。代码如下:

from cryptography.fernet import Fernet

message = open("D:/raaghav/code/os/user/password.txt", mode='w')
messageR = open("D:/raaghav/code/os/user/password.txt", mode='r')
messageRe= messageR.read()

key = Fernet.generate_key()

fernet = Fernet(key)

encMessage = fernet.encrypt(messageRe.encode())

message.write(encMessage)

print("original string: ", message)
print('encrypted message: ', encMessage)

【问题讨论】:

  • str(encMessage) 可能会有所帮助。只需将其替换为您写入文件的位置
  • "wb"模式打开文件进行写入。另外:使用with 在写入之前关闭您正在读取的文件。基本上:1.打开 2.读取 3.关闭 4.打开 5.写入 6.关闭
  • @Sujay 这真的行不通。 str(b'hello') 不会给你字符串"hello" 它会给你"b'hello'",包括b 和嵌入的引号。通过decode 成员函数转换为字符串。
  • 在您还指定编码之前,字节不会直接对应于文本。在纯 7 位 ASCII 文本的情况下,这种映射是微不足道的;但是对于其他任何事情,您确实需要知道文本编码。
  • @tripleee:但是对于加密和解密,我们甚至可以将文本文件作为二进制数据读取,不是吗?加密也适用于二进制文件。无需知道编码。

标签: python python-cryptography


【解决方案1】:

您的输出可以是 utf-8 编码,因此encMessage.decode('utf8') 会将您的字节对象转换为字符串。

保存原始二进制数据(字节对象本身)也可以通过将文件模式更改为'wb'来完成。

【讨论】:

  • 您是如何得知这是 UTF-8 编码的信息?
  • 指定它可以为utf-8编码。输出采用 base-64 编码(参见官方 doc),因此可以采用 utf-8 编码。
  • @Seon:任意二进制字符串是有效的latin1,它总是可以解码为 Unicode,然后再次编码回原始字符串(正如answer 中指出的类似问题)。
  • 很高兴知道,感谢您的提示!
【解决方案2】:
str = "sample text"
byteobj = str.encode('utf-8')
print(type(byteobj)) # this the byt from the above text
retStr = byteobj.decode('utf-8')
print(retStr) # this the string changed from string from bytes

【讨论】:

  • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
猜你喜欢
  • 1970-01-01
  • 2021-12-20
  • 2021-11-17
  • 2017-11-12
  • 1970-01-01
  • 1970-01-01
  • 2010-09-24
  • 2011-02-27
相关资源
最近更新 更多