本帖最后由 菜叶片 于 2025-2-2 21:09 编辑
这是Gemini写的 没测试 应该没什么问题?
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
import os
def chacha20_file_decrypt(input_file, output_file, key, nonce):
"""
使用 ChaCha20 解密文件。
Args:
input_file (str): 输入文件路径。
output_file (str): 输出文件路径。
key (bytes): 32 字节的密钥。
nonce (bytes): 8 字节的 nonce。
"""
try:
with open(input_file, 'rb') as infile:
ciphertext = infile.read()
cipher = Cipher(algorithms.ChaCha20(key, nonce), mode=None, backend=default_backend())
decryptor = cipher.decryptor()
plaintext = decryptor.update(ciphertext) + decryptor.finalize()
with open(output_file, 'wb') as outfile:
outfile.write(plaintext)
print(f"文件已成功解密并保存到: {output_file}")
except FileNotFoundError:
print(f"错误:找不到文件: {input_file}")
except Exception as e:
print(f"解密过程中发生错误: {e}")
if __name__ == '__main__':
key = bytes([0x20, 0x06, 0x02, 0x25, 0x4a, 0x69, 0x75, 0x59, 0x61, 0x6e, 0x20, 0x47, 0x69, 0x74, 0x48, 0x75,
0x62, 0x43, 0x4e, 0x4d, 0x72, 0x53, 0x75, 0x6e, 0x73, 0x68, 0x69, 0x6e, 0x65, 0x51, 0x41, 0x51])
nonce = bytes([0x59, 0x65, 0x50, 0x69, 0x61, 0x6e, 0x58, 0x44])
input_file = 'encrypted.txt' # 替换为你的加密文件路径
output_file = 'decrypted.txt' # 替换为你想要保存的解密文件路径
# 创建一个测试加密文件
with open(input_file, 'wb') as f:
f.write(os.urandom(1024))
# 加密文件
cipher = Cipher(algorithms.ChaCha20(key, nonce), mode=None, backend=default_backend())
encryptor = cipher.encryptor()
with open(input_file, 'rb') as infile:
ciphertext = encryptor.update(infile.read()) + encryptor.finalize()
with open(input_file, 'wb') as outfile:
outfile.write(ciphertext)
chacha20_file_decrypt(input_file, output_file, key, nonce)
|