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

标签 python cryptography x509certificate m2crypto pem

我希望如果我有一个 X509 证书作为内存中的对象,将其保存为 pem 文件,然后将其重新加载,我最终会得到与开始时相同的证书。然而情况似乎并非如此。我们将原始证书称为 A,从 pem 文件加载的证书称为 B。A.as_text() 与 B.as_text() 相同,但 A.as_pem() 与 B.as_pem() 不同。至少可以说,我对此感到困惑。附带说明一下,如果 A 已由另一个实体 C 签名,则 A 将根据 C 的证书进行验证,但 B 不会。

我编写了一个小示例程序来演示我所看到的内容。当我运行此命令时,会引发第二个 RuntimeError。

谢谢,
布洛克

#!/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))

最佳答案

如果您通过使用 M2Crypto 加载并保存使用 OpenSSL 命令行工具创建的证书(例如,测试目录中的 server.pem 没有 key 和文本)来尝试此操作,您应该会获得相同的文件。

我以为SimpleX509Create.py在 contrib 目录中的工作方式不同,但我对其进行了测试,并且遇到了与您发现的相同问题。显然,我们缺少 OpenSSL 命令行工具所做的一些步骤。

关于python - 使用 M2Crypto 在 pem 文件中保存和加载 X509 证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2726003/

相关文章:

ssl - docker + SSL + apache2 + x509

python - 在树莓派上使用 python 库 brother_ql 进行打印

python - 多线程访问 Python bytearray

c# - 在 C# 中生成 HMAC-SHA1

python - RSA公钥大小python

c# - 如何完全验证 X509 证书?

python - 使用带有 python 的 Selenium 通过部分 ID 选择元素?

python - 使用celery将任务从组件A发送到组件B

java - 使用 SunEC 提供商的generateKeyPair 时出现运行时异常

c# - TLS 之上的 p2p 协议(protocol),同步中间证书