python时间戳查询

2024-09-29 23:30:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用以下命令创建一个.tsq文件,比如openssl:

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

我想用python实现这个,有人知道怎么做吗,任何模块或类似的东西?在


Tags: 模块文件no命令dataoutqueryfile
3条回答

现在我可以想出三种不同的方法:

  1. 使用一些质量未知的预制python模块,比如@J.F.Sebastian在评论中提到的python-rfc3161。在
  2. 使用hashlib module计算要标记时间戳的数据的SHA512哈希,然后使用pyasn1 module构造并编码RFC3161中定义的^{cd1>}请求结构。在
  3. 使用hashlib module计算要标记时间戳的数据的SHA512哈希值,并将这些字节0x30 0x56 0x02 0x01 0x01 0x30 0x51 0x30 0x0D 0x06 0x09 0x60 0x86 0x48 0x01 0x65 0x03 0x04 0x02 0x03 0x05 0x00 0x04 0x40前置到哈希值。这应该对您有用,因为您提供的OpenSSL命令正在创建不包含任何变量部分(例如nonce或policy OID)的TS请求,因此无论您将使用什么输入数据,请求结构的第一部分都不会更改。在

要扩展@j-f-sebastian's answer,如果要使用sha-256(或任何256位哈希函数)哈希,请使用以下常量:

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

(是的,最后一个字符是空白)

下面是@jariq's answer中第3个想法的Python3实现:

#!/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())

相关问题 更多 >

    热门问题