通过Python和shell生成证书
之前在linux通过 openssl 创建证书,格式转换,超级方便,但是迁移到Python,就有更多选择了
Python库中 有好多关于证书的一些类库 本次是通过 OpenSSL.crypto 这个库来进行操作
代码是基于Python3.6的环境
制作key或者csr证书
from OpenSSL.crypto import (dump_certificate_request, dump_privatekey, PKey, TYPE_RSA, X509Req, FILETYPE_PEM)
def make_csr_content(csr_file_path, private_key_path):
key = PKey()
key.generate_key(TYPE_RSA, 2048)
req = X509Req()
req.get_subject().CN = 'FLY APP'
req.get_subject().O = 'FLY APP Inc'
req.get_subject().OU = 'IT'
req.get_subject().L = 'BJ'
req.get_subject().ST = 'BJ'
req.get_subject().C = 'CN'
req.get_subject().emailAddress = 'flyapps@126.com'
req.set_pubkey(key)
req.sign(key, 'sha256')
csr_content = dump_certificate_request(FILETYPE_PEM, req)
with open(csr_file_path, 'wb+') as f:
f.write(csr_content)
with open(private_key_path, 'wb+') as f:
f.write(dump_privatekey(FILETYPE_PEM, key))
return csr_content
换成在linux下,openssl命令如下
openssl genrsa -out aps_development.key 2048
openssl req -new -sha256 -key aps_development.key -out aps_development.csr
果然linux命令很精简,很强大
生成pem证书
既然已经有了csr证书,拿着证书去苹果开发者平台,得到 cer证书,这个在Python是如何操作的呢?
from OpenSSL.crypto import (FILETYPE_PEM, load_certificate, FILETYPE_ASN1, dump_certificate)
def make_pem(cer_content, pem_path):
cert = load_certificate(FILETYPE_ASN1, cer_content)
with open(pem_path, 'wb+') as f:
f.write(dump_certificate(FILETYPE_PEM, cert))
对应的shell命令如下:
openssl x509 -inform DER -outform PEM -in aps_development.cer -out aps_development.pem
p12证书生成
既然key和cert都有了,那么,p12证书也可以出来了
Python代码如下
from OpenSSL.crypto import (FILETYPE_PEM, load_certificate, load_privatekey, PKCS12)
def export_p12(pem_file, key_file, p12_file, password):
certificate = load_certificate(FILETYPE_PEM, open(pem_file, 'rb').read())
private_key = load_privatekey(FILETYPE_PEM, open(key_file, 'rb').read())
p12 = PKCS12()
p12.set_certificate(certificate)
p12.set_privatekey(private_key)
with open(p12_file, 'wb+') as f:
f.write(p12.export(password))
对应shell 命令如下,记得要输密码
openssl pkcs12 -inkey aps_development.key -in aps_development.pem -export -out aps_development.p12
|