使用M2Crypto在pem文件中保存和加载X509证书

2024-05-17 09:02:43 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我在内存中有一个X509证书作为一个对象,将它保存为pem文件,然后再将其加载回内存中,我将得到与我开始时相同的证书。然而,情况似乎并非如此。让我们调用原始证书A,从pem文件B.A.as_text()加载的证书与B.as_text()相同,但A.as_pem()与B.as_pem()不同。至少可以说,我被这个弄糊涂了。作为补充说明,如果a已经由另一个实体C签名,那么a将根据C的证书进行验证,但B不会。在

我已经建立了一个小的示例程序来演示我所看到的。当我运行这个时,会引发第二个运行时错误。在

谢谢,
布洛克

#!/usr/bin/python2.6

import M2Crypto as m2
import time

cur_time = m2.ASN1.ASN1_UTCTIME()
cur_time.set_time(int(time.time()) - 60*60*24)

expire_time = m2.ASN1.ASN1_UTCTIME()
# Expire certs in 1 hour.
expire_time.set_time(int(time.time()) + 60 * 60 * 24)


cs_rsa = m2.RSA.gen_key(1024, 65537, lambda: None)
cs_pk = m2.EVP.PKey()
cs_pk.assign_rsa(cs_rsa)
cs_cert = m2.X509.X509()

# These two seem the minimum necessary to make the as_text function call work
# at all
cs_cert.set_not_before(cur_time)
cs_cert.set_not_after(expire_time)

# This seems necessary to fill out the complete cert without errors.
cs_cert.set_pubkey(cs_pk)

# I've tried with the following set lines commented out and not commented.
cs_name = m2.X509.X509_Name()
cs_name.C = "US"
cs_name.ST = "CA"
cs_name.OU = "Fake Org CA 1"
cs_name.CN = "www.fakeorg.dex"
cs_name.Email = "cs1@www.fakeorg.dex"
cs_cert.set_subject(cs_name)
cs_cert.set_issuer_name(cs_name)
cs_cert.sign(cs_pk, md="sha256")

orig_text = cs_cert.as_text()
orig_pem = cs_cert.as_pem()

print "orig_text:\n%s" % orig_text

cs_cert.save_pem("/tmp/foo")

tcs = m2.X509.load_cert("/tmp/foo")

tcs_text = tcs.as_text()
tcs_pem = tcs.as_pem()

if orig_text != tcs_text:
        raise RuntimeError(
            "Texts were different.\nOrig:\n%s\nAfter load:\n%s" %
            (orig_text, tcs_text))

if orig_pem != tcs_pem:
        raise RuntimeError(
            "Pems were different.\nOrig:\n%s\nAfter load:\n%s" %
            (orig_pem, tcs_pem))

Tags: textnamecerttimeascspem证书
1条回答
网友
1楼 · 发布于 2024-05-17 09:02:43

如果您使用OpenSSL命令行工具创建的证书(例如,tests目录中的server.pem没有密钥和文本),通过加载并用M2Crypto保存它,您应该得到相同的文件。在

我认为contrib目录中的SimpleX509Create.py工作方式不同,但是我测试了它,我遇到了您发现的相同问题。显然,我们缺少OpenSSL命令行工具所做的某些步骤。在

相关问题 更多 >