docbow/docbow_project/docbow/timestamp.py

72 lines
2.3 KiB
Python

import rfc3161
import os.path
import importlib
import json
from . import app_settings
PROVIDERS = {
'certum': {
'class': 'rfc3161.RemoteTimestamper',
'url': 'http://time.certum.pl',
'certificate': file(os.path.join(os.path.dirname(__file__), 'certum_certificate.crt')).read(),
},
'fedict': {
'class': 'rfc3161.RemoteTimestamper',
'url': 'http://tsa.belgium.be/connect',
'certificate': file(os.path.join(os.path.dirname(__file__), 'fedict.crt')).read(),
},
'e_szigno': {
'class': 'rfc3161.RemoteTimestamper',
'url': 'https://teszt.e-szigno.hu:440/tsa',
'certificate': file(os.path.join(os.path.dirname(__file__), 'e_szigno_test_tsa2.crt')).read(),
'username': 'teszt',
'password': 'teszt',
'hashname': 'sha256',
},
}
class TimestampingError(RuntimeError):
pass
def timestamp(content, provider=None):
provider = provider or app_settings.TIMESTAMP_PROVIDER
kwargs = PROVIDERS[provider].copy()
klass = kwargs.pop('class')
module, klass = klass.rsplit('.', 1)
module = importlib.import_module(module)
klass = getattr(module, klass)
timestamper = klass(**kwargs)
try:
return timestamper(data=content)
except Exception, e:
raise TimestampingError(e)
def encode_timestamp(provider, tst):
return '%s!%s' % (provider, tst.encode('base64').strip())
def decode_timestamp(encoded_tst):
return encoded_tst.split('!')
def timestamp_json(json_dict, provider=None):
provider = provider or app_settings.TIMESTAMP_PROVIDER
s = json.dumps(json_dict)
if s[-1] != '}':
raise ValueError("timestamp_json takes a dictionnary as argument: %s" % s)
tst, error = timestamp(s, provider=provider)
try:
dt = rfc3161.get_timestamp(tst)
except ValueError:
dt = None
if tst:
return s[:-1] + ',"timestamp": "%s"}' % encode_timestamp(provider, tst), dt
else:
raise TimestampingError(error)
def check_timestamp_json(content, certificate):
content, tst = content.rsplit(',"timestamp": "', 1)
content += '}'
tst = tst[:-2].decode('base64')
return rfc3161.check_timestamp(tst, certificate, data=content)