本地TCP通信的加密机制可以通过使用加密算法对传输的数据进行加密和解密。以下是一个使用AES加密算法的示例代码:
import socket
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
# 加密密钥,必须是16、24或32字节的长度
key = b'this_is_a_16_key'
def encrypt(plain_text):
cipher = AES.new(key, AES.MODE_CBC)
cipher_text = cipher.encrypt(pad(plain_text.encode('utf-8'), AES.block_size))
# 返回加密后的数据和IV向量
return cipher_text, cipher.iv
def decrypt(cipher_text, iv):
cipher = AES.new(key, AES.MODE_CBC, iv)
plain_text = unpad(cipher.decrypt(cipher_text), AES.block_size)
return plain_text.decode('utf-8')
# 创建TCP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 1234))
server_socket.listen(1)
# 等待客户端连接
client_socket, address = server_socket.accept()
print('连接建立:', address)
# 加密并发送数据
data = 'Hello, world!'
cipher_text, iv = encrypt(data)
client_socket.send(iv + cipher_text)
# 接收并解密数据
received_data = client_socket.recv(1024)
iv = received_data[:AES.block_size]
cipher_text = received_data[AES.block_size:]
plain_text = decrypt(cipher_text, iv)
print('接收到的数据:', plain_text)
# 关闭连接
client_socket.close()
server_socket.close()
在以上示例中,使用了Crypto.Cipher
模块提供的AES加密算法进行加密和解密。在发送数据时,先使用AES算法对数据进行加密,然后将加密后的数据和初始化向量(IV)一起发送给接收端。接收端收到数据后,使用相同的密钥和IV进行解密,得到原始数据。
需要注意的是,在实际应用中,需要确保通信双方都使用相同的密钥和加密算法,并采取一定的安全措施来保护密钥的安全性,以防止被第三方获取。
上一篇:本地TCP连接。为什么会存在?