timestamp: add a local mode of timestamping using Django signing

This commit is contained in:
Benjamin Dauvergne 2013-01-04 12:05:51 +01:00
parent c3b2d05505
commit db02708d44
1 changed files with 32 additions and 1 deletions

View File

@ -1,17 +1,35 @@
import rfc3161
import os.path
import hashlib
import datetime
from django.utils import simplejson
from django.core import signing
__certificate_path = os.path.join(os.path.dirname(__file__), 'certum_certificate.crt')
__timestamper = rfc3161.RemoteTimestamper('http://time.certum.pl',
certificate=open(__certificate_path).read())
__timestamper = None
def timestamp(content):
return __timestamper(data=content)
def timestamp_json(json_dict):
if __timestamper:
return timestamp_json_rfc3161(json_dict)
else:
return timestamp_json_local(json_dict)
def timestamp_json_local(json_dict):
s = simplejson.dumps(json_dict)
if s[-1] != '}':
raise ValueError("timestamp_json takes a dictionnary as argument: %s" % s)
signer = signing.Signer()
signed_string = signer.sign('{0}:{1}'.format(hashlib.sha1(s).hexdigest(), datetime.datetime.utcnow().isoformat()))
return s[:-1] + ',"timestamp": "%s"}' % signed_string
def timestamp_json_rfc3161(json_dict):
s = simplejson.dumps(json_dict)
if s[-1] != '}':
raise ValueError("timestamp_json takes a dictionnary as argument: %s" % s)
@ -24,9 +42,22 @@ def timestamp_json(json_dict):
else:
return ValueError(error)
def check_timestamp_json(content, certificate):
def check_timestamp_json_rfc3161(content, certificate):
content, tst = content.rsplit(',"timestamp": "', 1)
content += '}'
tst = tst[:-2].decode('base64')
return rfc3161.check_timestamp(tst, certificate, data=content)
def check_timestamp_json_local(content):
content, tst = content.rsplit(',"timestamp": "', 1)
content += '}'
tst = tst[:-2]
signer = signing.Signer()
try:
signed_string = signer.unsign(tst)
except signing.BadSignature:
return False
digest, tst = signed_string.split(':', 1)
if digest != hashlib.sha1(content).hexdigest():
return False
return datetime.datetime.strptime(tst, '%Y-%m-%dT%H:%M:%S.%f')