为什么在读取字节时我得到一个额外的b前缀?

时间:2019-05-24 04:25:25

标签: python python-3.x aes

我正在尝试使用以下代码读取包含字节格式的密文的外部文件的内容:

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)

1 个答案:

答案 0 :(得分:1)

很难访问您正在使用的确切文件,这很难说,但是,这很可能与文件内容有关。

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

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

这将按预期在我的计算机上输出纯文本,因此我不怀疑您的代码有什么问题;相反,文件内容可能是这里的罪魁祸首。