<p>我需要验证证书是否由我的自定义CA签名。使用OpenSSL命令行实用程序很容易做到:</p>
<pre><code># Custom CA file: ca-cert.pem
# Cert signed by above CA: bob.cert
$ openssl verify -CAfile test-ca-cert.pem bob.cert
bob.cert: OK
</code></pre>
<p>但是我需要在Python中做同样的事情,我真的不想调用命令行实用程序。据我所知,m2cypto是OpenSSL的“最完整”python包装器,但我不知道如何完成命令行实用程序的功能!</p>
<p>参考<a href="https://stackoverflow.com/questions/3288694/validating-x-509-certificate-on-linux">this question</a>了解如何在C代码中完成相同的任务,我已经能够得到大约一半的结果。<em>我选择的变量名与openssl verify命令行实用程序的源代码中使用的变量名相同,请参见<code>openssl-xxx/apps/verify.c</code>。</em></p>
<pre><code>import M2Crypto as m2
# Load the certificates
cacert = m2.X509.load_cert('test-ca-cert.pem') # Create cert object from CA cert file
bobcert = m2.X509.load_cert('bob.cert') # Create cert object from Bob's cert file
cert_ctx = m2.X509.X509_Store() # Step 1 from referenced C code steps
csc = m2.X509.X509_Store_Context(cert_ctx) # Step 2 & 5
cert_ctx.add_cert(cacert) # Step 3
cert_ctx.add_cert(bobcert) # ditto
# Skip step 4 (no CRLs to add)
# Step 5 is combined with step 2...I think. (X509_STORE_CTX_init: Python creates and
# initialises an object in the same step)
# Skip step 6? (can't find anything corresponding to
# X509_STORE_CTX_set_purpose, not sure if we need to anyway???)
#
# It all falls apart at this point, as steps 7 and 8 don't have any corresponding
# functions in M2Crypto -- I even grepped the entire source code of M2Crypto, and
# neither of the following functions are present in it:
# Step 7: X509_STORE_CTX_set_cert - Tell the context which certificate to validate.
# Step 8: X509_verify_cert - Finally, validate it
</code></pre>
<p>所以我已经走到一半了,但我似乎无法真正完成验证!我遗漏了什么吗?M2Crypto中是否还有其他函数需要我使用?我应该寻找一个完全不同的OpenSSL的python包装器吗?我怎样才能用python!?!?</p>
<p><em>请注意,我使用证书来加密/解密文件,所以我不想使用基于SSL连接的对等证书验证(它有<a href="https://stackoverflow.com/questions/1087227/validate-ssl-certificates-with-python">already been answered</a>),因为我没有任何SSL连接。</em></p>