如何在python中验证SSL证书?

u1ehiz5o  于 2022-12-04  发布在  Python
关注(0)|答案(4)|浏览(255)

我需要验证证书是否由我的自定义CA签名。使用OpenSSL命令行实用程序可以轻松完成此操作:

# 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

但我需要在Python中做同样的事情,而且我真的不想调用命令行实用程序。据我所知,M2 Crypto是OpenSSL的“最完整”Python Package 器,但我不知道如何完成命令行实用程序所做的事情!
参考this question,了解如何在C代码中完成同样的任务,我已经了解了一半。* 我选择的变量名与openssl verify命令行实用程序的源代码中使用的变量名相同,请参见openssl-xxx/apps/verify.c。*

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

我已经完成了一半,但是我似乎无法完成验证!我是否遗漏了什么?我是否应该使用M2 Crypto中的其他函数?我是否应该寻找一个完全不同的OpenSSL的python Package 器?我如何才能在python中完成这项任务!??

  • 请注意,我使用证书来加密/解密文件,因此我对使用基于SSL连接的对等证书验证(具有already been answered)不感兴趣,因为我没有任何SSL连接。*
xpcnnkqh

xpcnnkqh1#

你不能用普通的M2Crypto来实现这一点,因为它没有 Package 一些必需的函数。好消息是,如果你安装了SWIG,你可以自己 Package 这些函数,并使用M2Crypto代码。我不久前为自己制作了一个带有一些额外函数的模块,并决定现在发布它,因为它可以进行这种验证。你可以在这里检查它:https://github.com/abbot/m2ext。这是如何使用此模块验证证书的示例:

import sys
from m2ext import SSL
from M2Crypto import X509

print "Validating certificate %s using CApath %s" % (sys.argv[1], sys.argv[2])
cert = X509.load_cert(sys.argv[1])
ctx = SSL.Context()
ctx.load_verify_locations(capath=sys.argv[2])
if ctx.validate_certificate(cert):
    print "valid"
else:
    print "invalid"

不幸的是,M2Crypto的开发似乎停滞不前(在过去的两年里,bug跟踪器中没有关闭的问题),维护者忽略了我的bug和电子邮件与这些和其他一些补丁...

ldxq2e6h

ldxq2e6h2#

使用此命令:/应用程序/Python\ 3.9/安装\证书.命令
不要改变空格,只要确保替换为您的python版本即可

7fhtutme

7fhtutme3#

您可以使用X509.verify方法来检查证书是否是用CA的私钥签名的,因为它在后台调用OpenSSL的x509_verify,我相信它也可以正确地检查所有参数(比如过期):

from M2Crypto X509

cert = X509.load_cert("certificate-filename")

caCertificate = X509.load_cert("trusted-ca-filename")
caPublic = caCertificate.get_pubkey()

if cert.verify(caPublic) == 1:
     # Certificate is okay!
else:
     # not okay
hmae6n7t

hmae6n7t4#

正如您所说,OpenSSL需要连接
M2 Crypto没有良好的验证
这个巧妙的主意怎么样:

import os 
os.system('openssl verify -CAfile ../ca-cert.pem bob.cert')

它很丑,但它很有效!

相关问题