org.bouncycastle.tsp.TimeStampToken Java Examples

The following examples show how to use org.bouncycastle.tsp.TimeStampToken. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TimeStampValidatorImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public void validateTimeStampToken(byte[] bs, TimeStampToken tsToken) throws InvalidTimeStampException, TechnicalConnectorException {
   byte[] calculatedDigest = ConnectorCryptoUtils.calculateDigest(tsToken.getTimeStampInfo().getMessageImprintAlgOID().getId(), bs);
   byte[] tokenDigestValue = tsToken.getTimeStampInfo().getMessageImprintDigest();
   if (!MessageDigest.isEqual(calculatedDigest, tokenDigestValue)) {
      throw new InvalidTimeStampException("Response for different message imprint digest.");
   } else {
      Attribute scV1 = tsToken.getSignedAttributes().get(PKCSObjectIdentifiers.id_aa_signingCertificate);
      Attribute scV2 = tsToken.getSignedAttributes().get(PKCSObjectIdentifiers.id_aa_signingCertificateV2);
      if (scV1 == null && scV2 == null) {
         throw new InvalidTimeStampException("no signing certificate attribute present.", (Exception)null);
      } else if (scV1 != null && scV2 != null) {
         throw new InvalidTimeStampException("Conflicting signing certificate attributes present.");
      } else {
         this.validateTimeStampToken(tsToken);
      }
   }
}
 
Example #2
Source File: TimeStampValidatorImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public void validateTimeStampToken(byte[] bs, TimeStampToken tsToken) throws InvalidTimeStampException, TechnicalConnectorException {
   byte[] calculatedDigest = ConnectorCryptoUtils.calculateDigest(tsToken.getTimeStampInfo().getMessageImprintAlgOID().getId(), bs);
   byte[] tokenDigestValue = tsToken.getTimeStampInfo().getMessageImprintDigest();
   if (!MessageDigest.isEqual(calculatedDigest, tokenDigestValue)) {
      throw new InvalidTimeStampException("Response for different message imprint digest.");
   } else {
      Attribute scV1 = tsToken.getSignedAttributes().get(PKCSObjectIdentifiers.id_aa_signingCertificate);
      Attribute scV2 = tsToken.getSignedAttributes().get(PKCSObjectIdentifiers.id_aa_signingCertificateV2);
      if (scV1 == null && scV2 == null) {
         throw new InvalidTimeStampException("no signing certificate attribute present.", (Exception)null);
      } else if (scV1 != null && scV2 != null) {
         throw new InvalidTimeStampException("Conflicting signing certificate attributes present.");
      } else {
         this.validateTimeStampToken(tsToken);
      }
   }
}
 
Example #3
Source File: TimestampUtil.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static TimeStampToken getTimeStampToken(byte[] tsToken) throws TechnicalConnectorException {
   byte[] cloneTsToken = ArrayUtils.clone(tsToken);

   try {
      cloneTsToken = ConnectorIOUtils.base64Decode(cloneTsToken, true);
      return new TimeStampToken(new CMSSignedData(cloneTsToken));
   } catch (TSPException var3) {
      LOG.error(var3.getClass().getSimpleName() + ": " + var3.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var3, new Object[]{var3.getMessage()});
   } catch (IOException var4) {
      LOG.error(var4.getClass().getSimpleName() + ": " + var4.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var4, new Object[]{var4.getMessage()});
   } catch (CMSException var5) {
      LOG.error(var5.getClass().getSimpleName() + ": " + var5.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var5, new Object[]{var5.getMessage()});
   }
}
 
