利用Socket套接字编程实现一个简单的局域网内点对点通信程序,要求参与通信双方可以相互发送信息并接收对方发来信息。 在以上通信程序实现基础上为两个客户端添加秘钥协商及对称加密部件,邀请参与通信双方除实现双工通信外,还需要在通信开始前完成身份认证、秘钥协商,且通信内容必须使用对称秘钥加密算法加密后传输。
时间: 2024-02-29 11:52:22 浏览: 28
好的,以下是一个基于Socket套接字编程实现的局域网内点对点通信程序,实现了身份认证、秘钥协商以及对称加密部件。
1. 客户端代码:
```python
import socket
import hashlib
from Crypto.Cipher import AES
# 定义主机名和端口号
host = '127.0.0.1'
port = 8000
# 定义秘钥协商的口令
password = '123456'
# 定义加密算法
key = hashlib.sha256(password.encode()).digest()
cipher = AES.new(key, AES.MODE_EAX)
# 创建TCP/IP套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器
sock.connect((host, port))
# 完成身份认证和秘钥协商
sock.sendall('authenticate'.encode())
challenge = sock.recv(1024)
response = hashlib.sha256(password.encode() + challenge).digest()
sock.sendall(response)
ack = sock.recv(1024)
if ack.decode() != 'acknowledge':
print('身份认证失败')
sock.close()
exit()
else:
print('身份认证成功')
# 循环发送和接收消息
while True:
# 发送消息
message = input('发送消息:')
nonce = cipher.nonce
ciphertext, tag = cipher.encrypt_and_digest(message.encode())
sock.sendall(nonce + ciphertext + tag)
# 接收消息
received_data = sock.recv(1024)
nonce = received_data[:16]
ciphertext = received_data[16:-16]
tag = received_data[-16:]
cipher = AES.new(key, AES.MODE_EAX, nonce)
try:
plaintext = cipher.decrypt_and_verify(ciphertext, tag).decode()
print('接收到消息:', plaintext)
except ValueError:
print('接收到错误的消息')
# 关闭套接字
sock.close()
```
2. 服务器端代码:
```python
import socket
import hashlib
from Crypto.Cipher import AES
# 定义主机名和端口号
host = '127.0.0.1'
port = 8000
# 定义秘钥协商的口令
password = '123456'
# 定义加密算法
key = hashlib.sha256(password.encode()).digest()
cipher = AES.new(key, AES.MODE_EAX)
# 创建TCP/IP套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定到指定的主机名和端口号
sock.bind((host, port))
# 监听客户端请求
sock.listen(1)
# 循环等待客户端连接
while True:
# 等待连接
conn, addr = sock.accept()
print('连接来自:', addr)
# 完成身份认证和秘钥协商
request = conn.recv(1024)
if request.decode() == 'authenticate':
challenge = hashlib.sha256(str(addr).encode()).digest()
conn.sendall(challenge)
response = conn.recv(1024)
expected_response = hashlib.sha256(password.encode() + challenge).digest()
if response == expected_response:
conn.sendall('acknowledge'.encode())
print('身份认证成功')
else:
conn.sendall('reject'.encode())
print('身份认证失败')
conn.close()
continue
# 循环接收和发送消息
while True:
# 接收消息
received_data = conn.recv(1024)
if not received_data:
break
nonce = received_data[:16]
ciphertext = received_data[16:-16]
tag = received_data[-16:]
cipher = AES.new(key, AES.MODE_EAX, nonce)
try:
plaintext = cipher.decrypt_and_verify(ciphertext, tag).decode()
print('接收到消息:', plaintext)
except ValueError:
print('接收到错误的消息')
# 发送消息
message = input('发送消息:')
nonce = cipher.nonce
ciphertext, tag = cipher.encrypt_and_digest(message.encode())
conn.sendall(nonce + ciphertext + tag)
# 关闭连接
conn.close()
# 关闭套接字
sock.close()
```
该程序使用了AES对称加密算法,如果需要使用其他加密算法,可自行替换相关代码。同时,为了提高安全性,建议在协商秘钥时使用Diffie-Hellman密钥交换协议。