加载证书时,Pythons M2Crypto在ssl_ctx_load_verify_locations中引发异常

时间:2010-09-29 23:44:43

标签: python django ssl-certificate m2crypto

M2Crypto在加载SSL CA证书时引发TypeError。我从Django模型的实例中获取SSL证书的路径。我的代码工作得很好,因为我从Django模型中拉出了证书的路径

我的代码:

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)

引发

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 *'

但是此代码可以正常使用

from M2Crypto import SSL
ctx = SSL.Context()
ctx.load_verify_locations('/path/to/my/certificates/certificate.cer')

1 个答案:

答案 0 :(得分:2)

刚刚解决了!

load_verify_locations()函数需要字符串对象,而不是 unicode 对象。

Django默认使用unicode,因此在传递到 load_verify_locations()之前,需要将证书路径转换为字符串。所以:

ctx.load_verify_locations(str(m.ca_file))