使用Python实现加密传输文件
时间: 2024-03-28 07:31:53 浏览: 183
基于Python实现(GUI)通信加密的文字文件传输系统【100010184】
5星 · 资源好评率100%
要使用Python实现加密传输文件,可以使用`socket`库进行网络通信,使用`cryptography`库进行文件加密。以下是一个简单的示例:
1. 首先,安装`cryptography`库:
```bash
pip install cryptography
```
2. 创建一个名为`server.py`的文件,用于接收客户端发送的加密文件:
```python
import socket
from cryptography.fernet import Fernet
# 生成密钥并保存到文件
key = Fernet.generate_key()
with open("key.key", "wb") as key_file:
key_file.write(key)
# 加载密钥
with open("key.key", "rb") as key_file:
key = key_file.read()
cipher_suite = Fernet(key)
# 创建服务器套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 12345))
server_socket.listen(1)
print("等待客户端连接...")
# 接受客户端连接
client_socket, client_address = server_socket.accept()
print(f"客户端 {client_address} 已连接")
# 接收加密文件
with open("received_file.txt", "wb") as received_file:
encrypted_data = client_socket.recv(1024)
decrypted_data = cipher_suite.decrypt(encrypted_data)
received_file.write(decrypted_data)
print("文件接收成功")
# 关闭套接字
client_socket.close()
server_socket.close()
```
3. 创建一个名为`client.py`的文件,用于发送加密文件给服务器:
```python
import socket
from cryptography.fernet import Fernet
# 生成密钥并保存到文件
key = Fernet.generate_key()
with open("key.key", "wb") as key_file:
key_file.write(key)
# 加载密钥
with open("key.key", "rb") as key_file:
key = key_file.read()
cipher_suite = Fernet(key)
# 创建客户端套接字
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('localhost', 12345))
# 读取要发送的文件
with open("send_file.txt", "rb") as send_file:
encrypted_data = cipher_suite.encrypt(send_file.read())
# 发送加密文件给服务器
client_socket.sendall(encrypted_data)
print("文件发送成功")
# 关闭套接字
client_socket.close()
```
运行`server.py`和`client.py`,客户端将加密文件发送给服务器,服务器解密后接收文件。
阅读全文