org.bouncycastle.cms.SignerInformationVerifier Java Examples
The following examples show how to use
org.bouncycastle.cms.SignerInformationVerifier.
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: TimestampToken.java From dss with GNU Lesser General Public License v2.1 | 6 votes |
private boolean isValidCMSSignedData(SignerInformationVerifier signerInformationVerifier) { try { // Only validate the cryptographic validity SignerInformationStore signerInfos = timeStamp.toCMSSignedData().getSignerInfos(); SignerInformation signerInformation = signerInfos.get(timeStamp.getSID()); return signerInformation.verify(signerInformationVerifier); } catch (CMSException e) { if (LOG.isDebugEnabled()) { LOG.debug("Unable to validate the related CMSSignedData : ", e); } else { LOG.warn("Unable to validate the related CMSSignedData : {}", e.getMessage()); } signatureInvalidityReason = e.getClass().getSimpleName() + " : " + e.getMessage(); return false; } }
Example #2
Source File: ValidateSignature.java From testarea-pdfbox2 with Apache License 2.0 | 6 votes |
/** * <a href="http://stackoverflow.com/questions/41116833/pdf-signature-validation"> * PDF Signature Validation * </a> * <br/> * <a href="https://drive.google.com/file/d/0BzEmZ9pRWLhPOUJSYUdlRjg2eEU/view?usp=sharing"> * SignatureVlidationTest.pdf * </a> * <p> * The code completely ignores the <b>SubFilter</b> of the signature. * It is appropriate for signatures with <b>SubFilter</b> values * <b>adbe.pkcs7.detached</b> and <b>ETSI.CAdES.detached</b> * but will fail for signatures with <b>SubFilter</b> values * <b>adbe.pkcs7.sha1</b> and <b>adbe.x509.rsa.sha1</b>. * </p> * <p> * The example document has been signed with a signatures with * <b>SubFilter</b> value <b>adbe.pkcs7.sha1</b>. * </p> */ @Test public void testValidateSignatureVlidationTest() throws Exception { System.out.println("\nValidate signature in SignatureVlidationTest.pdf; original code."); byte[] pdfByte; PDDocument pdfDoc = null; SignerInformationVerifier verifier = null; try { pdfByte = IOUtils.toByteArray(this.getClass().getResourceAsStream("SignatureVlidationTest.pdf")); pdfDoc = Loader.loadPDF(new ByteArrayInputStream(pdfByte)); PDSignature signature = pdfDoc.getSignatureDictionaries().get(0); byte[] signatureAsBytes = signature.getContents(pdfByte); byte[] signedContentAsBytes = signature.getSignedContent(pdfByte); CMSSignedData cms = new CMSSignedData(new CMSProcessableByteArray(signedContentAsBytes), signatureAsBytes); SignerInformation signerInfo = (SignerInformation) cms.getSignerInfos().getSigners().iterator().next(); X509CertificateHolder cert = (X509CertificateHolder) cms.getCertificates().getMatches(signerInfo.getSID()) .iterator().next(); verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider(new BouncyCastleProvider()).build(cert); // result if false boolean verifyRt = signerInfo.verify(verifier); System.out.println("Verify result: " + verifyRt); } finally { if (pdfDoc != null) { pdfDoc.close(); } } }
Example #3
Source File: PdfPKCS7.java From itext2 with GNU Lesser General Public License v3.0 | 6 votes |
/** * 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 #4
Source File: TimestampToken.java From dss with GNU Lesser General Public License v2.1 | 5 votes |
private SignerInformationVerifier getSignerInformationVerifier(final CertificateToken candidate) { try { final JcaSimpleSignerInfoVerifierBuilder verifier = new JcaSimpleSignerInfoVerifierBuilder(); verifier.setProvider(DSSSecurityProvider.getSecurityProviderName()); return verifier.build(candidate.getCertificate()); } catch (OperatorException e) { throw new DSSException("Unable to build an instance of SignerInformationVerifier", e); } }
Example #5
Source File: TimeStampValidatorImpl.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
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."); TimeStampTokenInfo timeStampInfo = tsToken.getTimeStampInfo(); if (timeStampInfo != null) { LOG.debug("Validating TimeStampToken with SerialNumber [" + timeStampInfo.getSerialNumber() + "]"); if (timeStampInfo.getTsa() != null) { X500Name name = (X500Name)timeStampInfo.getTsa().getName(); LOG.debug("Validating Timestamp against TrustStore Looking for [" + name + "]."); } } 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 var10) { lastException = var10; LOG.debug("TimeStampToken not valid with certificate-alias [" + alias + "]: " + var10.getMessage()); } } if (!signatureValid) { throw new InvalidTimeStampException("timestamp is not valid ", lastException); } else { LOG.debug("timestampToken is valid"); } }
Example #6
Source File: TimestampToken.java From dss with GNU Lesser General Public License v2.1 | 5 votes |
private boolean isValidTimestamp(SignerInformationVerifier signerInformationVerifier) { try { // Validate the timestamp, the signing certificate,... timeStamp.validate(signerInformationVerifier); return true; } catch (TSPException e) { if (LOG.isDebugEnabled()) { LOG.debug("Unable to validate timestamp token : ", e); } else { LOG.warn("Unable to validate timestamp token : {}", e.getMessage()); } signatureInvalidityReason = e.getClass().getSimpleName() + " : " + e.getMessage(); return false; } }
Example #7
Source File: TimestampToken.java From dss with GNU Lesser General Public License v2.1 | 5 votes |
@Override protected SignatureValidity checkIsSignedBy(final CertificateToken candidate) { final X509CertificateHolder x509CertificateHolder = DSSASN1Utils.getX509CertificateHolder(candidate); if (timeStamp.getSID().match(x509CertificateHolder)) { SignerInformationVerifier signerInformationVerifier = getSignerInformationVerifier(candidate); // Try firstly to validate as a Timestamp and if that fails try to validate the // timestamp as a CMSSignedData if (isValidTimestamp(signerInformationVerifier) || isValidCMSSignedData(signerInformationVerifier)) { signatureValidity = SignatureValidity.VALID; this.tsaX500Principal = candidate.getSubject().getPrincipal(); SignerInformation signerInformation = timeStamp.toCMSSignedData().getSignerInfos().get(timeStamp.getSID()); if (SignatureAlgorithm.RSA_SSA_PSS_SHA1_MGF1.getOid().equals(signerInformation.getEncryptionAlgOID())) { signatureAlgorithm = SignatureAlgorithm.forOidAndParams(signerInformation.getEncryptionAlgOID(), signerInformation.getEncryptionAlgParams()); } else { EncryptionAlgorithm encryptionAlgorithm = EncryptionAlgorithm.forName(candidate.getPublicKey().getAlgorithm()); final AlgorithmIdentifier hashAlgorithm = signerInformation.getDigestAlgorithmID(); final DigestAlgorithm digestAlgorithm = DigestAlgorithm.forOID(hashAlgorithm.getAlgorithm().getId()); signatureAlgorithm = SignatureAlgorithm.getAlgorithm(encryptionAlgorithm, digestAlgorithm); } } else { signatureValidity = SignatureValidity.INVALID; } return signatureValidity; } return SignatureValidity.INVALID; }
Example #8
Source File: ValidateSignature.java From testarea-pdfbox2 with Apache License 2.0 | 5 votes |
/** * <a href="http://stackoverflow.com/questions/41116833/pdf-signature-validation"> * PDF Signature Validation * </a> * <br/> * <a href="https://drive.google.com/file/d/0BzEmZ9pRWLhPOUJSYUdlRjg2eEU/view?usp=sharing"> * SignatureVlidationTest.pdf * </a> * <p> * This code also ignores the <b>SubFilter</b> of the signature, * it is appropriate for signatures with <b>SubFilter</b> value * <b>adbe.pkcs7.sha1</b> which the example document has been * signed with. * </p> */ @Test public void testValidateSignatureVlidationTestAdbePkcs7Sha1() throws Exception { System.out.println("\nValidate signature in SignatureVlidationTest.pdf; special adbe.pkcs7.sha1 code."); byte[] pdfByte; PDDocument pdfDoc = null; SignerInformationVerifier verifier = null; try { pdfByte = IOUtils.toByteArray(this.getClass().getResourceAsStream("SignatureVlidationTest.pdf")); pdfDoc = Loader.loadPDF(new ByteArrayInputStream(pdfByte)); PDSignature signature = pdfDoc.getSignatureDictionaries().get(0); byte[] signatureAsBytes = signature.getContents(pdfByte); CMSSignedData cms = new CMSSignedData(new ByteArrayInputStream(signatureAsBytes)); SignerInformation signerInfo = (SignerInformation) cms.getSignerInfos().getSigners().iterator().next(); X509CertificateHolder cert = (X509CertificateHolder) cms.getCertificates().getMatches(signerInfo.getSID()) .iterator().next(); verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider(new BouncyCastleProvider()).build(cert); boolean verifyRt = signerInfo.verify(verifier); System.out.println("Verify result: " + verifyRt); byte[] signedContentAsBytes = signature.getSignedContent(pdfByte); MessageDigest md = MessageDigest.getInstance("SHA1"); byte[] calculatedDigest = md.digest(signedContentAsBytes); byte[] signedDigest = (byte[]) cms.getSignedContent().getContent(); System.out.println("Document digest equals: " + Arrays.equals(calculatedDigest, signedDigest)); } finally { if (pdfDoc != null) { pdfDoc.close(); } } }
Example #9
Source File: TimeStampValidatorImpl.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
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 #10
Source File: TimeStampValidatorImpl.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
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 #11
Source File: TimeStampValidatorImpl.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
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."); TimeStampTokenInfo timeStampInfo = tsToken.getTimeStampInfo(); if (timeStampInfo != null) { LOG.debug("Validating TimeStampToken with SerialNumber [" + timeStampInfo.getSerialNumber() + "]"); if (timeStampInfo.getTsa() != null) { X500Name name = (X500Name)timeStampInfo.getTsa().getName(); LOG.debug("Validating Timestamp against TrustStore Looking for [" + name + "]."); } } 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 var10) { lastException = var10; LOG.debug("TimeStampToken not valid with certificate-alias [" + alias + "]: " + var10.getMessage()); } } if (!signatureValid) { throw new InvalidTimeStampException("timestamp is not valid ", lastException); } else { LOG.debug("timestampToken is valid"); } }
Example #12
Source File: RsaSsaPss.java From testarea-itext5 with GNU Affero General Public License v3.0 | 4 votes |
/** * For some tests I needed SHA256withRSAandMGF1 CMS signatures. */ @Test public void testCreateSimpleSignatureContainer() throws CMSException, GeneralSecurityException, OperatorCreationException, IOException { byte[] message = "SHA256withRSAandMGF1".getBytes(); CMSTypedData msg = new CMSProcessableByteArray(message); List<X509Certificate> certList = new ArrayList<X509Certificate>(); certList.add(origCert); certList.add(signCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA256withRSAandMGF1").setProvider("BC").build(signKP.getPrivate()); gen.addSignerInfoGenerator( new JcaSignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()) .build(sha1Signer, signCert)); gen.addCertificates(certs); CMSSignedData sigData = gen.generate(msg, false); Files.write(new File(RESULT_FOLDER, "simpleMessageSHA256withRSAandMGF1.bin").toPath(), message); Files.write(new File(RESULT_FOLDER, "simpleMessageSHA256withRSAandMGF1.p7s").toPath(), sigData.getEncoded()); boolean verifies = sigData.verifySignatures(new SignerInformationVerifierProvider() { @Override public SignerInformationVerifier get(SignerId sid) throws OperatorCreationException { if (sid.getSerialNumber().equals(origCert.getSerialNumber())) { System.out.println("SignerInformationVerifier requested for OrigCert"); return new JcaSignerInfoVerifierBuilder(new BcDigestCalculatorProvider()).build(origCert); } if (sid.getSerialNumber().equals(signCert.getSerialNumber())) { System.out.println("SignerInformationVerifier requested for SignCert"); return new JcaSignerInfoVerifierBuilder(new BcDigestCalculatorProvider()).build(signCert); } System.out.println("SignerInformationVerifier requested for unknown " + sid); return null; } }); System.out.println("Verifies? " + verifies); }
Example #13
Source File: PDFVerify.java From signer with GNU Lesser General Public License v3.0 | 4 votes |
public void testValidateSignatureVlidationTestAdbePkcs7Sha1() throws Exception { String filePath = "caminho arquivo"; byte[] pdfByte; PDDocument pdfDoc = null; SignerInformationVerifier verifier = null; try { //pdfByte = IOUtils.toByteArray(this.getClass().getResourceAsStream("Teste_AI_Assinado_Assinador_Livre.pdf")); pdfDoc = PDDocument.load(new File(filePath)); PDSignature signature = pdfDoc.getSignatureDictionaries().get(0); byte[] signedContentAsBytes = signature.getSignedContent(new FileInputStream(filePath)); byte[] signatureAsBytes = signature.getContents(new FileInputStream(filePath)); PAdESChecker checker = new PAdESChecker(); checker.checkDetachedSignature(signedContentAsBytes, signatureAsBytes); CMSSignedData cms = new CMSSignedData(new ByteArrayInputStream(signatureAsBytes)); SignerInformation signerInfo = (SignerInformation) cms.getSignerInfos().getSigners().iterator().next(); @SuppressWarnings("unchecked") X509CertificateHolder cert = (X509CertificateHolder) cms.getCertificates().getMatches(signerInfo.getSID()) .iterator().next(); verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider(new BouncyCastleProvider()).build(cert); boolean verifyRt = signerInfo.verify(verifier); System.out.println("Verify result: " + verifyRt); MessageDigest md = MessageDigest.getInstance("SHA1"); byte[] calculatedDigest = md.digest(signedContentAsBytes); byte[] signedDigest = (byte[]) cms.getSignedContent().getContent(); System.out.println("Document digest equals: " + Arrays.equals(calculatedDigest, signedDigest)); } finally { if (pdfDoc != null) { pdfDoc.close(); } } }
Example #14
Source File: AbstractIntegrationModule.java From freehealth-connector with GNU Affero General Public License v3.0 | 4 votes |
private boolean validateTimeStampToken(TimeStampToken tsToken) throws Exception { boolean result = false; KeyStore keyStore = getEncryptionUtils().getTSAKeyStore(); List<String> aliases = getEncryptionUtils().getTsaStoreAliases(); if (aliases == null || keyStore == null) { throw new IllegalStateException("keystore or aliases not initialised yet : aliases : [" + aliases + "] and keystore : [" + keyStore + "]"); } TimeStampTokenInfo tsi = tsToken.getTimeStampInfo(); LOG.info("GenTime:" + tsi.getGenTime()); LOG.info("ImprintAlgOID:" + tsi.getMessageImprintAlgOID()); LOG.info("Policy:" + tsi.getPolicy()); //LOG.info("Accuracy:" + tsi.getAccuracy().getSeconds()); LOG.info("HashAlgorithm:" + tsi.getHashAlgorithm().getAlgorithm().getId()); boolean signatureValid = false; Exception lastException = null; for (String alias : aliases) { try { X509Certificate ttsaCert = (X509Certificate) keyStore.getCertificate(alias); String t = ttsaCert.getSubjectX500Principal().getName(X500Principal.RFC1779); LOG.debug("Trying to validate timestamp against certificate with alias [" + alias + "] : [" + t + "]"); 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 e) { lastException = e; //throw new Exception("timestamp not valid with certificate-alias '" + alias + "': " + e.getMessage()); } } if (signatureValid) { result = true; LOG.debug("timestampToken is valid"); } else { result = false; throw new Exception("timestamp is not valid ", lastException); } return result; }
Example #15
Source File: AbstractIntegrationModule.java From freehealth-connector with GNU Affero General Public License v3.0 | 4 votes |
private boolean validateTimeStampToken(TimeStampToken tsToken) throws Exception { boolean result = false; KeyStore keyStore = this.getEncryptionUtils().getTSAKeyStore(); List<String> aliases = this.getEncryptionUtils().getTsaStoreAliases(); if (aliases != null && keyStore != null) { TimeStampTokenInfo tsi = tsToken.getTimeStampInfo(); LOG.info("GenTime:" + tsi.getGenTime()); LOG.info("ImprintAlgOID:" + tsi.getMessageImprintAlgOID()); LOG.info("Policy:" + tsi.getPolicy()); LOG.info("HashAlgorithm:" + tsi.getHashAlgorithm().getAlgorithm().getId()); boolean signatureValid = false; Exception lastException = null; Iterator var9 = aliases.iterator(); while(var9.hasNext()) { String alias = (String)var9.next(); try { X509Certificate ttsaCert = (X509Certificate)keyStore.getCertificate(alias); String t = ttsaCert.getSubjectX500Principal().getName("RFC1779"); LOG.debug("Trying to validate timestamp against certificate with alias [" + alias + "] : [" + t + "]"); 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 var14) { lastException = var14; } } if (signatureValid) { result = true; LOG.debug("timestampToken is valid"); return result; } else { result = false; throw new Exception("timestamp is not valid ", lastException); } } else { throw new IllegalStateException("keystore or aliases not initialised yet : aliases : [" + aliases + "] and keystore : [" + keyStore + "]"); } }
Example #16
Source File: AbstractIntegrationModule.java From freehealth-connector with GNU Affero General Public License v3.0 | 4 votes |
private boolean validateTimeStampToken(TimeStampToken tsToken) throws Exception { boolean result = false; KeyStore keyStore = getEncryptionUtils().getTSAKeyStore(); List<String> aliases = getEncryptionUtils().getTsaStoreAliases(); if (aliases == null || keyStore == null) { throw new IllegalStateException("keystore or aliases not initialised yet : aliases : [" + aliases + "] and keystore : [" + keyStore + "]"); } TimeStampTokenInfo tsi = tsToken.getTimeStampInfo(); LOG.info("GenTime:" + tsi.getGenTime()); LOG.info("ImprintAlgOID:" + tsi.getMessageImprintAlgOID()); LOG.info("Policy:" + tsi.getPolicy()); //LOG.info("Accuracy:" + tsi.getAccuracy().getSeconds()); LOG.info("HashAlgorithm:" + tsi.getHashAlgorithm().getAlgorithm().getId()); boolean signatureValid = false; Exception lastException = null; for (String alias : aliases) { try { X509Certificate ttsaCert = (X509Certificate) keyStore.getCertificate(alias); String t = ttsaCert.getSubjectX500Principal().getName(X500Principal.RFC1779); LOG.debug("Trying to validate timestamp against certificate with alias [" + alias + "] : [" + t + "]"); 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 e) { lastException = e; //throw new Exception("timestamp not valid with certificate-alias '" + alias + "': " + e.getMessage()); } } if (signatureValid) { result = true; LOG.debug("timestampToken is valid"); } else { result = false; throw new Exception("timestamp is not valid ", lastException); } return result; }
Example #17
Source File: CounterSignatureValidationTest.java From dss with GNU Lesser General Public License v2.1 | 3 votes |
@Override protected DSSDocument getSignedDocument() { FileDocument fileDocument = new FileDocument("src/test/resources/validation/counterSig.p7m"); try (InputStream is = fileDocument.openStream()) { CMSSignedData cms = new CMSSignedData(is); Collection<SignerInformation> signers = cms.getSignerInfos().getSigners(); assertEquals(1, signers.size()); Store<X509CertificateHolder> certificates = cms.getCertificates(); SignerInformation signerInformation = signers.iterator().next(); Collection<X509CertificateHolder> matches = certificates.getMatches(signerInformation.getSID()); X509CertificateHolder cert = matches.iterator().next(); SignerInformationVerifier verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider(new BouncyCastleProvider()).build(cert); assertTrue(signerInformation.verify(verifier)); SignerInformationStore counterSignatures = signerInformation.getCounterSignatures(); for (SignerInformation counterSigner : counterSignatures) { Collection<X509CertificateHolder> matchesCounter = certificates.getMatches(counterSigner.getSID()); X509CertificateHolder counterCert = matchesCounter.iterator().next(); SignerInformationVerifier counterVerifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider(new BouncyCastleProvider()).build(counterCert); assertTrue(counterSigner.verify(counterVerifier)); } } catch (Exception e) { fail(e); } return fileDocument; }