使用python模块cryptography.x509创建自签名证书和为server签名,验证签名时报错:Certificate is missing required extension
应该添加什么必要的扩展呢?
生成证书代码:
# 使用自签名签发服务器签名
def generate_sign_sret():
with open("csr.pem", "rb") as f:
pem_req_data = f.read()
server_csr = x509.load_pem_x509_csr(pem_req_data)
with open("cert.pem", "rb") as f:
ca_pem_req_data = f.read()
ca_cert = x509.load_pem_x509_certificate(ca_pem_req_data)
# 签发服务器证书
server_cert = (
x509.CertificateBuilder()
# 服务器请求信息
.subject_name(server_csr.subject)
# 自签名证书
.issuer_name(ca_cert.subject)
.public_key(server_csr.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(datetime.now() - timedelta(days=1))
# 有效期一年
.not_valid_after(datetime.now() + timedelta(days=365))
.add_extension(
# x509.BasicConstraints(ca=False, path_length=None),
x509.SubjectAlternativeName([x509.DNSName("cryptography.io")]),
# critical=True,
critical=False,
)
.add_extension(
x509.BasicConstraints(ca=False, path_length=None),
critical=True,
)
.add_extension(
x509.KeyUsage(True, True, True, True, True, False, True, True, True),
critical=True,
)
# 使用CA的私钥签发
.sign(key, SHA256(), default_backend())
)
server_cert_bytes = server_cert.public_bytes(encoding=serialization.Encoding.PEM)
with open("server_cert.pem", "wb") as f:
f.write(server_cert_bytes)
验证函数:
# 验签
def verifyCert():
with open("cert.pem", "rb") as f:
ca_pem_req_data = f.read()
ca_cert = x509.load_pem_x509_certificate(ca_pem_req_data)
with open("server_cert.pem", "rb") as f:
server_pem_req_data = f.read()
server_cert = x509.load_pem_x509_certificate(server_pem_req_data)
with open(certifi.where(), "rb") as pems:
store = Store(x509.load_pem_x509_certificates(pems.read()))
# 创建一个受信任的store
trust_builder = PolicyBuilder().store(store)
verifier = trust_builder.build_server_verifier(x509.DNSName("cryptography.io"))
try:
verifier.verify(server_cert, [server_cert, ca_cert])
print("Server certificate is valid.")
except Exception as e:
print("Server certificate validation failed:", e)