python - 为什么我在读取字节时会得到一个额外的 b 前缀?
问题描述
我正在尝试使用以下代码读取包含字节格式密文的外部文件的内容:
import pyaes
def decryption_method():
key = 'storochkraftfullsverige'
# the problem comes here
with open('encrypted.txt', 'rb') as f:
ciphertext = f.read()
print(type(ciphertext)) # this indicates that the variable is of type bytes
key = key.encode('utf-8')
aes = pyaes.AESModeOfOperationCTR(key)
decrypted = aes.decrypt(ciphertext).decode('utf-8')
return decrypted
但是,在读取外部文件时,我得到以下结果:
b"b'a`_\xc1\x9f\xd4J\xdc\xcd'"
代替
b'a`_\xc1\x9f\xd4J\xdc\xcd'
我的问题是:
- 为什么我在读取外部文件时会得到额外的前缀?如果没有额外的前缀,我怎么能读取文件?
- 有没有办法只选择我想要的字节,然后将它们附加到 BytesArray 对象中?
任何建议或进一步澄清都受到好评:)
如果您想做自己的测试,您可以使用以下代码在 Python 3.x 中使用 AES 进行加密和解密
import pyaes
key = "Your key file that will be used to encrypt and decrypt."
plaintext = "This text will be encrypted and decrypted."
# key must be bytes, so we convert it
key = key.encode('utf-8')
aes = pyaes.AESModeOfOperationCTR(key)
ciphertext = aes.encrypt(plaintext)
# show the encrypted data
print (ciphertext)
# DECRYPTION
aes = pyaes.AESModeOfOperationCTR(key)
# decrypted data is always binary, need to decode to plaintext
decrypted = aes.decrypt(ciphertext).decode('utf-8')
# True
print (decrypted == plaintext)
解决方案
如果无法访问您正在使用的确切文件,很难说,但这可能是文件内容的问题。
使用您的示例,我对其进行了修改,以便它可以写出一个密文文件(作为原始字节)并将其读入(作为原始字节)。
import pyaes
# Key length was invalid, so I changed it
key = 'This_key_for_demo_purposes_only!'
plaintext = "This text will be encrypted and decrypted."
# key must be bytes, so we convert it
key = key.encode('utf-8')
aes = pyaes.AESModeOfOperationCTR(key)
ciphertext = aes.encrypt(plaintext)
# show the encrypted data
print (ciphertext)
# Write out raw bytes to file
with open('ciphertext.txt', 'wb') as file_out:
file_out.write(ciphertext)
ciphertext = None
print(ciphertext)
# Read in raw bytes from file
with open('ciphertext.txt', 'rb') as file_in:
ciphertext = file_in.read()
print(ciphertext)
# DECRYPTION
aes = pyaes.AESModeOfOperationCTR(key)
# decrypted data is always binary, need to decode to plaintext
decrypted = aes.decrypt(ciphertext).decode('utf-8')
# True
print (decrypted == plaintext)
然后,使用decryption_method()
我能够解密密文文件:
import pyaes
def decryption_method():
# The key length was invalid, so I used a different one for this example.
key = 'This_key_for_demo_purposes_only!'
with open('ciphertext.txt', 'rb') as f:
ciphertext = f.read()
key = key.encode('utf-8')
aes = pyaes.AESModeOfOperationCTR(key)
decrypted = aes.decrypt(ciphertext).decode('utf-8')
return decrypted
print(decryption_method())
这会在我的机器上按预期输出明文,所以我不怀疑你的代码有什么问题;相反,文件内容可能是罪魁祸首。
推荐阅读
- scala - 如何使用 scalac 编译具有依赖项的类?
- c++ - ARM64上的多播“没有这样的设备”?
- docker - 发出 EC2 停止实例时如何使用 docker-compose down 优雅地停止 docker 服务
- java - 使用反射库时出现 UnsupportedClassVersionError: JVMCFRE003 错误
- python - 如何在 Python 中提取一个字典的键和值
- groovy - Nextflow 将提交的输出显示为空
- c - 我怎样才能毫不拖延地“延迟节目”?
- python - 遍历具有列表值的 pandas 列并将其存储在新列中
- angular8 - 等待每个数组元素的订阅完成,然后再移动到下一个索引
- python-3.x - 使用 datetime64 提取数据数组会出错