[python]Des加密解密7z压缩包

from Crypto.Cipher import DES3
from Crypto.Util.Padding import pad, unpad
import os

# 设置密钥和 IV
key = b"rfgsgdfsdffdthro"
iv = b"qazwsxed"

print("请选择操作: \n1. 加密\n2. 解密")
try:
    action = int(input("请输入操作编号: "))
    if action not in [1, 2]:
        print("无效选择")
        exit()
except ValueError:
    print("请输入有效的数字编号")
    exit()

if action == 1:
    files = [f for f in os.listdir() if f.endswith(".7z")]
    file_type = ".7z"
    output_extension = ".sql"
elif action == 2:
    files = [f for f in os.listdir() if f.endswith(".sql")]
    file_type = ".sql"
    output_extension = "_decrypted.7z"

if not files:
    print(f"当前目录中没有找到 {file_type} 文件")
    exit()

print(f"请选择要处理的 {file_type} 文件:")
for idx, filename in enumerate(files, start=1):
    print(f"{idx}. {filename}")

try:
    choice = int(input("请输入文件编号: ")) - 1
    if choice < 0 or choice >= len(files):
        print("无效选择")
        exit()
except ValueError:
    print("请输入有效的数字编号")
    exit()

file_path = files[choice]

if action == 1:
    cipher = DES3.new(key, DES3.MODE_CBC, iv)
    with open(file_path, "rb") as f:
        plaintext = f.read()
    padded_text = pad(plaintext, DES3.block_size)
    ciphertext = cipher.encrypt(padded_text)
    encrypted_file_path = f"{os.path.splitext(file_path)[0]}{output_extension}"
    with open(encrypted_file_path, "wb") as f:
        f.write(ciphertext)
    print(f"文件已加密,输出路径:{encrypted_file_path}")

elif action == 2:
    cipher = DES3.new(key, DES3.MODE_CBC, iv)
    with open(file_path, "rb") as f:
        ciphertext = f.read()
    try:
        padded_plaintext = cipher.decrypt(ciphertext)
        plaintext = unpad(padded_plaintext, DES3.block_size)
    except ValueError:
        print("解密失败,可能是密钥或IV错误。")
        exit()
    decrypted_file_path = f"{os.path.splitext(file_path)[0]}{output_extension}"
    with open(decrypted_file_path, "wb") as f:
        f.write(plaintext)
    print(f"文件已解密,输出路径:{decrypted_file_path}")