验证Python套接字是否已加密

时间:2016-01-20 08:01:05

标签: python sockets ssl encryption tcp

我使用herehere的位创建了一个TCP echo客户端/服务器。如何验证套接字是否已加密且无法拦截和读取?我尝试过使用Wireshark,但SSL和非SSL都显示加密数据包。这让我质疑它们的有效性。

客户端:

import socket
import ssl

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('HOSTNAME', 10000)
print('Connecting to %s port %s' % server_address)
sock.connect(server_address)
ssl_sock = ssl.wrap_socket(
        sock,
        ssl_version = ssl.PROTOCOL_TLSv1_2
)

try:
    message = str.encode(input('>>> '))
    print('Sending "%s"' % message)
    ssl_sock.sendall(message)

    amount_received = 0
    amount_expected = len(message)

    while amount_received < amount_expected:
        data = ssl_sock.recv(16)
        amount_received += len(data)
        print('Received "%s"' % data)

finally:
    print('Closing socket')
    ssl_sock.close()

服务器

import socket
import ssl

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('HOSTNAME', 10000)
print('Starting up on %s port %s' % server_address)
sock.bind(server_address)
sock.listen(1)

while True:
    print('Waiting for a connection')
    try:
        connection, client_address = sock.accept()
        stream = ssl.wrap_socket(
            connection,
            server_side = True,
            certfile = 'fullchain.pem',
            keyfile = 'privkey.pem',
            ssl_version = ssl.PROTOCOL_TLSv1_2
        )
    except KeyboardInterrupt:
        print('\nStopping server')
        exit()
    except:
        print('ERROR')
        continue

    try:
        print('Connection from', client_address)

        while True:
            data = stream.recv(16)
            print('Received "%s"' % data)
            if data:
                print('Sending data back to the client')
                stream.sendall(data)
            else:
                print('No more data from', client_address)
                break
    finally:
        stream.close()

服务器正在我的VPS上运行并使用HTTPS的真实证书。一切正常,但我只是想确保这个测试是安全的,然后再构建真实的东西。

0 个答案:

没有答案