Python加密:创建由现有CA签名的证书,然后导出

时间:2019-05-24 02:09:53

标签: python python-3.x cryptography

我正在这样创建一个CA:

openssl genrsa -out ca.key 4096
openssl req -new -x509 -days 3650 -key ca.key -out ca.cert

这给了我两个PEM文件。

然后我调用此函数,其中cert_authorityprivate_key是上面生成的数据的字符串。

def create_cert(cert_authority, private_key):
    one_day = datetime.timedelta(1, 0, 0)
    # Use our private key to generate a public key
    private_key = serialization.load_pem_private_key(
        private_key.encode("ascii"), password=None, backend=default_backend()
    )
    public_key = private_key.public_key()

    ca = x509.load_pem_x509_certificate(
        cert_authority.encode("ascii"), default_backend()
    )

    builder = x509.CertificateBuilder()
    builder = builder.subject_name(
        x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, u"cryptography.io")])
    )
    builder = builder.issuer_name(ca.issuer)
    builder = builder.not_valid_before(datetime.datetime.today() - one_day)
    builder = builder.not_valid_after(datetime.datetime.today() + (one_day * 30))
    builder = builder.serial_number(x509.random_serial_number())
    builder = builder.public_key(public_key)

    cert = builder.sign(
        private_key=private_key, algorithm=hashes.SHA256(), backend=default_backend()
    )

    print(cert.public_bytes(serialization.Encoding.PEM))

然后生成似乎是证书的内容,但是在将数据复制并粘贴到文件中(并以64行换行并按照http://srdevspot.blogspot.com/2011/08/openssl-error0906d064pem.html使用Unix换行符)时,在尝试验证时出现此错误:

$ openssl verify -CAfile ca.crt -untrusted phone.crt
unable to load certificates

希望我缺少一些简单的东西,因为我是这一切的新手!

最后,我会指出,如果密码学不是最好的,我愿意使用另一个密码库。

编辑:

现在,根据Paul的非常有用的回复使用此信息:

def create_cert(cert_authority, private_key):
    one_day = datetime.timedelta(1, 0, 0)
    # Use our private key to generate a public key
    root_key = serialization.load_pem_private_key(
        private_key.encode("ascii"), password=None, backend=default_backend()
    )

    root_cert = x509.load_pem_x509_certificate(
        cert_authority.encode("ascii"), 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())
    )

    # Dump to scratch
    with open("scratch/phone_cert.pem", "wb") as f:
        f.write(cert.public_bytes(encoding=serialization.Encoding.PEM))

    # Return PEM
    cert_pem = cert.public_bytes(encoding=serialization.Encoding.PEM)

    cert_key_pem = cert_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption(),
    )

    return cert_pem, cert_key_pem

这既是保存文件又将创建的证书和私钥作为PEM字符串返回的正确方法吗?

我还发现,当我尝试使用openssl verify -verbose -CAfile ca.crt -untrusted phone_cert.pem针对保存的PEM验证创建的证书时,该命令永不返回-可能是一个单独的问题,但希望您能提出任何建议。

2 个答案:

答案 0 :(得分:2)

由于我是新手并且还不能发表评论,所以我必须发布答案?

我非常依赖Pauls的回答来实现自己的实现,这非常有帮助。但是我必须在CA证书上添加一个扩展名,才能使openssl verify -verbose -CAfile ca.crt client.crt正常工作。

.add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True)添加到根CertificateBuilder即可达到目的。

ca_crt = x509.CertificateBuilder() \
    .subject_name(subject) \
    .issuer_name(issuer) \
    .public_key(ca_key.public_key()) \
    .serial_number(x509.random_serial_number()) \
    .not_valid_before(datetime.datetime.today() - one_day) \
    .not_valid_after(datetime.datetime.today() + (one_day * 365)) \
    .add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True) \
    .sign(ca_key, hashes.SHA256(), default_backend())

其他一切都像保罗一样。

答案 1 :(得分:1)

我在这里看到两个问题。首先,您要创建另一个自签名证书,因此生成的证书不是由CA签名的,它本身就是CA。要更正此问题,请使用CA的私钥(例如,示例中的private_key)进行签名,但是您需要创建与该私钥相关的 new 私钥。新证书,并将其公钥嵌入证书中。

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)

由于尝试将内容复制并粘贴到打印语句中,因此您的输出也有问题。 cert.public_bytes(serialization.Encoding.PEM)的输出将是有效的X509证书,带有分隔符和适当的PEM行长,因此请将其直接写入文件:

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())