今天我们用python编写加密通信程序
代码中的127.0.0.1是编造地址
注意:
这个程序只能让客户端连接到特定的服务器
可以用input让用户自己输入服务器ip
使用的时候记得更改为自己服务器的ip地址
import socket
from cryptography.fernet import Fernet
# 生成加密密钥
key = Fernet.generate_key()
cipher_suite = Fernet(key)
# 服务器端代码
def server():
host = '127.0.0.1'
port = 12345
# 创建socket对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(1)
print("等待客户端连接...")
# 接受客户端连接
client_socket, addr = server_socket.accept()
print("客户端已连接:", addr)
while True:
# 接收加密的消息
encrypted_message = client_socket.recv(1024)
decrypted_message = cipher_suite.decrypt(encrypted_message).decode()
if decrypted_message == "结束":
break
print("客户端消息:", decrypted_message)
# 发送加密的响应
response = input("服务器回复:")
encrypted_response = cipher_suite.encrypt(response.encode())
client_socket.send(encrypted_response)
client_socket.close()
server_socket.close()
# 客户端代码
def client():
host = '127.0.0.1'
port = 12345
# 创建socket对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((host, port))
while True:
# 发送加密的消息
message = input("客户端消息:")
encrypted_message = cipher_suite.encrypt(message.encode())
client_socket.send(encrypted_message)
if message == "结束":
break
# 接收加密的响应
encrypted_response = client_socket.recv(1024)
decrypted_response = cipher_suite.decrypt(encrypted_response).decode()
print("服务器回复:", decrypted_response)
client_socket.close()
# 启动服务器和客户端
server()
client()