Example #4
Source File: XadesTSpecification.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private void verifyTimestampList(SignatureVerificationResult result, Element baseElement, NodeList timestampList, String c14nMethodValue) throws TechnicalConnectorException {
   if (timestampList != null && timestampList.getLength() > 0) {
      for(int j = 0; j < timestampList.getLength(); ++j) {
         try {
            Node timestampNode = timestampList.item(j);
            byte[] digestValue = this.generateTimestampDigest(baseElement, c14nMethodValue);
            TimeStampToken tsToken = TimestampUtil.getTimeStampToken(Base64.decode(timestampNode.getTextContent().getBytes()));
            TimeStampValidatorFactory.Companion.getInstance().validateTimeStampToken(digestValue, tsToken);
            result.getTimestampGenTimes().add(new DateTime(tsToken.getTimeStampInfo().getGenTime()));
            result.getTsTokens().add(tsToken);
         } catch (InvalidTimeStampException var9) {
            LOG.error(var9.getMessage(), var9);
            result.getErrors().add(SignatureVerificationError.XADES_ENCAPSULATED_TIMESTAMP_NOT_VALID);
         }
      }
   } else {
      result.getErrors().add(SignatureVerificationError.XADES_ENCAPSULATED_TIMESTAMP_NOT_FOUND);
   }

}
 
Example #5
Source File: TimeStampTokenProductionComparator.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public int compare(TimeStampToken timeStampTokenOne, TimeStampToken timeStampTokenTwo) {
	
	int result = DSSASN1Utils.getTimeStampTokenGenerationTime(timeStampTokenOne).compareTo(DSSASN1Utils.getTimeStampTokenGenerationTime(timeStampTokenTwo));
	if (result == 0) {			
		
		ASN1Sequence atsHashIndexOne = DSSASN1Utils.getAtsHashIndex(timeStampTokenOne.getUnsignedAttributes());
		ASN1Sequence atsHashIndexTwo = DSSASN1Utils.getAtsHashIndex(timeStampTokenTwo.getUnsignedAttributes());

		if (atsHashIndexOne != null && atsHashIndexTwo != null) {
			
			int hashTableSizeOne = getHashTableSize(atsHashIndexOne);
			int hashTableSizeTwo = getHashTableSize(atsHashIndexTwo);
			
			if (hashTableSizeOne < hashTableSizeTwo) {
				result = -1;
			} else if (hashTableSizeOne > hashTableSizeTwo) {
				result = 1;
			}
		}
	}
	return result;
}
 
Example #6
Source File: XadesTSpecification.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private void verifyTimestampList(SignatureVerificationResult result, Element baseElement, NodeList timestampList, String c14nMethodValue) throws TechnicalConnectorException {
   if (timestampList != null && timestampList.getLength() > 0) {
      for(int j = 0; j < timestampList.getLength(); ++j) {
         try {
            Node timestampNode = timestampList.item(j);
            byte[] digestValue = this.generateTimestampDigest(baseElement, c14nMethodValue);
            TimeStampToken tsToken = TimestampUtil.getTimeStampToken(Base64.decode(timestampNode.getTextContent().getBytes()));
            TimeStampValidatorFactory.getInstance().validateTimeStampToken(digestValue, tsToken);
            result.getTimestampGenTimes().add(new DateTime(tsToken.getTimeStampInfo().getGenTime()));
            result.getTsTokens().add(tsToken);
         } catch (InvalidTimeStampException var9) {
            LOG.error(var9.getMessage(), var9);
            result.getErrors().add(SignatureVerificationError.XADES_ENCAPSULATED_TIMESTAMP_NOT_VALID);
         }
      }
   } else {
      result.getErrors().add(SignatureVerificationError.XADES_ENCAPSULATED_TIMESTAMP_NOT_FOUND);
   }

}
 
Example #7
Source File: TimestampUtil.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static TimeStampToken getTimeStampToken(byte[] tsToken) throws TechnicalConnectorException {
   byte[] cloneTsToken = ArrayUtils.clone(tsToken);

   try {
      cloneTsToken = ConnectorIOUtils.base64Decode(cloneTsToken, true);
      return new TimeStampToken(new CMSSignedData(cloneTsToken));
   } catch (TSPException var3) {
      LOG.error(var3.getClass().getSimpleName() + ": " + var3.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var3, new Object[]{var3.getMessage()});
   } catch (IOException var4) {
      LOG.error(var4.getClass().getSimpleName() + ": " + var4.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var4, new Object[]{var4.getMessage()});
   } catch (CMSException var5) {
      LOG.error(var5.getClass().getSimpleName() + ": " + var5.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var5, new Object[]{var5.getMessage()});
   }
}
 
