datxy commited on
Commit
4f263b6
·
verified ·
1 Parent(s): 30f98f6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -0
app.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from cryptography.fernet import Fernet
3
+
4
+ # AES 加密函数(Fernet 实现)
5
+ def encrypt_file_gr(file):
6
+ # `file` 是一个 NamedTemporaryFile 对象,带有属性 `name`
7
+ file_path = file.name
8
+ # 生成密钥并初始化 cipher
9
+ key = Fernet.generate_key()
10
+ cipher = Fernet(key)
11
+ # 读取原文件并加密
12
+ with open(file_path, 'rb') as f:
13
+ data = f.read()
14
+ encrypted_data = cipher.encrypt(data)
15
+ # 写入加密文件
16
+ enc_path = file_path + '.enc'
17
+ with open(enc_path, 'wb') as f:
18
+ f.write(encrypted_data)
19
+ # 返回密钥和加密文件路径
20
+ return key.decode(), enc_path
21
+
22
+ # AES 解密函数
23
+
24
+ def decrypt_file_gr(file, key):
25
+ file_path = file.name
26
+ cipher = Fernet(key.encode())
27
+ try:
28
+ with open(file_path, 'rb') as f:
29
+ encrypted_data = f.read()
30
+ decrypted_data = cipher.decrypt(encrypted_data)
31
+ dec_path = file_path.replace('.enc', '.dec')
32
+ with open(dec_path, 'wb') as f:
33
+ f.write(decrypted_data)
34
+ return dec_path
35
+ except Exception as e:
36
+ # 如果解密失败,返回空,让 Gradio 显示错误
37
+ return None
38
+
39
+ # Gradio 界面设计
40
+ with gr.Blocks() as demo:
41
+ gr.Markdown("# 文件加密解密工具")
42
+
43
+ with gr.Tab("加密"):
44
+ encrypt_in = gr.File(label="上传文件")
45
+ encrypt_btn = gr.Button("加密文件 🔒")
46
+ encrypt_key = gr.Textbox(label="生成的密钥", interactive=False)
47
+ encrypt_out = gr.File(label="下载加密文件 (.enc)")
48
+ encrypt_btn.click(
49
+ fn=encrypt_file_gr,
50
+ inputs=encrypt_in,
51
+ outputs=[encrypt_key, encrypt_out]
52
+ )
53
+
54
+ with gr.Tab("解密"):
55
+ decrypt_in = gr.File(label="上传加密文件 (.enc)")
56
+ decrypt_key_in = gr.Textbox(label="输入密钥")
57
+ decrypt_btn = gr.Button("解密文件 🔓")
58
+ decrypt_out = gr.File(label="下载解密文件 (.dec)")
59
+ decrypt_btn.click(
60
+ fn=decrypt_file_gr,
61
+ inputs=[decrypt_in, decrypt_key_in],
62
+ outputs=decrypt_out
63
+ )
64
+
65
+ # 本地服务器启动函数,Hugging Face Spaces 会自动调用 demo.launch()
66
+ if __name__ == "__main__":
67
+ demo.launch()