使用pyopenssl创建自签名证书时出错

时间:2019-06-13 16:18:11

标签: python-3.x x509certificate pyopenssl

from OpenSSL import crypto, SSL
from socket import gethostname
from pprint import pprint
from time import gmtime, mktime

CERT_FILE = "selfsigned.crt"
KEY_FILE = "private.key"

def create_self_signed_cert():

    # create a key pair
    k = crypto.PKey()
    k.generate_key(crypto.TYPE_RSA, 1024)

    # create a self-signed cert
    cert = crypto.X509()
    cert.get_subject().C = "UK"
    cert.get_subject().ST = "London"
    cert.get_subject().L = "London"
    cert.get_subject().O = "Dummy Company Ltd"
    cert.get_subject().OU = "Dummy Company Ltd"
    cert.get_subject().CN = gethostname()
    cert.set_serial_number(1000)
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(10*365*24*60*60)
    cert.set_issuer(cert.get_subject())
    cert.set_pubkey(k)
    cert.sign(k, 'sha1')

    open(CERT_FILE, "wt").write(
        crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
    open(KEY_FILE, "wt").write(
        crypto.dump_privatekey(crypto.FILETYPE_PEM, k))

create_self_signed_cert()

我正在尝试创建自我证书,但显示错误:

crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
TypeError: write() argument must be str, not bytes

请帮助我。

3 个答案:

答案 0 :(得分:0)

我认为os.write()将能够写入crypto.dump_certificate返回的缓冲区:


import os

f = os.open(CERT_FILE)
os.write(f, crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
os.close(f)

答案 1 :(得分:0)

在python 3中,我使用了解码

NewResultVO<T>{
  private String code;
  private T data; // T is your ResultVO or other VO.
}

答案 2 :(得分:0)

您可以使用“写入二进制”文件打开模式
通过用"wt"中的"wb"替换值open(FILE, "wt")