Example #8
Source File: XadesTSpecification.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private void verifyTimestampList(SignatureVerificationResult result, Element baseElement, NodeList timestampList, String c14nMethodValue) throws TechnicalConnectorException {
   if (timestampList != null && timestampList.getLength() > 0) {
      for(int j = 0; j < timestampList.getLength(); ++j) {
         try {
            Node timestampNode = timestampList.item(j);
            byte[] digestValue = this.generateTimestampDigest(baseElement, c14nMethodValue);
            TimeStampToken tsToken = TimestampUtil.getTimeStampToken(Base64.decode(timestampNode.getTextContent().getBytes()));
            TimeStampValidatorFactory.getInstance().validateTimeStampToken(digestValue, tsToken);
            result.getTimestampGenTimes().add(new DateTime(tsToken.getTimeStampInfo().getGenTime()));
            result.getTsTokens().add(tsToken);
         } catch (InvalidTimeStampException var9) {
            LOG.error(var9.getMessage(), var9);
            result.getErrors().add(SignatureVerificationError.XADES_ENCAPSULATED_TIMESTAMP_NOT_VALID);
         }
      }
   } else {
      result.getErrors().add(SignatureVerificationError.XADES_ENCAPSULATED_TIMESTAMP_NOT_FOUND);
   }

}
 
Example #9
Source File: TimestampUtil.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static TimeStampToken getTimeStampToken(byte[] tsToken) throws TechnicalConnectorException {
   byte[] cloneTsToken = ArrayUtils.clone(tsToken);

   try {
      cloneTsToken = ConnectorIOUtils.base64Decode(cloneTsToken, true);
      return new TimeStampToken(new CMSSignedData(cloneTsToken));
   } catch (TSPException var3) {
      LOG.error(var3.getClass().getSimpleName() + ": " + var3.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var3, new Object[]{var3.getMessage()});
   } catch (IOException var4) {
      LOG.error(var4.getClass().getSimpleName() + ": " + var4.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var4, new Object[]{var4.getMessage()});
   } catch (CMSException var5) {
      LOG.error(var5.getClass().getSimpleName() + ": " + var5.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var5, new Object[]{var5.getMessage()});
   }
}
 
Example #10
Source File: TimeStampValidatorImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public void validateTimeStampToken(byte[] bs, TimeStampToken tsToken) throws InvalidTimeStampException, TechnicalConnectorException {
   byte[] calculatedDigest = ConnectorCryptoUtils.calculateDigest(tsToken.getTimeStampInfo().getMessageImprintAlgOID().getId(), bs);
   byte[] tokenDigestValue = tsToken.getTimeStampInfo().getMessageImprintDigest();
   if (!MessageDigest.isEqual(calculatedDigest, tokenDigestValue)) {
      throw new InvalidTimeStampException("Response for different message imprint digest.");
   } else {
      Attribute scV1 = tsToken.getSignedAttributes().get(PKCSObjectIdentifiers.id_aa_signingCertificate);
      Attribute scV2 = tsToken.getSignedAttributes().get(PKCSObjectIdentifiers.id_aa_signingCertificateV2);
      if (scV1 == null && scV2 == null) {
         throw new InvalidTimeStampException("no signing certificate attribute present.", (Exception)null);
      } else if (scV1 != null && scV2 != null) {
         throw new InvalidTimeStampException("Conflicting signing certificate attributes present.");
      } else {
         this.validateTimeStampToken(tsToken);
      }
   }
}
 
Example #11
Source File: VerifyTimestamp.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/48211757/itext-pdf-timestamp-validation-returns-false-why">
 * iText pdf timestamp validation returns false, why?
 * </a>
 * <br/>
 * <a href="https://drive.google.com/file/d/1skI3NM9cqw2m6eW9jKXaJXKzvCjyQMib/view">
 * testpdf_timestamp.pdf
 * </a>
 * <p>
 * The code the OP used for inspiration was for retrieving information
 * from a signature which may include a signature time stamp. The PDF
 * of the OP, on the other hand, contains a document time stamp. The
 * call `pkcs7.verifyTimestampImprint()` checks the time stamp as a
 * signature time stamp and, therefore, fails.
 * </p>
 */
