List of usage examples for org.bouncycastle.cms CMSSignedData CMSSignedData
public CMSSignedData(Map hashes, ContentInfo sigData) throws CMSException
From source file:bluecrystal.bcdeps.helper.PkiOps.java
License:Open Source License
public boolean verify(String contentPath, String envPath) throws Exception { CMSSignedData csd = null;/* w w w .ja v a2 s . c om*/ byte[] buffer = loadEnv(envPath); if (contentPath != null) { byte[] content = getBytesFromFile(new File(contentPath)); CMSProcessableByteArray cpbfile = new CMSProcessableByteArray(content); csd = new CMSSignedData(cpbfile, buffer); } else { csd = new CMSSignedData(buffer); } return verify(csd); }
From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java
License:Open Source License
@SuppressWarnings("unchecked") protected static String validarAssinaturaCMS(byte[] digest, String digestAlgorithm, byte[] assinatura, Date dtAssinatura) throws InvalidKeyException, SecurityException, CRLException, CertificateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, AplicacaoException, ChainValidationException, IOException, Exception { final CMSSignedData s; if (digest != null) { Map<String, byte[]> map = new HashMap<String, byte[]>(); map.put(digestAlgorithm, digest); s = new CMSSignedData(map, assinatura); } else {/*from ww w . j a v a 2 s.c o m*/ s = new CMSSignedData(assinatura); } Store certs = s.getCertificates(); SignerInformationStore signers = s.getSignerInfos(); Collection<SignerInformation> c = signers.getSigners(); Iterator<SignerInformation> it = c.iterator(); X509CertificateHolder firstSignerCert = null; while (it.hasNext()) { SignerInformation signer = it.next(); Collection<X509CertificateHolder> certCollection = certs.getMatches(signer.getSID()); Iterator<X509CertificateHolder> certIt = certCollection.iterator(); X509CertificateHolder cert = certIt.next(); if (firstSignerCert == null) firstSignerCert = cert; if (!signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))) throw new Exception("Assinatura invlida!"); System.out.println("\nSigner Info: \n"); System.out.println("Is Signature Valid? true"); System.out.println("Digest: " + asHex(signer.getContentDigest())); System.out.println("Enc Alg Oid: " + signer.getEncryptionAlgOID()); System.out.println("Digest Alg Oid: " + signer.getDigestAlgOID()); System.out.println("Signature: " + asHex(signer.getSignature())); } // X509Certificate[] cadeiaTotal = montarCadeiaOrdenadaECompleta((Collection<X509Certificate>) (certs.getCertificates(null))); X509Certificate[] cadeiaTotal = montarCadeiaOrdenadaECompleta(certs.getMatches(null)); List<X509CRLObject> crls = new ArrayList<>(); if (certs.getMatches(null) != null) { Enumeration ec = ASN1Set.getInstance(certs.getMatches(null)).getObjects(); while (ec.hasMoreElements()) { crls.add(new X509CRLObject(CertificateList.getInstance(ec.nextElement()))); } } final X509ChainValidator cadeia = new X509ChainValidator(cadeiaTotal, /* trustedAnchors */new HashSet(FachadaDeCertificadosAC.getTrustAnchors()), crls.toArray(new X509CRLObject[0])); cadeia.checkCRL(true); try { cadeia.validateChain(dtAssinatura); } catch (Exception e1) { if (e1.getMessage().endsWith("Validation time is in future.")) { String s1 = e1.getMessage() + " Current date: [" + new Date().toString() + "]. Record date: [" + dtAssinatura + "]. LCRs' dates ["; for (X509CRLObject crl : (Collection<X509CRLObject>) certs.getMatches(null)) { String s2 = crl.getIssuerX500Principal().getName(); s2 = s2.split(",")[0]; s1 += s2 + " (" + crl.getThisUpdate() + " - " + crl.getNextUpdate() + ") "; } s1 += "]"; throw new AplicacaoException(s1, 0, e1); } else throw e1; } // String s1 = firstSignerCert.getSubjectDN().getName(); String s1 = firstSignerCert.getSubject().toString(); s1 = obterNomeExibicao(s1); return s1; }
From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java
License:Open Source License
@SuppressWarnings("unchecked") protected static String validarAssinaturaCMSeCarimboDeTempo(final byte[] digest, final String digestAlgorithm, final byte[] assinatura, Date dtAssinatura) throws InvalidKeyException, SecurityException, CRLException, CertificateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, AplicacaoException, ChainValidationException, IOException, Exception { String nome = validarAssinaturaCMS(digest, digestAlgorithm, assinatura, dtAssinatura); Map<String, byte[]> map = new HashMap<String, byte[]>(); map.put(digestAlgorithm, digest);//from ww w . java 2 s .co m final CMSSignedData s = new CMSSignedData(map, assinatura); Collection ss = s.getSignerInfos().getSigners(); SignerInformation si = (SignerInformation) ss.iterator().next(); Attribute attr = si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken); CMSSignedData cmsTS = new CMSSignedData(attr.getAttrValues().getObjectAt(0).toASN1Primitive().getEncoded()); TimeStampToken tok = new TimeStampToken(cmsTS); Store cs = tok.getCertificates(); SignerId signer_id = tok.getSID(); BigInteger cert_serial_number = signer_id.getSerialNumber(); Collection certs = cs.getMatches(null); Iterator iter = certs.iterator(); X509Certificate certificate = null; while (iter.hasNext()) { X509Certificate cert = (X509Certificate) iter.next(); if (cert_serial_number != null) { if (cert.getSerialNumber().equals(cert_serial_number)) { certificate = cert; } } else { if (certificate == null) { certificate = cert; } } } tok.validate(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certificate)); // Nato: falta validar as CRLs do carimbo de tempo if (!Arrays.equals(tok.getTimeStampInfo().getMessageImprintDigest(), MessageDigest.getInstance("SHA1").digest(si.getSignature()))) { throw new Exception("Carimbo de tempo no confere com o resumo do documento"); } try { validarAssinaturaCMS(null, null, cmsTS.getEncoded(), tok.getTimeStampInfo().getGenTime()); } catch (Exception e) { throw new Exception("Carimbo de tempo invlido!", e); } return nome; }
From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java
License:Open Source License
@SuppressWarnings("unchecked") public static String validarAssinaturaPKCS7(final byte[] digest, final String digestAlgorithm, final byte[] assinatura, Date dtAssinatura, boolean verificarLCRs) throws InvalidKeyException, SecurityException, CRLException, CertificateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, AplicacaoException, ChainValidationException, IOException, Exception { Map<String, byte[]> map = new HashMap<String, byte[]>(); map.put(digestAlgorithm, digest);// w w w . jav a 2 s . c o m final CMSSignedData signedData = new CMSSignedData(map, assinatura); Store certs = signedData.getCertificates(); SignerInformationStore signers = signedData.getSignerInfos(); Collection<SignerInformation> c = signers.getSigners(); Iterator<SignerInformation> it = c.iterator(); String sCN = ""; while (it.hasNext()) { SignerInformation signer = it.next(); Collection<X509CertificateHolder> certCollection = certs.getMatches(signer.getSID()); @SuppressWarnings("unused") String ss = signer.getDigestAlgOID(); @SuppressWarnings("unused") String sss = signer.getDigestAlgorithmID().getObjectId().getId(); Iterator<X509CertificateHolder> certIt = certCollection.iterator(); X509CertificateHolder certHolder = certIt.next(); X509Certificate cert = AssinaturaDigital.getX509Certificate(certHolder); if (!signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certHolder))) throw new Exception("Assinatura invlida!"); X509Certificate[] cadeiaTotal = montarCadeiaOrdenadaECompleta(certCollection); final X509ChainValidator cadeia = new X509ChainValidator(cadeiaTotal, /* trustedAnchors */new HashSet(FachadaDeCertificadosAC.getTrustAnchors()), null); cadeia.checkCRL(verificarLCRs); cadeia.validateChain(dtAssinatura); String s2 = cert.getSubjectDN().getName(); s2 = obterNomeExibicao(s2); if (sCN.length() != 0) sCN += ", "; sCN += s2; } return sCN.length() == 0 ? null : sCN; }
From source file:chapter9.SignedDataExample.java
/** * * @param args// www . j a v a2 s . c o m * @throws Exception */ public static void main(String[] args) throws Exception { KeyStore credentials = Utils.createCredentials(); PrivateKey key = (PrivateKey) credentials.getKey(Utils.END_ENTITY_ALIAS, Utils.KEY_PASSWD); Certificate[] chain = credentials.getCertificateChain(Utils.END_ENTITY_ALIAS); CertStore certsAndCRLs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(Arrays.asList(chain)), CryptoDefs.Provider.BC.getName()); X509Certificate cert = (X509Certificate) chain[0]; // Set up the generator CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); gen.addSigner(key, cert, CMSSignedDataGenerator.DIGEST_SHA224); gen.addCertificatesAndCRLs(certsAndCRLs); // Create the signed-data object CMSProcessable data = new CMSProcessableByteArray("Hello World!!".getBytes()); CMSSignedData signed = gen.generate(data, CryptoDefs.Provider.BC.getName()); // Re-create signed = new CMSSignedData(data, signed.getEncoded()); // Verification step X509Certificate rootCert = (X509Certificate) credentials.getCertificate(Utils.ROOT_ALIAS); if (isValid(signed, rootCert)) System.out.println("verification succeeded!!"); else System.out.println("verification failed!!"); }
From source file:com.blackberry.bidhelper.BidCertificateVerifierAndroid.java
License:Apache License
@Override public boolean verifyReport(byte[] tzReport, byte[] signature) throws CertificateException { if (this.bidCert == null) { throw new IllegalStateException("Certificate not yet set"); }/*from ww w. j av a 2s. c o m*/ try { CMSSignedData cms = new CMSSignedData(new CMSProcessableByteArray(tzReport), signature); Store certStore = cms.getCertificates(); SignerInformationStore signers = cms.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); if (c.size() != 1) { return false; } while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); Collection certCollection = certStore.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); // If there is no certificate part of the signature then the report may have been created before // the certificate was cut. if (certCollection.size() == 0) { return signer .verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(this.bidCert)); } X509CertificateHolder certHolder = (X509CertificateHolder) certIt.next(); X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC") .getCertificate(certHolder); return signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert)); } } catch (CMSException e) { throw new CertificateException(e.toString()); } catch (OperatorCreationException oce) { throw new CertificateException(oce.toString()); } catch (Exception ex) { throw ex; } return false; }
From source file:com.google.code.p.keytooliui.ktl.util.jarsigner.CmsVerif.java
License:LGPL
private CMSSignedData _getSignPkcs7() throws Exception { //File fleDoc = new File("D:\\Mes Documents bantchao\\_perso\\prod\\rcp\\_test\\mon_fichier.txt"); File fleDoc = new File(super._strPathAbsFileData_); byte[] bytsDoc = _read(fleDoc); File fleSigCmsPkcs7 = new File(super._strPathAbsFileSig_); byte[] bytsSigCmsPkcs7 = _read(fleSigCmsPkcs7); CMSProcessable cmdProcDoc = new CMSProcessableByteArray(bytsDoc); CMSSignedData cms = new CMSSignedData(cmdProcDoc, bytsSigCmsPkcs7); return cms;// w w w . j a v a2 s . c om }
From source file:com.guardtime.ksi.trust.CMSSignature.java
License:Apache License
public CMSSignature(byte[] signedData, byte[] cmsSignature) throws InvalidCmsSignatureException { try {//from w ww . j a v a 2 s .c om if (signedData == null || signedData.length < 1) { throw new InvalidCmsSignatureException("CMS signature signed data is null or empty array"); } if (cmsSignature == null || cmsSignature.length < 1) { throw new InvalidCmsSignatureException("CMS signature is null or empty array"); } CMSProcessableByteArray cmsProcessable = new CMSProcessableByteArray(signedData); CMSSignedData cmsSignedData = new CMSSignedData(cmsProcessable, cmsSignature); this.signerInformationStore = cmsSignedData.getSignerInfos(); this.signedDataCertificates = cmsSignedData.getCertificates(); LOGGER.debug("CMS signature contains {} signer information elements", signerInformationStore.size()); } catch (CMSException e) { throw new InvalidCmsSignatureException("Invalid CMS signature", e); } }
From source file:com.yahoo.athenz.auth.util.Crypto.java
License:Apache License
public static boolean validatePKCS7Signature(String data, String signature, PublicKey publicKey) { try {//from w w w.j a v a2 s . com SignerInformationStore signerStore = null; try (InputStream sigIs = new ByteArrayInputStream( Base64.decode(signature.getBytes(StandardCharsets.UTF_8)))) { CMSProcessable content = new CMSProcessableByteArray(data.getBytes(StandardCharsets.UTF_8)); CMSSignedData signedData = new CMSSignedData(content, sigIs); signerStore = signedData.getSignerInfos(); } Collection<SignerInformation> signers = signerStore.getSigners(); Iterator<SignerInformation> it = signers.iterator(); SignerInformationVerifier infoVerifier = new JcaSimpleSignerInfoVerifierBuilder() .setProvider(BC_PROVIDER).build(publicKey); while (it.hasNext()) { SignerInformation signerInfo = (SignerInformation) it.next(); if (signerInfo.verify(infoVerifier)) { return true; } } } catch (CMSException ex) { LOG.error("validatePKCS7Signature: unable to initialize CMSSignedData object: " + ex.getMessage()); throw new CryptoException(ex); } catch (OperatorCreationException ex) { LOG.error( "validatePKCS7Signature: Caught OperatorCreationException when creating JcaSimpleSignerInfoVerifierBuilder: " + ex.getMessage()); throw new CryptoException(ex); } catch (IOException ex) { LOG.error("validatePKCS7Signature: Caught IOException when closing InputStream: " + ex.getMessage()); throw new CryptoException(ex); } catch (Exception ex) { LOG.error("validatePKCS7Signature: unable to validate signature: " + ex.getMessage()); throw new CryptoException(ex.getMessage()); } return false; }
From source file:com.zotoh.crypto.CryptoUte.java
License:Open Source License
/** * @param cert//from w w w .j a v a 2s .c o m * @param data * @param signature * @return * @throws GeneralSecurityException * @throws IOException * @throws CertificateEncodingException */ public static byte[] verifyPkcsDigSig(Certificate cert, StreamData data, byte[] signature) throws GeneralSecurityException, IOException, CertificateEncodingException { tstObjArg("digital-signature", signature); tstObjArg("cert", cert); tstObjArg("input-content", data); Provider prov = Crypto.getInstance().getProvider(); SignerInformation si; CMSProcessable cproc; CMSSignedData cms; byte[] digest; if (data.isDiskFile()) { cproc = new CMSProcessableFile(data.getFileRef()); } else { cproc = new CMSProcessableByteArray(data.getBytes()); } try { cms = new CMSSignedData(cproc, signature); digest = null; } catch (CMSException e) { throw new GeneralSecurityException(e); } List<Certificate> cl = LT(); cl.add(cert); Store s = new JcaCertStore(cl); Collection<?> c; JcaSimpleSignerInfoVerifierBuilder bdr; for (Object obj : cms.getSignerInfos().getSigners()) try { si = (SignerInformation) obj; c = s.getMatches(si.getSID()); for (Iterator<?> it = c.iterator(); it.hasNext();) { bdr = new JcaSimpleSignerInfoVerifierBuilder().setProvider(prov); if (si.verify(bdr.build((X509CertificateHolder) it.next()))) { digest = si.getContentDigest(); break; } } if (digest != null) { break; } } catch (Exception e) { } if (digest == null) { throw new GeneralSecurityException("Failed to decode signature: no matching certificate"); } // else return digest; }