基于数据库+TCP+RC4实现消息的加解密传输和存储功能python程序
时间: 2023-12-12 21:05:18 浏览: 31
好的,以下是一个基于Python语言实现的简单示例程序,用于演示如何使用数据库+TCP+RC4实现消息的加解密传输和存储功能。
这个程序需要安装PyMySQL和pycryptodome两个库,可以使用pip install命令进行安装。
客户端代码:
```python
import socket
from Crypto.Cipher import ARC4
import pymysql
# 连接数据库
db = pymysql.connect(host="localhost", user="root", password="password", database="chat")
cursor = db.cursor()
# 客户端套接字
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 服务器地址和端口
server_address = ('127.0.0.1', 8888)
# 连接服务器
client_socket.connect(server_address)
# RC4加解密密钥
key = b'1234567890'
# 循环发送消息
while True:
# 获取输入的消息
message = input("请输入消息:")
# 加密消息
cipher = ARC4.new(key)
encrypted_message = cipher.encrypt(message.encode())
# 发送加密后的消息
client_socket.sendall(encrypted_message)
# 存储消息到数据库
sql = "INSERT INTO messages (sender, receiver, message) VALUES ('client', 'server', %s)"
cursor.execute(sql, (encrypted_message.hex()))
db.commit()
# 接收服务器响应
data = client_socket.recv(1024)
# 解密响应
cipher = ARC4.new(key)
decrypted_data = cipher.decrypt(data).decode()
print("收到服务器响应:", decrypted_data)
# 关闭套接字和数据库连接
client_socket.close()
db.close()
```
服务器端代码:
```python
import socket
from Crypto.Cipher import ARC4
import pymysql
# 连接数据库
db = pymysql.connect(host="localhost", user="root", password="password", database="chat")
cursor = db.cursor()
# 服务器套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 服务器地址和端口
server_address = ('127.0.0.1', 8888)
# 绑定服务器地址和端口
server_socket.bind(server_address)
# 监听连接
server_socket.listen(1)
# 等待客户端连接
print("等待客户端连接...")
client_socket, client_address = server_socket.accept()
print("客户端已连接:", client_address)
# RC4加解密密钥
key = b'1234567890'
# 循环接收消息
while True:
# 接收客户端消息
data = client_socket.recv(1024)
# 如果没有接收到数据,说明客户端已关闭连接
if not data:
print("客户端已关闭连接")
break
# 解密消息
cipher = ARC4.new(key)
decrypted_data = cipher.decrypt(data).decode()
print("收到客户端消息:", decrypted_data)
# 存储消息到数据库
sql = "INSERT INTO messages (sender, receiver, message) VALUES ('server', 'client', %s)"
cursor.execute(sql, (data.hex()))
db.commit()
# 发送响应
response = "已收到消息"
cipher = ARC4.new(key)
encrypted_response = cipher.encrypt(response.encode())
client_socket.sendall(encrypted_response)
# 关闭套接字和数据库连接
client_socket.close()
server_socket.close()
db.close()
```
注意:这个程序只是一个简单的示例,没有考虑到所有可能的错误和异常情况。在实际应用中,您需要进行更全面的错误处理和安全性保护。