@Test
public void testDocumentTimestampLikeRadekKantor() throws IOException, GeneralSecurityException {
    try (   InputStream resource = getClass().getResourceAsStream("testpdf_timestamp.pdf") )
    {
        PdfReader reader = new PdfReader(resource);
        AcroFields fields = reader.getAcroFields();
        ArrayList<String> names = fields.getSignatureNames();
        for (String name : names) {
            System.out.println("===== " + name + " =====");
            System.out.println("Signature covers whole document: " + fields.signatureCoversWholeDocument(name));
            System.out.println("Document revision: " + fields.getRevision(name) + " of " + fields.getTotalRevisions());
            PdfPKCS7 pkcs7 = fields.verifySignature(name);
            System.out.println("Integrity check OK? " + pkcs7.verify());
            SimpleDateFormat date_format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS");
            System.out.println("Signed on: " + date_format.format(pkcs7.getSignDate().getTime()));
            if (pkcs7.getTimeStampDate() != null) {
                System.out.println("TimeStamp: " + date_format.format(pkcs7.getTimeStampDate().getTime()));
                TimeStampToken ts = pkcs7.getTimeStampToken();
                System.out.println("TimeStamp service: " + ts.getTimeStampInfo().getTsa());
                // Why pkcs7.verifyTimestampImprint() returns FLASE?
                System.out.println("Timestamp verified? " + pkcs7.verifyTimestampImprint());
            }
        }
    }
}
 
Example #12
Source File: TimestampUtil.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static TimeStampToken getTimeStampToken(byte[] tsToken) throws TechnicalConnectorException {
   byte[] cloneTsToken = ArrayUtils.clone(tsToken);

   try {
      cloneTsToken = ConnectorIOUtils.base64Decode(cloneTsToken, true);
      return new TimeStampToken(new CMSSignedData(cloneTsToken));
   } catch (TSPException var3) {
      LOG.error(var3.getClass().getSimpleName() + ": " + var3.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var3, new Object[]{var3.getMessage()});
   } catch (IOException var4) {
      LOG.error(var4.getClass().getSimpleName() + ": " + var4.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var4, new Object[]{var4.getMessage()});
   } catch (CMSException var5) {
      LOG.error(var5.getClass().getSimpleName() + ": " + var5.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var5, new Object[]{var5.getMessage()});
   }
}
 
Example #13
Source File: XadesTSpecification.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private void verifyTimestampList(SignatureVerificationResult result, Element baseElement, NodeList timestampList, String c14nMethodValue) throws TechnicalConnectorException {
   if (timestampList != null && timestampList.getLength() > 0) {
      for(int j = 0; j < timestampList.getLength(); ++j) {
         try {
            Node timestampNode = timestampList.item(j);
            byte[] digestValue = this.generateTimestampDigest(baseElement, c14nMethodValue);
            TimeStampToken tsToken = TimestampUtil.getTimeStampToken(Base64.decode(timestampNode.getTextContent().getBytes()));
            TimeStampValidatorFactory.getInstance().validateTimeStampToken(digestValue, tsToken);
            result.getTimestampGenTimes().add(new DateTime(tsToken.getTimeStampInfo().getGenTime()));
            result.getTsTokens().add(tsToken);
         } catch (InvalidTimeStampException var9) {
            LOG.error(var9.getMessage(), var9);
            result.getErrors().add(SignatureVerificationError.XADES_ENCAPSULATED_TIMESTAMP_NOT_VALID);
         }
      }
   } else {
      result.getErrors().add(SignatureVerificationError.XADES_ENCAPSULATED_TIMESTAMP_NOT_FOUND);
   }

}
 
Example #14
Source File: CAdESTimestampDataBuilder.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Remove any archive-timestamp-v2/3 attribute added after the
 * timestampToken
 */
