首页 > 解决方案 > 为什么我在读取字节时会得到一个额外的 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'

我的问题是:

  1. 为什么我在读取外部文件时会得到额外的前缀?如果没有额外的前缀,我怎么能读取文件?
  2. 有没有办法只选择我想要的字节,然后将它们附加到 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)

标签: pythonpython-3.xaes

解决方案


如果无法访问您正在使用的确切文件,很难说,但这可能是文件内容的问题。

使用您的示例,我对其进行了修改,以便它可以写出一个密文文件(作为原始字节)并将其读入(作为原始字节)。

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())

这会在我的机器上按预期输出明文,所以我不怀疑你的代码有什么问题;相反,文件内容可能是罪魁祸首。


推荐阅读