Python 创建电子证书

import OpenSSL
import os
from cryptography.hazmat.primitives import serialization
import random
from datetime import datetime as dt
from datetime import timedelta
try:
    from cryptography import x509
    from cryptography.x509.oid import NameOID
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives import hashes
    from cryptography.hazmat.primitives.asymmetric import rsa
except ImportError:
    raise TypeError("Using ad-hoc certificates requires the cryptography library.")
def generate_key(public_exponent=100253,key_size=2048):
    pkey = rsa.generate_private_key(
        public_exponent=65537, key_size=2048, backend=default_backend()
    )
    return pkey
def generate_adhoc_ssl_pair(cn=None,pkey=None,
                            sub_user_name='A',sub_common_name='local_host',sub_country_name='cn',
                            isr_user_name='A',isr_common_name='local_host',isr_country_name='cn',
                            sign=None
                            ):
    if pkey == None:
        pkey = rsa.generate_private_key(
            public_exponent=65537, key_size=2048, backend=default_backend()
        )

    # pretty damn sure that this is not actually accepted by anyone
    if cn is None:
        cn = u"*"
    # subject:使用者
    subject = x509.Name(
        [
            x509.NameAttribute(NameOID.ORGANIZATION_NAME, sub_user_name),
            x509.NameAttribute(NameOID.COMMON_NAME, sub_common_name),
            x509.NameAttribute(NameOID.COUNTRY_NAME, sub_country_name)
        ]
    )

    # issuer:颁发者
    issuer = x509.Name(
        [
            x509.NameAttribute(NameOID.ORGANIZATION_NAME, isr_user_name),
            x509.NameAttribute(NameOID.COMMON_NAME, isr_common_name),
            x509.NameAttribute(NameOID.COUNTRY_NAME, isr_country_name),
        ]
    )

    # cert使用私钥签名(.sign(私钥,摘要生成算法,填充方式)),使用x509.CertificateBuilder()方法生成证书,证书属性使用下列函数叠加补充
    if sign == None:
        private_key = pkey
    else:
        private_key = sign
    cert = (
        x509.CertificateBuilder()
            .subject_name(subject)
            .issuer_name(issuer)
            .public_key(pkey.public_key())
            .serial_number(x509.random_serial_number())
            .not_valid_before(dt.utcnow() + timedelta())
            .not_valid_after(dt.utcnow() + timedelta(days=365))
            .sign(private_key, hashes.SHA256(), default_backend())
    )
    # 最终生成的证书与密钥对为类对象,要保存在文件中还需要进一步转换成字节格式
    return cert
if __name__ == '__main__':
    print('创建X509证书')
    print('是否建立CA证书(Y/N)')
    C=input()
    if C =="Y":
        print('开始创建密钥对')
        pkey = generate_key(random.randint(0,10000000),2048)
        print('机构名: ')
        orgName=input()
        print('通用名: ')
        comName=input()
        print('国家: ')
        countryName=input()
        cert=generate_adhoc_ssl_pair(cn=None, pkey=pkey,
                                    sub_user_name=orgName, sub_common_name=comName, sub_country_name=countryName,
                                    isr_user_name=orgName, isr_common_name=comName, isr_country_name=countryName
                                    )
        private_text = pkey.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=serialization.NoEncryption()
        )
        print(private_text)

        # 将私钥字节串保存到文件中
        with open(orgName+'_signed_pkey.key', mode='wb') as pkey_file:
            pkey_file.write(private_text)

        cert_text = cert.public_bytes(serialization.Encoding.PEM)
        print(cert_text)
        # 将证书字节串保存到文件中
        with open(orgName+'_signed.cer', mode='wb') as cert_file:
            cert_file.write(cert_text)
    if C == "N":
        print('请输入颁发机构:')
        lsr=input()
        if not os.path.exists(lsr+'_signed.cer') or not os.path.exists(lsr+'_signed_pkey.key'):
            print('未发现颁发者')
        else:
            print('载入CA证书')
            with open(lsr+'_signed.cer', mode='r') as cert_file:
                isr_cert_text=cert_file.read()
            #print(cert_text)
            isr_cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
                                                   isr_cert_text)
            isr_certIssue = isr_cert.get_issuer()

            for item in isr_certIssue.get_components():
                if item[0].decode("utf-8") == 'O':
                    lsr_org_name = item[1].decode("utf-8")
                elif item[0].decode("utf-8") == 'CN':
                    lsr_common_name = item[1].decode("utf-8")
                elif item[0].decode("utf-8") == 'C':
                    lsr_country_name = item[1].decode("utf-8")
            print('开始创建密钥对')
            pkey = generate_key(random.randint(0, 10000000), 2048)
            print('机构名: ')
            orgName = input()
            print('通用名: ')
            comName = input()
            print('国家: ')
            countryName = input()

            with open(lsr+'_signed_pkey.key', 'r') as f:
                lsr_private_key_text = f.read()
            lsr_private_key = OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM,
                                                     lsr_private_key_text)
            lsr_private_key = lsr_private_key.to_cryptography_key()
            cert = generate_adhoc_ssl_pair(cn=None, pkey=pkey,
                                       sub_user_name=orgName, sub_common_name=comName, sub_country_name=countryName,
                                       isr_user_name=lsr_org_name, isr_common_name=lsr_common_name, isr_country_name=lsr_country_name,
                                        sign=lsr_private_key
                                       )
            private_text = pkey.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.TraditionalOpenSSL,
                encryption_algorithm=serialization.NoEncryption()
            )
            print(private_text)

            # 将私钥字节串保存到文件中
            with open(orgName + '_signed_pkey.key', mode='wb') as pkey_file:
                pkey_file.write(private_text)

            cert_text = cert.public_bytes(serialization.Encoding.PEM)
            print(cert_text)
            # 将证书字节串保存到文件中
            with open(orgName + '_signed.cer', mode='wb') as cert_file:
                cert_file.write(cert_text)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值