Pythons M2Crypto raises exception in ssl_ctx_load_verify_locations when loading certificates
M2Crypto raises a TypeError when loading SSL CA certificates. I'm getting the path of an SSL certificate from an instance of a Django model. My开发者_如何转开发 code worked perfectly because I was pulling the path of the certificate from a Django model
My code:
from M2Crypto import SSL
from django.db import models
class MyModel(models.Model):
ca_file = models.FilePathField(path='/path/to/my/certificates/')
m = MyModel(ca_file='/path/to/my/certificates/certificate.cer')
m.save()
ctx = SSL.Context()
ctx.load_verify_locations(m.ca_file)
Raises:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/django/lib/datalivelib/utils/https.py", line 51, in do_https
if ctx.load_verify_locations(ca_file) != 1:
File "/usr/lib/pymodules/python2.6/M2Crypto/SSL/Context.py", line 131, in load_verify_locations
return m2.ssl_ctx_load_verify_locations(self.ctx, cafile, capath)
TypeError: in method 'ssl_ctx_load_verify_locations', argument 2 of type 'char const *'
However this code works fine
from M2Crypto import SSL
ctx = SSL.Context()
ctx.load_verify_locations('/path/to/my/certificates/certificate.cer')
Just worked it out!
The load_verify_locations() function is expecting a string object, not a unicode object.
Django uses unicode by default, so the certificate path needs to be converted to a string before passed into load_verify_locations(). So:
ctx.load_verify_locations(str(m.ca_file))
精彩评论