2024.6.8

文件加密与解密

from flask import Flask, render_template, request, jsonify, send_file
from cryptography.fernet import Fernet
import os

app = Flask(__name__)

# 硬编码的密钥,务必在生产环境中避免这样做
key = b'9P5o8VfVP54FAtlC5tgDc7dY-nQP-romGLMDx0tM8wY='
cipher_suite = Fernet(key) # 创建加密/解密套件


@app.route('/')
def index():
return render_template('index.html')


@app.route('/encrypt', methods=['POST'])
def encrypt():
file = request.files['file']
file_content = file.read()
encrypted_content = cipher_suite.encrypt(file_content)
with open('encrypted_' + file.filename, 'wb') as encrypted_file:
encrypted_file.write(encrypted_content)
return send_file('encrypted_' + file.filename, as_attachment=True)


@app.route('/decrypt', methods=['POST'])
def decrypt():
file = request.files['file']
file_content = file.read()
try:
decrypted_content = cipher_suite.decrypt(file_content)
except:
return jsonify({"error": "解密失败,请提供有效的加密文件"}), 400
with open('decrypted_' + file.filename, 'wb') as decrypted_file:
decrypted_file.write(decrypted_content)
return send_file('decrypted_' + file.filename, as_attachment=True)


if __name__ == "__main__":
app.run(debug=True)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Encryption</title>
<style>
body {
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
background-color: #e6f2ff; /* Light blue color */
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
h1 {
text-align: center;
color: #333; /* Dark text color */
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
}
form {
text-align: center;
margin-top: 20px;
}
input[type="file"] {
margin-bottom: 10px;
}
button {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s;
}
button:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<div class="container">
<h1>File Encryption</h1>
<form action="/encrypt" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<br>
<button type="submit">Encrypt File</button>
</form>
<form action="/decrypt" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<br>
<button type="submit">Decrypt File</button>
</form>
</div>
</body>
</html>







posted @ 2024-06-13 16:09  liuxuechao  阅读(5)  评论(0编辑  收藏  举报