3

I generated my self-signed certificate with open ssl

openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem

I am using python2, and this is my server code:

import socket, ssl 

bindsocket = socket.socket()
bindsocket.bind(('localhost', 10023))
bindsocket.listen(5)

while True:
    newsocket, fromaddr = bindsocket.accept()
    connstream = ssl.wrap_socket(newsocket,
                                 server_side=True,
                                 certfile="cert.pem",
                                 ssl_version=ssl.PROTOCOL_SSLv23)
    try:
        data = connstream.read()
        print data
    finally:
        connstream.write('hi this is server')
        connstream.shutdown(socket.SHUT_RDWR)
        connstream.close()

this code works well, my client can get 'hi this is server' successfully. however, when i changed the ssl_version from ssl.PROTOCOL_SSLv23 to ssl.PROTOCOL_TLSv1 or ssl.PROTOCOL_SSLv3, there will be an error:

ssl.SSLError: [Errno 1] _ssl.c:504: error:1408F10B:SSL routines:SSL3_GET_RECORD:wrong version number

if i changed ssl_versiton to ssl.PROTOCOL_SSLv2:

ssl.SSLError: [Errno 1] _ssl.c:504: error:1406B0CB:SSL routines:GET_CLIENT_MASTER_KEY:peer error no cipher

this is my client code, I hope this may help to generate the issue:

import socket, ssl 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_sock = ssl.wrap_socket(s,
                           ca_certs="cert.pem",
                           cert_reqs=ssl.CERT_REQUIRED)
ssl_sock.connect(('localhost', 10023))
ssl_sock.write('hi this is client')
data = ssl_sock.read()
print data
ssl_sock.close()

I can not understand what's wrong with these. how could I use protocols other than SSLv23?

4

1 回答 1

0

您是否曾经考虑过服务器端需要密钥文件而客户端不需要证书文件?

在这里稍微修改了您的代码,希望对您有所帮助。

#Server side:
import socket, ssl 

bindsocket = socket.socket()
bindsocket.bind(('localhost', 10023))
bindsocket.listen(5)

while True:
    newsocket, fromaddr = bindsocket.accept()
    connstream = ssl.wrap_socket(newsocket,
                                    keyfile='key.pem',
                                 server_side=True,
                                 certfile="cert.crt",
                                 ssl_version=ssl.PROTOCOL_SSLv23)
    try:
        data = connstream.read()
        print data
    finally:
        connstream.write('hi this is server')
        connstream.shutdown(socket.SHUT_RDWR)
        connstream.close()


#Client side:
import socket, ssl 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_sock = ssl.wrap_socket(s,
                           ca_certs="cert.crt",
                           cert_reqs=ssl.CERT_REQUIRED
                           )
ssl_sock.connect(('localhost', 10023))
ssl_sock.write('hi this is client')
data = ssl_sock.read()
print data`enter code here`
ssl_sock.close()
于 2017-01-04T15:10:10.720 回答