Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
670 views
in Technique[技术] by (71.8m points)

openssl - Python Simple SSL Socket Server

Just trying to set up a simple SSL server. I have never had anything SSL work for me in the past. I have a loose understanding of how SSL certificates and signing.

The code is simple

import socket, ssl

context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.load_cert_chain(certfile="mycertfile") ###############

bindsocket = socket.socket()
bindsocket.bind(('', 2099))
bindsocket.listen(5)

while True:
    newsocket, fromaddr = bindsocket.accept()
    sslsoc = context.wrap_socket(newsocket, server_side=True)
    request = sslsoc.read()
    print(request)

The line in there with the ###s after it is the one that isnt working. I don't know what I have to do with openssl to generate a PEM file that will work here.

Can anyone enlighten me as to how to make this simple socket work.

By the way, this is NOT used for HTTP.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you can use this command to generate a self-signed certificate

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

the openssl framework will ask you to enter some information, such as your country, city, etc. just follow the instruction, and you will get a cert.pem file. the output file will have both your RSA private key, with which you can generate your public key, and the certificate. the output file looks like this:

-----BEGIN RSA PRIVATE KEY-----
 # your private key
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
 # your certificate
-----END CERTIFICATE-----

just load it, and the ssl module will handle the rest for you:

context.load_cert_chain(certfile="cert.pem", keyfile="cert.pem")

btw, there is no "SSLContext" in python2. for guys who are using python2, just assign the pem file when wrapping socket:

newsocket, fromaddr = bindsocket.accept()
connstream = ssl.wrap_socket(newsocket,
                             server_side=True,
                             certfile="cert.pem",
                             keyfile="cert.pem",
                             ssl_version=YOUR CHOICE) 

available ssl version: ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23. if you have no idea, ssl.PROTOCOL_SSLv23 may be your choice as it provides the most compatibility with other versions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...