在以上通信程序实现基础上为两个客户端添加秘钥协商及对称加密部件,邀请参与通信双方除实现双工通信外,还需要在通信开始前完成身份认证、秘钥协商,且通信内容必须使用对称秘钥加密算法加密后传输。
时间: 2024-02-28 15:53:07 浏览: 14
好的,以下是一个添加了秘钥协商和对称加密部件的Python代码示例:
```python
import socket
import hashlib
from Crypto.Cipher import AES
# 创建一个套接字对象
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 获取本地IP地址
local_ip = socket.gethostbyname(socket.gethostname())
# 设置端口号
port = 8888
# 绑定IP地址和端口号
sock.bind((local_ip, port))
# 监听客户端请求
sock.listen()
print(f"Listening on {local_ip}:{port}")
# 等待客户端1连接
client1_sock, client1_address = sock.accept()
print(f"Accepted connection from {client1_address}")
# 发送公钥给客户端1
public_key = "12345" # 公钥
client1_sock.send(public_key.encode())
# 等待客户端2连接
client2_sock, client2_address = sock.accept()
print(f"Accepted connection from {client2_address}")
# 发送公钥给客户端2
client2_sock.send(public_key.encode())
# 接收客户端1的密钥
key1 = client1_sock.recv(1024).decode()
# 发送密钥给客户端2
client2_sock.send(key1.encode())
# 接收客户端2的密钥
key2 = client2_sock.recv(1024).decode()
# 发送密钥给客户端1
client1_sock.send(key2.encode())
# 对称加密算法
def encrypt(key, message):
cipher = AES.new(key, AES.MODE_EAX)
ciphertext, tag = cipher.encrypt_and_digest(message.encode())
return ciphertext, cipher.nonce, tag
# 对称解密算法
def decrypt(key, nonce, ciphertext, tag):
cipher = AES.new(key, AES.MODE_EAX, nonce=nonce)
plaintext = cipher.decrypt(ciphertext)
try:
cipher.verify(tag)
except ValueError:
print("Message authentication failed")
return None
return plaintext.decode()
# 生成密钥
def generate_key(secret):
return hashlib.sha256(secret.encode()).digest()
while True:
# 接收客户端1发来的消息
ciphertext = client1_sock.recv(1024)
nonce = client1_sock.recv(16)
tag = client1_sock.recv(16)
# 解密消息
message = decrypt(generate_key(key1), nonce, ciphertext, tag)
if not message:
break
print(f"Received message from client 1: {message}")
# 发送消息给客户端2
message = input("Enter message to send to client 2: ")
ciphertext, nonce, tag = encrypt(generate_key(key2), message)
client2_sock.send(ciphertext)
client2_sock.send(nonce)
client2_sock.send(tag)
# 接收客户端2发来的消息
ciphertext = client2_sock.recv(1024)
nonce = client2_sock.recv(16)
tag = client2_sock.recv(16)
# 解密消息
message = decrypt(generate_key(key2), nonce, ciphertext, tag)
if not message:
break
print(f"Received message from client 2: {message}")
# 发送消息给客户端1
message = input("Enter message to send to client 1: ")
ciphertext, nonce, tag = encrypt(generate_key(key1), message)
client1_sock.send(ciphertext)
client1_sock.send(nonce)
client1_sock.send(tag)
# 关闭套接字
client1_sock.close()
client2_sock.close()
sock.close()
```
在这个示例中,我们首先向两个客户端发送公钥。然后我们等待客户端1发送密钥,将其发送给客户端2,并等待客户端2发送密钥,将其发送给客户端1。这样,双方就完成了秘钥协商。
接下来我们使用一个对称加密算法对通信内容进行加密和解密。这里我们使用了AES算法,我们使用一个密码字符串生成一个密钥,然后使用该密钥对通信内容进行加密和解密。
在每次接收到消息时,我们首先对其进行解密,然后再打印出来。然后我们要求用户输入要发送给对方的消息,并将其加密后发送给对方。
请注意,这只是一个简单的示例,用于演示如何实现秘钥协商和对称加密。在实际应用中,需要使用更安全的加密算法和更复杂的协商过程来确保通信的安全。