Skip to main content
 首页 » 编程设计

python之为什么在读取字节时会得到一个额外的 b 前缀

2024年11月24日10sharpest

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

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) 

请您参考如下方法:

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

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

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

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