Exemplo n.º 1
0
  /**
   * method for JSP to create valid TimeStampRequest
   *
   * @param file
   * @param tsr
   * @return
   */
  public TimeStampRequest createCorrespondingTSQ(byte[] file, TimeStampResponse tsr) {
    // get hash algorithm
    ASN1ObjectIdentifier algID =
        tsr.getTimeStampToken().getTimeStampInfo().getMessageImprintAlgOID();
    GeneralDigest digestAlgorithm = getDigestAlg(algID);

    logger.info(
        "The timestamp's algorithm was recognized as {}.", digestAlgorithm.getAlgorithmName());

    // create new hashed request
    byte[] digest = calculateMessageDigest(file, digestAlgorithm);
    TimeStampRequest tsq = getTSRequest(digest, algID);

    return tsq;
  }
Exemplo n.º 2
0
  /**
   * Main method for validating files with stamps. It serves as an example of whole process in one
   * go.
   *
   * @param originalFile
   * @param timeStamp
   * @throws IOException
   * @throws TSPException
   * @throws CertificateException
   * @throws CertificateEncodingException
   * @throws OperatorCreationException
   */
  public void verify(InputStream originalFile, InputStream timeStamp)
      throws IOException, TSPException, CertificateException, CertificateEncodingException,
          OperatorCreationException {
    logger.entry();

    // open files
    byte[] file = getBytesFromInputStream(originalFile);
    TimeStampResponse tsr = parseTSR(timeStamp);

    logger.info("The timestamp was sucessfully opened.");
    logResponse(tsr);

    // get hash algorithm
    ASN1ObjectIdentifier algID =
        tsr.getTimeStampToken().getTimeStampInfo().getMessageImprintAlgOID();
    GeneralDigest digestAlgorithm = getDigestAlg(algID);

    logger.info(
        "The timestamp's algorithm was recognized as {}.", digestAlgorithm.getAlgorithmName());

    // create new hashed request
    byte[] digest = calculateMessageDigest(file, digestAlgorithm);
    TimeStampRequest tsq = getTSRequest(digest, algID);

    logger.info(
        "The timestamp fits the file (the file was not changed), now verifying certificates..");

    InputStream is = null;

    if (is == null) {
      throw new UnsupportedOperationException(
          "Timestamp fits the file (the file was not changed), certificate not implemented yet.");
    }

    // <editor-fold defaultstate="collapsed" desc="varianta 1 - ze souboru">
    CertificateFactory factory;
    X509Certificate cert;
    try {
      factory = CertificateFactory.getInstance("X.509");
      cert = (X509Certificate) factory.generateCertificate(null); // TODO: get inputstream
    } catch (CertificateException e) {
      logger.catching(e);
      throw e;
    }

    // RSA Signature processing with BC
    X509CertificateHolder holder;
    SignerInformationVerifier siv;
    try {
      holder = new X509CertificateHolder(cert.getEncoded());
      siv =
          new BcRSASignerInfoVerifierBuilder(
                  new DefaultCMSSignatureAlgorithmNameGenerator(),
                      new DefaultSignatureAlgorithmIdentifierFinder(),
                  new DefaultDigestAlgorithmIdentifierFinder(), new BcDigestCalculatorProvider())
              .build(holder);
    } catch (CertificateEncodingException | OperatorCreationException e) {
      logger.catching(e);
      throw e;
    }

    // Signature processing with JCA and other provider
    // X509CertificateHolder holderJca = new JcaX509CertificateHolder(cert);
    // SignerInformationVerifier sivJca = new
    // JcaSimpleSignerInfoVerifierBuilder().setProvider("anotherprovider").build(holderJca);

    try {
      tsr.getTimeStampToken().validate(siv);
    } catch (TSPException e) {
      logger.catching(e);
      throw e;
    }
    /* konec varianty 1 */
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="varianta 2 - z razitka">
    /*/ get certificates
            CollectionStore certs = (CollectionStore) tst.getCertificates();
            SignerInformationStore signers = tst.toCMSSignedData().getSignerInfos();

            int certsCount = 0;
            for (Iterator it = certs.iterator(); it.hasNext();) {
                certsCount++; // stupid hack to get actual number of certificates
            }
            if (certsCount < 1) {
                logger.error("No certificate found.");
                return;
            }

            for (SignerInformation signer : signers) {
                Collection<X509Certificate> col = certs.getMatches(signer.getSID());
                X509Certificate[] signerCerts = new X509Certificate[0];
                col.toArray(signerCerts);

                if (signerCerts.length != 1) {
                    logger.error("Expected only one certificate per signer.");
                    return;
                }

                try {
                    signerCerts[0].checkValidity();
                } catch (CertificateExpiredException | CertificateNotYetValidException ex) {
                    java.util.logging.Logger.getLogger(TSAConnector.class.getName()).log(Level.SEVERE, null, ex);
                }

    //            signer.verify(signerCerts[0]); // should verify that the timestamp is signed correctly
            }
            /* konec varianty 2 */
    // </editor-fold>

    logger.info("All certificates successfully verified, the timestamp is trusted.");
    logger.exit();
  }