I need to verify that a certificate was signed by my custom CA. Using OpenSSL command-line utilities this is easy to do:
# Custom CA file: ca-cert.pem
# Cer
You can use the unfortunately undocumented X509.verify method to check whether the certificate was signed with the CA's private key. As this calls OpenSSL's x509_verify
in the background, I'm sure this also checks all parameters (like expiration) correctly:
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
You can't do this with plain M2Crypto, since it does not wrap some of the required functions. Good news is if you have SWIG installed you can wrap those yourself and use with M2Crypto code. I've made a module with some extra functions for myself some time ago, and decided to publish it now, since it does this kind of validation. You can check it here: https://github.com/abbot/m2ext. This is an example how to validate a certificate using this module:
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"
Unfortunately M2Crypto development seems to be stagnant (no closed issues in bug tracker for the last two years) and the maintainer was ignoring my bugs and emails with these and some other patches...
Like you said, OpenSSL requires connection
M2Crypto doesn't have good verification
How about this ingenious idea:
import os
os.system('openssl verify -CAfile ../ca-cert.pem bob.cert')
Its ugly, but it works!