python使用的是3.7的版本
需要提前安装
pip install pyopenssl
pip install tornado
生成自签数字证书代码:
from OpenSSL import crypto
from OpenSSL import SSL
from socket import gethostname#获取主机名
from pprint import pprint
from time import gmtime
from time import mktime
from os.path import exists, join#用来验证路径
CERT_FILE = "test.cer"
KEY_FILE = "test.key"
def create_self_signed_cert(cert_dir):
'''
if datacard.crt and datacard.key don't exist in cert_dir,create a new self-signed cert and keypair and write them into that directory.
:param cert_dir: user defined
:return: none
'''
if not exists(join(cert_dir, CERT_FILE)) or not exists(join(cert_dir, KEY_FILE)):
# create a key pair
k = crypto.PKey()
k.generate_key(crypto.TYPE_RSA, 1024)
# create a self-signed cert
cert = crypto.X509()
cert.get_subject().C = "CN"
cert.get_subject().ST = "henan"
cert.get_subject().L = "zhengzhou"
cert.get_subject().O = "my company"
cert.get_subject().OU = "my organization"
cert.get_subject().CN = "localhost"
cert.set_serial_number(1000)
cert.gmtime_adj_notBefore(0)
cert.gmtime_adj_notAfter(10 * 365 * 24 * 60 * 60)
cert.set_issuer(cert.get_subject())
cert.set_pubkey(k)
cert.sign(k, 'sha1')
# open(join(cert_dir, CERT_FILE), "wt").write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
with open(join(cert_dir, CERT_FILE), "wb") as f:
f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
# open(join(cert_dir, KEY_FILE), "wt").write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k))
with open(join(cert_dir, KEY_FILE), "wb") as f:
f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k))
create_self_signed_cert(r"C:\\Users\\15013\\Desktop\\pycerti\\")
验证代码:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os.path
from tornado import httpserver
from tornado import ioloop
from tornado import web
class TestHandler(web.RequestHandler):
def get(self):
self.write("GreenSummer")
def main():
settings = {
"static_path": os.path.join(os.path.dirname(__file__), "static"),
}
application = web.Application([
(r"/", TestHandler),
], **settings)
server = httpserver.HTTPServer(application, ssl_options={
"certfile": os.path.join(os.path.abspath("."), "test.cer"),
"keyfile": os.path.join(os.path.abspath("."), "test.key"),
})
server.listen(8000)
ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
最后用IE验证
注意主机名跟数字证书中一致