private ASN1Sequence filterUnauthenticatedAttributes(ASN1Set unauthenticatedAttributes, TimestampToken timestampToken) {
	ASN1EncodableVector result = new ASN1EncodableVector();
	for (int ii = 0; ii < unauthenticatedAttributes.size(); ii++) {

		final Attribute attribute = Attribute.getInstance(unauthenticatedAttributes.getObjectAt(ii));
		final ASN1ObjectIdentifier attrType = attribute.getAttrType();
		if (id_aa_ets_archiveTimestampV2.equals(attrType) || id_aa_ets_archiveTimestampV3.equals(attrType)) {
			try {

				TimeStampToken token = DSSASN1Utils.getTimeStampToken(attribute);
				if (!token.getTimeStampInfo().getGenTime().before(timestampToken.getGenerationTime())) {
					continue;
				}
			} catch (Exception e) {
				throw new DSSException(e);
			}
		}
		result.add(unauthenticatedAttributes.getObjectAt(ii));
	}
	return new DERSequence(result);
}
 
Example #15
Source File: TimeStampValidatorImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public void validateTimeStampToken(byte[] bs, TimeStampToken tsToken) throws InvalidTimeStampException, TechnicalConnectorException {
   byte[] calculatedDigest = ConnectorCryptoUtils.calculateDigest(tsToken.getTimeStampInfo().getMessageImprintAlgOID().getId(), bs);
   byte[] tokenDigestValue = tsToken.getTimeStampInfo().getMessageImprintDigest();
   if (!MessageDigest.isEqual(calculatedDigest, tokenDigestValue)) {
      throw new InvalidTimeStampException("Response for different message imprint digest.");
   } else {
      Attribute scV1 = tsToken.getSignedAttributes().get(PKCSObjectIdentifiers.id_aa_signingCertificate);
      Attribute scV2 = tsToken.getSignedAttributes().get(PKCSObjectIdentifiers.id_aa_signingCertificateV2);
      if (scV1 == null && scV2 == null) {
         throw new InvalidTimeStampException("no signing certificate attribute present.", (Exception)null);
      } else if (scV1 != null && scV2 != null) {
         throw new InvalidTimeStampException("Conflicting signing certificate attributes present.");
      } else {
         this.validateTimeStampToken(tsToken);
      }
   }
}
 
Example #16
Source File: CAdESTimeStampSigner.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
private Timestamp checkTimeStamp(byte[] timeStamp, byte[] content,  byte[] hash){
	try {
		Security.addProvider(new BouncyCastleProvider());
		ais = new ASN1InputStream(new ByteArrayInputStream(timeStamp));
	    ASN1Sequence seq=(ASN1Sequence)ais.readObject();
        Attribute attributeTimeStamp = new Attribute((ASN1ObjectIdentifier)seq.getObjectAt(0), (ASN1Set)seq.getObjectAt(1));
        byte[] varTimeStamp = attributeTimeStamp.getAttrValues().getObjectAt(0).toASN1Primitive().getEncoded();
        TimeStampOperator timeStampOperator = new TimeStampOperator();
        if (content != null){
        	timeStampOperator.validate(content, varTimeStamp,null);
        }else{
        	timeStampOperator.validate(null, varTimeStamp,hash);
        }			
		TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(varTimeStamp));
		Timestamp timeStampSigner = new Timestamp(timeStampToken);
		return timeStampSigner;
	} catch (CertificateCoreException | IOException | TSPException
			| CMSException e) {
		throw new SignerException(e);
	}

}
 
Example #17
Source File: CAdESTimeStampSigner.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
private Timestamp checkTimeStampPDF(byte[] timeStamp, byte[] content,  byte[] hash){
	try {
		Security.addProvider(new BouncyCastleProvider());
		byte[] varTimeStamp = timeStamp;
		TimeStampOperator timeStampOperator = new TimeStampOperator();
		if (content != null){
			timeStampOperator.validate(content, varTimeStamp,null);
		}else{
			timeStampOperator.validate(null, varTimeStamp,hash);
		}			
		TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(varTimeStamp));
		Timestamp timeStampSigner = new Timestamp(timeStampToken);
		return timeStampSigner;
	} catch (CertificateCoreException | IOException | TSPException
		| CMSException e) {
		throw new SignerException(e);
	}
	
}
 
