csadan
csadan

Reputation: 291

timestamp query with python

I want to create a .tsq file like openssl with command:

openssl ts -query -data <file> -no_nonce -sha512 -out <out.tsq>

I want to implement this with python, Anyone know how to do this, any module or something like that?

Upvotes: 2

Views: 1444

Answers (3)

matheusd
matheusd

Reputation: 11

To expand upon @j-f-sebastian's answer, if you want to hash using sha-256 (or any 256 bit hash function), use the following constant:

b'06\x02\x01\x01010\r\x06\t`\x86H\x01e\x03\x04\x02\x01\x05\x00\x04 '

(and yes, the last character is an empty space)

Upvotes: 1

jfs
jfs

Reputation: 414069

Here's a Python 3 implementation of the 3rd idea from @jariq's answer:

#!/usr/bin/env python3
"""Emulate `openssl ts -query -data <file> -no_nonce -sha512 -out <out.tsq>`

   Usage: %(prog)s <file> [<out.tsq>]

If <out.tsq> is not given; use <file> name and append '.tsq' suffix
"""
import hashlib
import sys
from functools import partial

def hash_file(filename, hashtype, chunksize=2**15, bufsize=-1):
    h = hashtype()
    with open(filename, 'rb', bufsize) as file:
        for chunk in iter(partial(file.read, chunksize), b''):
            h.update(chunk)
    return h

try: # parse command-line arguments
    filename, *out_filename = sys.argv[1:]
    out_filename.append(filename + '.tsq')
except ValueError:
    sys.exit(__doc__ % dict(prog=sys.argv[0]))

h = hash_file(filename, hashlib.sha512) # find hash of the input file
with open(out_filename[0], 'wb') as file: # write timestamp query
    file.write(b'0V\x02\x01\x010Q0\r\x06\t`\x86H\x01'
               b'e\x03\x04\x02\x03\x05\x00\x04@')
    file.write(h.digest())

Upvotes: 1

jariq
jariq

Reputation: 12108

Right now I can think of three different approaches:

  1. Use some premade python module of unknown quality like python-rfc3161 mentioned by @J.F.Sebastian in his comment.
  2. Use hashlib module to compute SHA512 hash of the data you want to timestamp and then use pyasn1 module to construct and encode TimeStampReq request structure defined in RFC3161.
  3. Use hashlib module to compute SHA512 hash of the data you want to timestamp and pre-pend these bytes 0x30 0x56 0x02 0x01 0x01 0x30 0x51 0x30 0x0D 0x06 0x09 0x60 0x86 0x48 0x01 0x65 0x03 0x04 0x02 0x03 0x05 0x00 0x04 0x40 to the hash value. This should work for you because OpenSSL command you have provided is creating TS request which does not contain any variable part (such as nonce or policy OID) so the first part of the request structure will not change no matter what input data you will use.

Upvotes: 2

Related Questions