【问题标题】:How to secure messages travelling between a socket client and server in Python 3?如何保护在 Python 3 中的套接字客户端和服务器之间传输的消息?
【发布时间】:2015-09-22 01:27:20
【问题描述】:

我正在尝试保护在 Python 套接字服务器和客户端之间传输的消息。我做了研究,发现了以下链接: Wrapping an existing socket in SSL - Python Python socket client and server http://the.randomengineer.com/2013/10/11/a-practitioners-overview-to-ssl-and-viewing-the-certificate-chain-from-python/

并查看了 Python 文档: https://docs.python.org/3.5/library/ssl.html

但我仍然不明白该怎么做。网上找到的大多数教程都是指 Apache 或 HTTP 服务器。

这里有一些代码可以准确地解释我想要问的问题:

客户:

import socket, sys
host = 'localhost'
port = 5558
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    s.connect((host,port))
except socket.error as e:
    print (str(e))
    y = input('Press enter to close')
    sys.exit()
data = 'test'
s.sendall(str.encode(data))

服务器:

import socket, time
host = ''
port = 5558
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
s.listen(10)
sock, addr = s.accept()
data = sock.recv(2048)
print(data.decode('utf-8'))

【问题讨论】:

标签: python sockets python-3.x ssl


【解决方案1】:

尝试使用来自PyCrypto 的AES 简单地加密您的消息。

例子:

from Crypto.Cipher import AES
from Crypto import Random
IV = Random.new().read(32)
c = AES.new('abcd1234efgh5678', AES.MODE_CFB, IV)
data = c.encrypt('test')

c.decrypt(data)

代码未经测试。

【讨论】:

  • 看看你的答案——出于好奇,你为什么在代码的第四行写'abcd1234efgh5678'?
  • 密码需要16字节。
  • 好的,谢谢你的回答!
猜你喜欢
  • 1970-01-01
  • 2021-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-06
  • 1970-01-01
  • 1970-01-01
  • 2018-10-13
相关资源
最近更新 更多