使用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的python库 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) and 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 <CA cert path> <name of device cert file>
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屋!