如何将 Python 密码学 CRL 对象序列化为 PEM

How to Serialize Python Cryptography CRL Object into PEM

我使用 python 加密包来创建 CRL 对象。但我需要将这个对象转换成 PEM 格式。在他们的文档中,他们似乎没有反序列化操作 x509.load_pem_x509_crl 的对立面。在下面代码的末尾,我如何将“crl”转换为 PEM。有什么想法吗?

from cryptography import x509
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import NameOID
import datetime
one_day = datetime.timedelta(1, 0, 0)
private_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048,
)
builder = x509.CertificateRevocationListBuilder()
builder = builder.issuer_name(x509.Name([
    x509.NameAttribute(NameOID.COMMON_NAME, u'cryptography.io CA'),
]))
builder = builder.last_update(datetime.datetime.today())
builder = builder.next_update(datetime.datetime.today() + one_day)
revoked_cert = x509.RevokedCertificateBuilder().serial_number(
    333
).revocation_date(
    datetime.datetime.today()
).build()
builder = builder.add_revoked_certificate(revoked_cert)
crl = builder.sign(
    private_key=private_key, algorithm=hashes.SHA256(),
)
# how to convert crl to PEM?

可以使用CertificateRevocationListBuilder#sign() method returns a CertificateRevocationList object whose public_bytes()方法进行序列化

反序列化是用 x509.load_pem_x509_crl() 完成的。

示例:

...

# Serialize
from cryptography.hazmat.primitives import serialization
pem = crl.public_bytes(encoding=serialization.Encoding.PEM)
print(pem.decode('utf8'))

# Deserialize
from cryptography import x509
crl = x509.load_pem_x509_crl(pem)
pem = crl.public_bytes(encoding=serialization.Encoding.PEM) # Check
print(pem.decode('utf8')) 

例如以下输出:

-----BEGIN X509 CRL-----
MIIBfDBmAgEBMA0GCSqGSIb3DQEBCwUAMB0xGzAZBgNVBAMMEmNyeXB0b2dyYXBo
eS5pbyBDQRcNMjEwOTExMDg0OTI3WhcNMjEwOTEyMDg0OTI3WjAVMBMCAgFNFw0y
MTA5MTEwODQ5MjdaMA0GCSqGSIb3DQEBCwUAA4IBAQCmO+pCzndqgeZBgfMNUsk4
SSVQg+lJ5W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