Example #18
Source File: TimestampUtil.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static TimeStampToken getTimeStampToken(byte[] tsToken) throws TechnicalConnectorException {
   byte[] cloneTsToken = ArrayUtils.clone(tsToken);

   try {
      cloneTsToken = ConnectorIOUtils.base64Decode(cloneTsToken, true);
      return new TimeStampToken(new CMSSignedData(cloneTsToken));
   } catch (TSPException var3) {
      LOG.error(var3.getClass().getSimpleName() + ": " + var3.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var3, new Object[]{var3.getMessage()});
   } catch (IOException var4) {
      LOG.error(var4.getClass().getSimpleName() + ": " + var4.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var4, new Object[]{var4.getMessage()});
   } catch (CMSException var5) {
      LOG.error(var5.getClass().getSimpleName() + ": " + var5.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var5, new Object[]{var5.getMessage()});
   }
}
 
Example #19
Source File: XadesTSpecification.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private void verifyTimestampList(SignatureVerificationResult result, Element baseElement, NodeList timestampList, String c14nMethodValue) throws TechnicalConnectorException {
   if (timestampList != null && timestampList.getLength() > 0) {
      for(int j = 0; j < timestampList.getLength(); ++j) {
         try {
            Node timestampNode = timestampList.item(j);
            byte[] digestValue = this.generateTimestampDigest(baseElement, c14nMethodValue);
            TimeStampToken tsToken = TimestampUtil.getTimeStampToken(Base64.decode(timestampNode.getTextContent().getBytes()));
            TimeStampValidatorFactory.getInstance().validateTimeStampToken(digestValue, tsToken);
            result.getTimestampGenTimes().add(new DateTime(tsToken.getTimeStampInfo().getGenTime()));
            result.getTsTokens().add(tsToken);
         } catch (InvalidTimeStampException var9) {
            LOG.error(var9.getMessage(), var9);
            result.getErrors().add(SignatureVerificationError.XADES_ENCAPSULATED_TIMESTAMP_NOT_VALID);
         }
      }
   } else {
      result.getErrors().add(SignatureVerificationError.XADES_ENCAPSULATED_TIMESTAMP_NOT_FOUND);
   }

}
 
Example #20
Source File: PdfPKCS7.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Verifies a timestamp against a KeyStore.
 * @param ts the timestamp
 * @param keystore the <CODE>KeyStore</CODE>
 * @param provider the provider or <CODE>null</CODE> to use the BouncyCastle provider
 * @return <CODE>true</CODE> is a certificate was found
 * @since	2.1.6
 */    
public static boolean verifyTimestampCertificates(TimeStampToken ts, KeyStore keystore, String provider) {
    if (provider == null)
        provider = "BC";
    try {
        for (Enumeration aliases = keystore.aliases(); aliases.hasMoreElements();) {
            try {
                String alias = (String)aliases.nextElement();
                if (!keystore.isCertificateEntry(alias))
                    continue;
                X509Certificate certStoreX509 = (X509Certificate)keystore.getCertificate(alias);
                SignerInformationVerifier siv = new JcaSimpleSignerInfoVerifierBuilder().setProvider(provider).build(certStoreX509);
                ts.validate(siv);
                return true;
            }
            catch (Exception ex) {
            }
        }
    }
    catch (Exception e) {
    }
    return false;
}
 
Example #21
Source File: TimestampUtil.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public static TimeStampToken getTimestamp(byte[] tsTokenResponse) throws TechnicalConnectorException {
   try {
      LOG.debug("Trying to generate unwrapped TimeStampToken");
      return getTimeStampToken(tsTokenResponse);
   } catch (TechnicalConnectorException var2) {
      LOG.debug("Trying to generate wrapped TimeStampToken");
      return getTimestampResponse(tsTokenResponse).getTimeStampToken();
   }
}
 
