64 lines
2.1 KiB
Python
64 lines
2.1 KiB
Python
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)
|
|
try:
|
|
tst, error = timestamp(s)
|
|
except Exception, e:
|
|
raise RuntimeError("unable to communicate with timestamping service", e)
|
|
if tst:
|
|
return s[:-1] + ',"timestamp": "%s"}' % tst.encode('base64').strip()
|
|
else:
|
|
return ValueError(error)
|
|
|
|
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')
|