如何通过OpenSSL PHP扩展生成TimeStampQuery(无需外部命令)
Generate TimeStampQuery (TSQ) with PHP OpenSSL Extension
Yes, you absolutely can create a TSQ directly via PHP's built-in OpenSSL extension—no need to spawn external processes. Below is a complete implementation that replicates the behavior of your openssl ts -query command:
Full Code Example
<?php // Read the input file content (matches `-data input_file.xml`) $inputData = file_get_contents('input_file.xml'); if ($inputData === false) { die("Error: Could not read input_file.xml"); } // Initialize a new TimeStampQuery object $tsq = openssl_ts_query_new(); if ($tsq === false) { die("Error: Failed to create TSQ context"); } // Configure TSQ parameters: SHA-512 digest, no nonce (matches `-sha512 -no_nonce`) $tsqParams = [ 'digest_alg' => 'sha512', 'nonce' => null, // Disables nonce generation ]; if (!openssl_ts_query_set_params($tsq, $tsqParams)) { die("Error: Failed to set TSQ parameters"); } // Attach the input data (the extension automatically computes the SHA-512 hash) if (!openssl_ts_query_add_data($tsq, $inputData)) { die("Error: Failed to add data to TSQ"); } // Export the TSQ as DER-encoded binary data (matches the output of `-out request.tsq`) $tsqDer = openssl_ts_query_export($tsq); if ($tsqDer === false) { die("Error: Failed to export TSQ"); } // Save the TSQ to file if (file_put_contents('request.tsq', $tsqDer) === false) { die("Error: Could not write request.tsq"); } echo "Successfully generated request.tsq\n"; ?>
Key Details & Command Line Equivalents
Let's break down how this maps to your original command:
-data input_file.xml: We read the file content withfile_get_contents()and pass it toopenssl_ts_query_add_data(), which handles computing the SHA-512 hash automatically.-no_nonce: Setting'nonce' => nullin the parameters disables nonce generation (if you wanted a nonce later, you could pass a random string/int here).-sha512: The'digest_alg' => 'sha512'parameter specifies the hash algorithm to use.-out request.tsq:openssl_ts_query_export()outputs the raw DER-encoded TSQ data, which we write to a file withfile_put_contents().
Prerequisites
- Ensure the PHP OpenSSL extension is enabled (check via
phpinfo()orfunction_exists('openssl_ts_query_new')). - This works on PHP 5.3.0 and later, but PHP 7.0+ is recommended for better stability and security.
内容的提问来源于stack exchange,提问作者josemmo
相关产品推荐
相关产品推荐