Example #22
Source File: TimeStampValidatorImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public void validateTimeStampToken(TimeStampToken tsToken) throws InvalidTimeStampException, TechnicalConnectorException {
   Validate.notNull(this.keyStore, "keyStore is not correctly initialised.");
   Validate.notNull(this.aliases, "aliases is not correctly initialised.");
   Validate.notNull(tsToken, "Parameter tsToken value is not nullable.");
   if (tsToken.getTimeStampInfo() != null) {
      LOG.debug("Validating TimeStampToken with SerialNumber [" + tsToken.getTimeStampInfo().getSerialNumber() + "]");
   }

   boolean signatureValid = false;
   Exception lastException = null;
   Iterator i$ = this.aliases.iterator();

   while(i$.hasNext()) {
      String alias = (String)i$.next();

      try {
         X509Certificate ttsaCert = (X509Certificate)this.keyStore.getCertificate(alias);
         LOG.debug("Trying to validate timestamp against certificate with alias [" + alias + "] : [" + ttsaCert.getSubjectX500Principal().getName("RFC1779") + "]");
         X509CertificateHolder tokenSigner = new X509CertificateHolder(ttsaCert.getEncoded());
         SignerInformationVerifier verifier = (new BcRSASignerInfoVerifierBuilder(new DefaultCMSSignatureAlgorithmNameGenerator(), new DefaultSignatureAlgorithmIdentifierFinder(), new DefaultDigestAlgorithmIdentifierFinder(), new BcDigestCalculatorProvider())).build(tokenSigner);
         tsToken.validate(verifier);
         signatureValid = true;
         break;
      } catch (Exception var9) {
         lastException = var9;
         LOG.debug("TimeStampToken not valid with certificate-alias [" + alias + "]: " + var9.getMessage());
      }
   }

   if (!signatureValid) {
      throw new InvalidTimeStampException("timestamp is not valid ", lastException);
   } else {
      LOG.debug("timestampToken is valid");
   }
}
 
Example #23
Source File: CAdESLevelBaselineLTA.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private TimeStampToken getLastArchiveTimestamp(AttributeTable unsignedAttributes) {
	TimeStampToken lastTimeStampToken = null;
	TimeStampTokenProductionComparator comparator = new TimeStampTokenProductionComparator();
	for (TimeStampToken timeStampToken : DSSASN1Utils.findArchiveTimeStampTokens(unsignedAttributes)) {
		if (lastTimeStampToken == null || comparator.after(timeStampToken, lastTimeStampToken)) {
			lastTimeStampToken = timeStampToken; 
		}
	}
	return lastTimeStampToken;
}
 
Example #24
Source File: CAdESTimeStampSigner.java    From signer with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public List<Timestamp> checkTimeStampOnSignature(byte[] signature) {
	try {
		Security.addProvider(new BouncyCastleProvider());
		List<Timestamp> listOfTimeStamp = new ArrayList<Timestamp>();
		CMSSignedData cmsSignedData = new CMSSignedData(signature);
		SignerInformationStore signers = cmsSignedData.getSignerInfos();
		Iterator<?> it = signers.getSigners().iterator();
		while (it.hasNext()) {
			SignerInformation signer = (SignerInformation) it.next();
			AttributeTable unsignedAttributes = signer
					.getUnsignedAttributes();
			Attribute attributeTimeStamp = unsignedAttributes
					.get(new ASN1ObjectIdentifier(
							PKCSObjectIdentifiers.id_aa_signatureTimeStampToken
									.getId()));
			if (attributeTimeStamp != null) {
				TimeStampOperator timeStampOperator = new TimeStampOperator();
				byte[] varTimeStamp = attributeTimeStamp.getAttrValues()
						.getObjectAt(0).toASN1Primitive().getEncoded();
				TimeStampToken timeStampToken = new TimeStampToken(
						new CMSSignedData(varTimeStamp));
				Timestamp timeStampSigner = new Timestamp(timeStampToken);
				timeStampOperator.validate(signer.getSignature(),
						varTimeStamp, null);
				listOfTimeStamp.add(timeStampSigner);
			}
		}
		return listOfTimeStamp;
	} catch (CertificateCoreException | IOException | TSPException
			| CMSException e) {
		throw new SignerException(e);
	}		
}
 
