|
|
|
|
|
|
|
|
|
|
|
|
|
from Crypto.Cipher import AES |
|
import operator |
|
import time |
|
|
|
AES_BLOCK_SIZE = AES.block_size |
|
AES_KEY_SIZE = 16 |
|
|
|
|
|
|
|
def PadTest(bytes): |
|
while len(bytes) % AES_BLOCK_SIZE != 0: |
|
bytes += ' '.encode() |
|
return bytes |
|
|
|
|
|
|
|
def PadKey(key): |
|
if len(key) > AES_KEY_SIZE: |
|
return key[:AES_KEY_SIZE] |
|
while len(key) % AES_KEY_SIZE != 0: |
|
key += ' '.encode() |
|
return key |
|
|
|
|
|
|
|
def EnCrypt(key, bytes): |
|
myCipher = AES.new(key, AES.MODE_ECB) |
|
encryptData = myCipher.encrypt(bytes) |
|
return encryptData |
|
|
|
|
|
|
|
def DeCrypt(key, encryptData): |
|
myCipher = AES.new(key, AES.MODE_ECB) |
|
bytes = myCipher.decrypt(encryptData) |
|
return bytes |
|
|
|
|
|
def load_encrypt_model(model_path, key='test'): |
|
with open(model_path, 'rb') as f_: |
|
bytes_aes = f_.read() |
|
bytes = DeCrypt(PadKey(key.encode()), bytes_aes) |
|
pad_len = int(model_path.split('_')[-1].split('.')[0]) |
|
return bytes[:-pad_len] |
|
|
|
|
|
if __name__ == '__main__': |
|
|
|
key = "test" |
|
file_path = '' |
|
output_path = '' |
|
|
|
with open(file_path, 'rb') as f: |
|
bytes_ori = f.read() |
|
print('源文件长度:{}'.format(len(bytes_ori))) |
|
|
|
key = PadKey(key.encode()) |
|
bytes = PadTest(bytes_ori) |
|
print('补齐后的源文件长度:{}'.format(len(bytes))) |
|
|
|
encryptTest = EnCrypt(key, bytes) |
|
|
|
start_time = time.time() |
|
decryptTest = DeCrypt(key, encryptTest) |
|
dt = time.time() - start_time |
|
print("解密时间: ", dt) |
|
|
|
pad_len = len(bytes) - len(bytes_ori) |
|
print(pad_len) |
|
decryptTest = decryptTest[:-pad_len] |
|
print('补齐长度:{} '.format(len(decryptTest))) |
|
if operator.eq(bytes_ori, decryptTest): |
|
print('AES 加解密成功!') |
|
with open(output_path, "wb") as fo: |
|
fo.write(encryptTest) |
|
else: |
|
print('AES 加解密失败,解密数据与元数据不相等') |
|
|