python使用OpenSSL生成证书的编程代码
时间: 2023-04-07 07:03:25 浏览: 204
openssl生成证书
以下是使用Python OpenSSL生成证书的示例代码:
```python
from OpenSSL import crypto, SSL
# 创建私钥
key = crypto.PKey()
key.generate_key(crypto.TYPE_RSA, 2048)
# 创建证书请求
req = crypto.X509Req()
subj = req.get_subject()
subj.countryName = "CN"
subj.stateOrProvinceName = "Beijing"
subj.localityName = "Beijing"
subj.organizationName = "CSDN"
subj.organizationalUnitName = "IT"
subj.commonName = "www.csdn.net"
req.set_pubkey(key)
req.sign(key, "sha256")
# 创建自签名证书
cert = crypto.X509()
cert.set_subject(subj)
cert.set_serial_number(1000)
cert.gmtime_adj_notBefore(0)
cert.gmtime_adj_notAfter(365*24*60*60)
cert.set_issuer(cert.get_subject())
cert.set_pubkey(key)
cert.sign(key, "sha256")
# 保存证书和私钥
with open("cert.pem", "wt") as f:
f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode("utf-8"))
f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, key).decode("utf-8"))
```
希望对你有所帮助!
阅读全文