Erstellung eines Timestamp Requests in Java

16. Juli 2015

In Java mithilfe der BouncyCastle Bibliotheken geschrieben, erstellt folgendes Programm einen Timestamp Request im File request.tsq für das File doc.txt:

package eu.globaltrust.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.tsp.TimeStampRequest;
import org.bouncycastle.tsp.TimeStampRequestGenerator;

public final class TSQCreator {

    private TSQCreator() {
    }

    public static void main(final String[] args) {
        // Die OID des Hash Algorithmus muss bekannt sein
        String sha1Oid = “1.3.14.3.2.26”;
        // Wir wollen ein Timestamp Request für doc.txt erstellen
        File doc = new File(“doc.txt”);
        byte[] bytes = new byte[(int) doc.length()];
        try {
            new FileInputStream(doc).read(bytes);
        } catch (Exception e) {
            System.err.println(“Error reading from file”);
            return;
        }
        byte[] digest;
        try {
            digest = MessageDigest.getInstance(“SHA1”).digest(bytes);
        } catch (NoSuchAlgorithmException e) {
            System.out.println(“SHA-1 algorithm not available.”);
            return;
        }
        TimeStampRequestGenerator gen = new TimeStampRequestGenerator();
        try {
            TimeStampRequest tsq = gen.generate(new ASN1ObjectIdentifier(sha1Oid), digest, new BigInteger(64,
                    SecureRandom.getInstance(“SHA1PRNG”)));
            try {
                new FileOutputStream(“request.tsq”).write(tsq.getEncoded());
            } catch (Exception e) {
                System.out.println(“Error writing request.”);
                return;
            }
        } catch (NoSuchAlgorithmException e) {
            System.out.println(“No such algorithm: ” + e.getMessage());
        }
    }
}