具有给定扩展集的Python pyOpenSSL签名证书

时间:2017-01-21 17:17:11

标签: python openssl pyopenssl

给定包含这些扩展集的CA文件:

[ usr_cert ]
# Extensions for client certificates (`man x509v3_config`).
basicConstraints = CA:FALSE
nsCertType = client, email
nsComment = "OpenSSL Generated Client Certificate"
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
keyUsage = critical, nonRepudiation, digitalSignature, keyEncipherment
extendedKeyUsage = clientAuth, emailProtection

[ server_cert ]
# Extensions for server certificates (`man x509v3_config`).
basicConstraints = CA:FALSE
nsCertType = server
nsComment = "OpenSSL Generated Server Certificate"
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer:always
keyUsage = critical, digitalSignature, keyEncipherment
extendedKeyUsage = serverAuth

使用"常规" openssl我可以根据CSR和以下声明创建证书:

openssl ca -config intermediate/openssl.cnf -extensions server_cert -days 375 -notext -md sha256 -in intermediate/csr/www.example.com.csr.pem -out intermediate/certs/www.example.com.cert.pem

我想使用pyOpenSSL做同样的事情,但是,我无法在crypto.X509()类上找到允许我这样做的方法:

cert = crypto.X509()
cert.set_issuer(caCert.get_subject())
cert.set_serial_number(1)
cert.set_notAfter("20170201000000Z")
cert.set_notBefore("20160201000000Z")
cert.set_subject(deviceCsr.get_subject())
cert.set_issuer(issuer=caCert.get_issuer())
cert.set_pubkey(deviceCsr.get_pubkey())
cert.sign(CAprivatekey, "sha1")

我可以看到cert.add_extensions,但这似乎不允许添加"模板",而是明确的扩展名,例如critical, digitalSignature, keyEncipherment等。

创建证书时,有没有办法在pyOpenSSL中指定"模板" /扩展名?

编辑:考虑到这一点,我意识到pyOpenSSL根本不关心ca.conf文件,它只是使用ca证书来签署有问题的新服务器证书,那就是它。所以我想我的问题应该是:有没有办法让pyopenssl使用ca.conf文件中的配置,或者我是否必须在代码中创建所有选项?如果是真的,那么看起来更容易将python shell输出到openssl以生成证书。

1 个答案:

答案 0 :(得分:1)

这里是有关如何设置各种扩展名的示例。每个扩展都有不同的数据/有效载荷。

您获得了扩展名,它们是关键标志,最后是扩展数据。

extensions = [
    crypto.X509Extension(b'basicConstraints', False, b'CA:FALSE'),
    crypto.X509Extension(b'keyUsage', 'digitalSignature, nonRepudiation', keyusage),
    crypto.X509Extension(b'extendedKeyUsage', True, b'serverAuth'),
    crypto.X509Extension(b'subjectAltName', False, b'DNS:www.ex.com,IP:1.2.3.4')
    ]
cert.add_extensions(extensions)