gpt4 book ai didi

Python AES解密例程(代码帮助)

转载 作者:行者123 更新时间:2023-12-01 05:08:31 25 4
gpt4 key购买 nike

我根据在线提供的有关 AES 加密和解密例程的信息开发了一个代码。

语言:Python 2.7.x

完整代码 -

#!/usr/bin/python

import sys, os
import hashlib
import base64
from Crypto.Cipher import AES

## Variables in computation.
IV = u'1234567890123456'
BLOCK_SIZE = 32
INTERRUPT = u'\u0001'
PAD = u'\u0000'
SECRET = os.urandom(32)
filename=sys.argv[1]

def AddPadding(data, interrupt, pad, block_size):
new_data = ''.join([data, interrupt])
new_data_len = len(new_data)
remaining_len = block_size - new_data_len
to_pad_len = remaining_len % block_size
pad_string = pad * to_pad_len
return ''.join([new_data, pad_string])

def StripPadding(data, interrupt, pad):
return data.rstrip(pad).rstrip(interrupt)

def encAES(cipher_code, file_data):
data_padded = AddPadding(file_data, INTERRUPT, PAD, BLOCK_SIZE)
encrypted = cipher_code.encrypt(data_padded)
return encrypted

def decAES(cipher_code, file_data):
decrypted = cipher_code.decrypt(file_data)
return StripPadding(decrypted, INTERRUPT, PAD)

def FileSave(fwname, fwdata):
f = open(fwname, 'w')
f.write(fwdata)
f.close

def FileRead(frname):
f = open(frname, 'rb')
frdata = f.read()
return frdata

cipher = AES.new(SECRET, AES.MODE_CBC, IV)

## Encryption
data2encrypt = base64.b64encode(FileRead(filename))
encrypted_data = encAES(cipher, data2encrypt)
encrypted_content = base64.b64encode(encrypted_data)

encrypted_filename = "enc_"+filename
FileSave(encrypted_filename, encrypted_content)
print "Encryption complete. File saved as: "+ encrypted_filename

## Decryption
data2decrypt = base64.b64decode(FileRead(encrypted_filename))
decrypted_data = decAES(cipher, data2decrypt)
decrypted_content = base64.b64decode(decrypted_data)

decrypted_filename = "dec_"+filename
FileSave(decrypted_filename, decrypted_content)
print "Decryption complete. File saved as: "+ decrypted_filename

现在,加密例程工作正常,但解密例程出现错误 -

命令行 - python test.py example.txt

错误:

Traceback (most recent call last):
File "test.py", line 65, in <module>
decrypted_data = decAES(cipher, data2decrypt)
File "test.py", line 38, in decAES
return StripPadding(decrypted, INTERRUPT, PAD)
File "test.py", line 29, in StripPadding
return data.rstrip(pad).rstrip(interrupt)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 3: ordinal not in range(128)

可能的解决方法是什么?

最佳答案

您正在将字节字符串与 Unicode 值连接起来,从而触发字节字符串的自动解码。这会失败,因为您的解密文本无法解码为 ASCII。

不要在此处使用 Unicode INTERRUPTPAD 值;无论如何,您都没有从此处的文件中读取 Unicode 数据:

INTERRUPT = '\1'
PAD = '\0'

您必须创建 AES 对象的实例才能解密;您无法重复使用用于加密的对象,因为它的 IV 状态已被加密更改:

decrypt_cipher = AES.new(SECRET, AES.MODE_CBC, IV)
decrypted_data = decAES(decrypt_cipher, data2decrypt)

通过这些更改,您的代码可以正常工作,并且可以加密并再次解密数据。

关于Python AES解密例程(代码帮助),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24638786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com