我在这里看到两个问题。首先,您正在创建另一个自签名证书,因此您生成的证书不是由CA签名的,它本身就是一个CA
使用CA的私钥(例如。
private_key
但您需要创建一个
新的
与新证书关联的私钥,并将该证书的公钥嵌入证书中。
certificate_private_key = <generate an ec or rsa key here>
certificate_public_key = certificate_private_key.public_key()
那就做吧
builder = builder.public_key(certificate_public_key)
您的输出也有问题,因为您试图从print语句中复制和粘贴内容。输出
cert.public_bytes(serialization.Encoding.PEM)
将是具有分隔符和正确PEM行长度的有效X509证书,因此请直接将其写入文件:
with open("cert.crt", "wb") as f:
f.write(cert.public_bytes(serialization.Encoding.PEM))
openssl x509 -noout -text -in cert.crt
下面是一个完整的例子
cryptography
创建自签名根CA并使用该CA对证书进行签名。
import datetime
from cryptography import x509
from cryptography.x509.oid import NameOID
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
root_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
subject = issuer = x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"),
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"Texas"),
x509.NameAttribute(NameOID.LOCALITY_NAME, u"Austin"),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"My Company"),
x509.NameAttribute(NameOID.COMMON_NAME, u"My CA"),
])
root_cert = x509.CertificateBuilder().subject_name(
subject
).issuer_name(
issuer
).public_key(
root_key.public_key()
).serial_number(
x509.random_serial_number()
).not_valid_before(
datetime.datetime.utcnow()
).not_valid_after(
datetime.datetime.utcnow() + datetime.timedelta(days=3650)
).sign(root_key, hashes.SHA256(), default_backend())
# Now we want to generate a cert from that root
cert_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
new_subject = x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"),
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"Texas"),
x509.NameAttribute(NameOID.LOCALITY_NAME, u"Austin"),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"New Org Name!"),
])
cert = x509.CertificateBuilder().subject_name(
new_subject
).issuer_name(
root_cert.issuer
).public_key(
cert_key.public_key()
).serial_number(
x509.random_serial_number()
).not_valid_before(
datetime.datetime.utcnow()
).not_valid_after(
datetime.datetime.utcnow() + datetime.timedelta(days=30)
).add_extension(
x509.SubjectAlternativeName([x509.DNSName(u"somedomain.com")]),
critical=False,
).sign(root_key, hashes.SHA256(), default_backend())