在 python 中使用 CA 根证书从客户端签署 CSR [英] Sign CSR from client using CA root certificate in python
问题描述
我是 python 新手,还在学习它,所以我的问题可能有点幼稚.请多多包涵;)
I am new to python and still learning it so my question can be little naive. Please bear with it ;)
问题是客户端将发送 CSR,我想用我的 CA 根证书对其进行签名并将签名的证书返回给客户端.
The problem is client will be sending CSR and I want to sign it with my CA root certificate and return the signed certificate back to client.
我一直在使用这个命令来使用命令行来完成它
I have been using this command to do it using command line
openssl x509 -req -in device.csr -CA root.pem -CAkey root.key -CAcreateserial -out device.crt -days 500
我想用 python 实现同样的事情.我遇到了用于 openssl pyopenssl
same thing I want achieve using python. I have come across python library for openssl pyopenssl
可以使用这个库吗?如何 ?还是我应该选择 M2Crypto?
is it possible using this library ? How ? or shoudl I go for M2Crypto ?
推荐答案
你确实可以使用 pyOpenSSL.正如您所说,您已经拥有 CA 根证书和私钥,并且 CSR 将由客户端发送,然后您可以使用加密功能从文件中读取所有这些(CA 证书、私钥和设备 CSR)或设法拥有他们在缓冲区.
You can indeed go with pyOpenSSL. As you are saying you already have CA root certificate and a private key, and CSR will be sent by a client then you can use functions of crypto to read all those ( CA cert, private key and Device CSR ) from file or manage to have them in buffer.
使用以下功能开始.在 python 解释器上检查 dir(crypto) 和 crypto.function_name.__doc__
以获取更多信息 :) 您需要从 pyOpenSSL 导入加密
Use below functions to start with. Check dir(crypto) and crypto.function_name.__doc__
on python interpreter for more info :) You need to import crypto from pyOpenSSL
- crypto.load_certificate_request() - 获取设备 CSR obj
- crypto.load_privatekey() - 获取 CA 私钥的私钥 obj
- crypto.load_certificate() - 获取 CA 根证书
然后你可以编写简单的函数来返回证书
then you can write simple funcation to return certificate
def create_cert():
cert = crypto.X509()
cert.set_serial_number(serial_no)
cert.gmtime_adj_notBefore(notBeforeVal)
cert.gmtime_adj_notAfter(notAfterVal)
cert.set_issuer(caCert.get_subject())
cert.set_subject(deviceCsr.get_subject())
cert.set_pubkey(deviceCsr.get_pubkey())
cert.sign(CAprivatekey, digest)
return cert
其中 caCert 、 deviceCsr 和 CAprivatekey 是上述三个函数的值.现在您已经有了证书,您可以使用 crypto.dump_certificate(crypto.FILETYPE_PEM, cert)
将其写入文件,并选择文件名.
where caCert , deviceCsr and CAprivatekey are values from above three funcations.
Now that you have certificate with you, you can write this to a file using crypto.dump_certificate(crypto.FILETYPE_PEM, cert)
with file name of your choice.
您可以根据需要修改此功能.之后,您可以使用 openssl 命令使用 CA 根证书验证生成的设备证书,例如openssl verify -CApath
You can modify this function as per your requirement. After this you can verify generated device certificate with CA root certificate with openssl command e.g. openssl verify -CApath <CA cert path> <name of device cert file>
您还可以浏览 github 中的几个示例.M2Crypto 示例 , pyOpenSSL 示例
You can also go through few examples from github. M2Crypto Example , pyOpenSSL example
希望这能让您对实现有所了解
Hope this gives you idea about the implementation
这篇关于在 python 中使用 CA 根证书从客户端签署 CSR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!