Example #25
Source File: CAdESUnsignedAttributes.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private List<CAdESAttribute> sortTimestamps(List<CAdESAttribute> attributes) {
	// TODO: improve ?
	TimeStampTokenProductionComparator comparator = new TimeStampTokenProductionComparator();
	
	for (int ii = 0; ii < attributes.size() - 1; ii++) {
		for (int jj = 0; jj < attributes.size() - ii - 1; jj++) {
			CAdESAttribute cadesAttribute = attributes.get(jj);
			// if the first element is a timestamp
			if (timestampOids.contains(cadesAttribute.getASN1Oid())) {
				CAdESAttribute nextCAdESAttribute = attributes.get(jj + 1);
				// swap if the next element is not a timestamp
				if (!timestampOids.contains(nextCAdESAttribute.getASN1Oid())) {
					Collections.swap(attributes, jj, jj + 1);
				} else {

					TimeStampToken current = cadesAttribute.toTimeStampToken();
					TimeStampToken next = nextCAdESAttribute.toTimeStampToken();
					// swap if the current element was generated after the following timestamp attribute
					if (current != null && next != null && (comparator.compare(current, next) > 0)) {
						Collections.swap(attributes, jj, jj + 1);
					}

				}
			}
		}
	}
	return attributes;
}
 
Example #26
Source File: CAdESAttribute.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Returns a TimeStampToken if possible
 * 
 * @return a {@link TimeStampToken} or null
 */
public TimeStampToken toTimeStampToken() {
	try {
		return DSSASN1Utils.getTimeStampToken(attribute);
	} catch (Exception e) {
		LOG.warn("Unable to build a timestamp token from the attribute [{}] : {}", this, e.getMessage());
		return null;
	}
}
 
Example #27
Source File: CAdESChecker.java    From signer with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 *  validade a timestampo on signature
 * @param attributeTimeStamp
 * @param varSignature
 * @return
 */
private Timestamp validateTimestamp(Attribute attributeTimeStamp, byte[] varSignature){
	try {
		TimeStampOperator timeStampOperator = new TimeStampOperator();
		byte [] varTimeStamp = attributeTimeStamp.getAttrValues().getObjectAt(0).toASN1Primitive().getEncoded();
		TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(varTimeStamp));
		Timestamp timeStampSigner = new Timestamp(timeStampToken);
		timeStampOperator.validate(varSignature,varTimeStamp , null);
		return timeStampSigner;
	} catch (CertificateCoreException | IOException | TSPException | CMSException e) {
		throw new SignerException(e);
	}		
}
 
Example #28
Source File: CAdESTimestampSource.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected TimestampToken makeTimestampToken(CAdESAttribute signatureAttribute, TimestampType timestampType,
		List<TimestampedReference> references) {
	TimeStampToken timestamp = signatureAttribute.toTimeStampToken();
	if (timestamp == null) {
		return null;
	}
	return new TimestampToken(timestamp, timestampType, references, TimestampLocation.CAdES);
}
 
Example #29
Source File: SignatureVerificationResult.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private void writeObject(ObjectOutputStream out) throws IOException {
   this.serTsTokens = new ArrayList();
   Iterator i$ = this.tsTokens.iterator();

   while(i$.hasNext()) {
      TimeStampToken tsToken = (TimeStampToken)i$.next();
      this.serTsTokens.add(ArrayUtils.toObject(tsToken.getEncoded()));
   }

   out.defaultWriteObject();
   this.serTsTokens = null;
}
 
Example #30
Source File: TimestampUtil.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public static TimeStampToken getTimestamp(byte[] tsTokenResponse) throws TechnicalConnectorException {
   try {
      LOG.debug("Trying to generate unwrapped TimeStampToken");
      return getTimeStampToken(tsTokenResponse);
   } catch (TechnicalConnectorException var2) {
      LOG.debug("Trying to generate wrapped TimeStampToken");
      return getTimestampResponse(tsTokenResponse).getTimeStampToken();
   }
}