转: fastapi https 配置
python3 快速生成 https 所需证书
from OpenSSL import crypto, SSL
def generate_certificate(
organization="PrivacyFilter",
common_name="https://www.url.com",
country="NL",
duration=(365 * 24 * 60 * 60),
keyfilename="key.pem",
certfilename="cert.pem"):
k = crypto.PKey()
k.generate_key(crypto.TYPE_RSA, 4096)
cert = crypto.X509()
cert.get_subject().C = country
cert.get_subject().O = organization
cert.get_subject().CN = common_name
cert.gmtime_adj_notBefore(0)
cert.gmtime_adj_notAfter(duration)
cert.set_issuer(cert.get_subject())
cert.set_pubkey(k)
cert.sign(k, 'sha512')
with open(keyfilename, "wt") as keyfile:
keyfile.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k).decode("utf-8"))
with open(certfilename, "wt") as certfile:
certfile.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode("utf-8"))
if __name__ == '__main__':
generate_certificate()
快速生成一个非安全的测试用证书,我运行了一下,发现可以在win10环境中运行上述代码生成证书和私钥。
运行fastapi
我的终端运行指令:
uvicorn tst-sql.main:app --ssl-keyfile ./cert/key.pem --ssl-certfile ./cert/cert.pem
原运行代码:
uvicorn.run("PrivacyFilterAPI:privacyFilterApp",
host="0.0.0.0", port=8000, reload=True,
ssl_keyfile="./key.pem", ssl_certfile="./cert.pem"
)
摘自:https://zhuanlan.zhihu.com/p/387353414
小工具 xca
xca下载地址:http://xca.hohnstaedt.de/
使用说明,见博客https SSL 自建证书的制作