安装Crypto库
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pycryptodome
# AES-demo #采用AES对称加密算法
import base64
from Crypto.Cipher import AES
def add_to_16(value): # str不是16的倍数那就补足为16的倍数
while len(value) % 16 != 0:
value += '\0'
return str.encode(value) # 返回bytes
def file_content(file, read_type):
with open(file, read_type) as targetfile:
for line in targetfile:
yield line
def encrypt_oracle(file, key):
text = ""
for i in file_content(file, 'rb'):
text += str(i)
aes = AES.new(add_to_16(key), AES.MODE_ECB) # 初始化加密器
encrypt_aes = aes.encrypt(add_to_16(text)) # 先进行aes加密
encrypted_text = str(base64.encodebytes(encrypt_aes), encoding='cp936') # 用base64转成字符串形式 # 执行加密并转码返回bytes
with open("encrypt_file", "w+") as f:
f.write(encrypted_text)
def decrypt_oralce(encrypt_file, key):
text = ""
for i in file_content(encrypt_file, 'r'):
text += str(i)
aes = AES.new(add_to_16(key), AES.MODE_ECB) # 初始化加密器
base64_decrypted = base64.decodebytes(text.encode(encoding='cp936')) # 优先逆向解密base64成bytes
decrypted_text = str(aes.decrypt(base64_decrypted), encoding='gbk').replace('\0', '') # 执行解密密并转码返回str
decrypted_text2 = eval(decrypted_text)
with open("original_file.zip", "wb+") as f:
f.write(decrypted_text2)
# 加密ss.zip文件成encrypt_file,"1111"是秘钥,随便填
encrypt_oracle("ss.zip", "1111")
# 解密encrypt_file,同时输入秘钥解密
decrypt_oralce("encrypt_file", "1111")