List of usage examples for org.bouncycastle.cms CMSSignedData getSignerInfos
public SignerInformationStore getSignerInfos()
From source file:com.zotoh.crypto.CryptoUte.java
License:Open Source License
/** * @param cert//from w w w. j a va2 s . co 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; }
From source file:de.mendelson.util.security.BCCryptoHelper.java
/** * Returns the digest OID algorithm from a pkcs7 signature The return value * for sha1 is e.g. "1.3.14.3.2.26"./* w w w.jav a 2s. co m*/ */ public String getDigestAlgOIDFromSignature(byte[] signature) throws Exception { if (signature == null) { throw new GeneralSecurityException("getDigestAlgOIDFromSignature: Signature is absent"); } CMSSignedData signedData = new CMSSignedData(signature); SignerInformationStore signers = signedData.getSignerInfos(); Collection signerCollection = signers.getSigners(); Iterator iterator = signerCollection.iterator(); while (iterator.hasNext()) { SignerInformation signerInfo = (SignerInformation) iterator.next(); return (signerInfo.getDigestAlgOID()); } throw new GeneralSecurityException("getDigestAlgOIDFromSignature: Unable to identify signature algorithm."); }
From source file:ec.gov.informatica.firmadigital.signature.BouncyCastleSignatureProcessor.java
License:Open Source License
public byte[] verify(byte[] signedBytes) throws SignatureVerificationException { try {//from w w w . j a v a 2s.c om Signature sig = Signature.getInstance("Sha1withRSAEncryption"); CMSSignedData signedData = new CMSSignedData(signedBytes); CertStore certs = signedData.getCertificatesAndCRLs("Collection", "BC"); Collection<SignerInformation> signers = signedData.getSignerInfos().getSigners(); for (SignerInformation signer : signers) { Collection<? extends Certificate> certCollection = certs.getCertificates(signer.getSID()); if (!certCollection.isEmpty()) { X509Certificate cert = (X509Certificate) certCollection.iterator().next(); if (!signer.verify(cert.getPublicKey(), "BC")) { throw new SignatureVerificationException("La firma no verifico con " + signer.getSID()); } setCert(cert); } } CMSProcessable signedContent = signedData.getSignedContent(); System.out.println("Tiene:" + signedContent.getContent()); return (byte[]) signedContent.getContent(); } catch (GeneralSecurityException e) { throw new RuntimeException(e); // FIXME } catch (CMSException e) { throw new RuntimeException(e); // FIXME } }
From source file:ec.gov.informatica.firmadigital.signature.BouncyCastleSignatureProcessor.java
License:Open Source License
@Override public byte[] addSignature(byte[] signedBytes, PrivateKey privateKey, Certificate[] chain) { X509Certificate cert = (X509Certificate) chain[0]; try {//from w w w. j a v a2s. com CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); generator.addSigner(privateKey, cert, CMSSignedDataGenerator.DIGEST_SHA1); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(Arrays.asList(chain))); CMSSignedData signedData = new CMSSignedData(signedBytes); SignerInformationStore signers = signedData.getSignerInfos(); CertStore existingCerts = signedData.getCertificatesAndCRLs("Collection", "BC"); X509Store x509Store = signedData.getAttributeCertificates("Collection", "BC"); // add new certs generator.addCertificatesAndCRLs(certs); // add existing certs generator.addCertificatesAndCRLs(existingCerts); // add existing certs attributes generator.addAttributeCertificates(x509Store); // add existing signers generator.addSigners(signers); CMSProcessable content = signedData.getSignedContent(); signedData = generator.generate(content, true, "BC"); return signedData.getEncoded(); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } catch (CMSException e) { throw new RuntimeException(e); } catch (NoSuchStoreException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:es.gob.afirma.cert.signvalidation.ValidateBinarySignature.java
License:Open Source License
/** Verifica la valides de una firma. Si la firma es válida, no hace nada. Si no es * válida, lanza una excepción. * @param sign Firma que se desea validar. * @param data Datos para la comprobación. * @throws CMSException Cuando la firma no tenga una estructura válida. * @throws CertStoreException Cuando se encuentra un error en los certificados de * firma o estos no pueden recuperarse.// ww w . j ava2 s. co m * @throws CertificateExpiredException Cuando el certificado estáa caducado. * @throws CertificateNotYetValidException Cuando el certificado aun no es válido. * @throws NoSuchAlgorithmException Cuando no se reconoce o soporta alguno de los * algoritmos utilizados en la firma. * @throws NoMatchDataException Cuando los datos introducidos no coinciden con los firmados. * @throws CRLException Cuando ocurre un error con las CRL de la firma. * @throws NoSuchProviderException Cuando no se encuentran los proveedores de seguridad necesarios para validar la firma * @throws IOException Cuando no se puede crear un certificado desde la firma para validarlo * @throws OperatorCreationException Cuando no se puede crear el validado de contenido de firma*/ private static void verifySignatures(final byte[] sign, final byte[] data) throws CMSException, CertStoreException, NoSuchAlgorithmException, NoMatchDataException, CRLException, NoSuchProviderException, CertificateException, IOException, OperatorCreationException { final CMSSignedData s; if (data == null) { s = new CMSSignedData(sign); } else { s = new CMSSignedData(new CMSProcessableByteArray(data), sign); } final Store<X509CertificateHolder> store = s.getCertificates(); final CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); //$NON-NLS-1$ for (final Object si : s.getSignerInfos().getSigners()) { final SignerInformation signer = (SignerInformation) si; final Iterator<X509CertificateHolder> certIt = store .getMatches(new CertHolderBySignerIdSelector(signer.getSID())).iterator(); final X509Certificate cert = (X509Certificate) certFactory .generateCertificate(new ByteArrayInputStream(certIt.next().getEncoded())); if (!signer .verify(new SignerInformationVerifier(new DefaultCMSSignatureAlgorithmNameGenerator(), new DefaultSignatureAlgorithmIdentifierFinder(), new JcaContentVerifierProviderBuilder() .setProvider(new BouncyCastleProvider()).build(cert), new BcDigestCalculatorProvider()))) { throw new CMSException("Firma no valida"); //$NON-NLS-1$ } } }
From source file:es.gob.afirma.signature.ValidateBinarySignature.java
License:Open Source License
/** Verifica la valides de una firma. Si la firma es válida, no hace nada. Si no es * válida, lanza una excepción. * @param sign Firma que se desea validar. * @param data Datos para la comprobación. * @throws CMSException Cuando la firma no tenga una estructura válida. * @throws CertStoreException Cuando se encuentra un error en los certificados de * firma o estos no pueden recuperarse.//from ww w. j ava 2 s . com * @throws CertificateExpiredException Cuando el certificado estáa caducado. * @throws CertificateNotYetValidException Cuando el certificado aun no es válido. * @throws NoSuchAlgorithmException Cuando no se reconoce o soporta alguno de los * algoritmos utilizados en la firma. * @throws NoMatchDataException Cuando los datos introducidos no coinciden con los firmados. * @throws CRLException Cuando ocurre un error con las CRL de la firma. * @throws NoSuchProviderException Cuando no se encuentran los proveedores de seguridad necesarios para validar la firma * @throws IOException Cuando no se puede crear un certificado desde la firma para validarlo * @throws OperatorCreationException Cuando no se puede crear el validado de contenido de firma*/ private static void verifySignatures(final byte[] sign, final byte[] data) throws CMSException, CertStoreException, NoSuchAlgorithmException, NoMatchDataException, CRLException, NoSuchProviderException, CertificateException, IOException, OperatorCreationException { final CMSSignedData s; if (data == null) { s = new CMSSignedData(sign); } else { s = new CMSSignedData(new CMSProcessableByteArray(data), sign); } final Store store = s.getCertificates(); final CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); //$NON-NLS-1$ for (final Object si : s.getSignerInfos().getSigners()) { final SignerInformation signer = (SignerInformation) si; final Iterator<X509CertificateHolder> certIt = store .getMatches(new CertHolderBySignerIdSelector(signer.getSID())).iterator(); final X509Certificate cert = (X509Certificate) certFactory .generateCertificate(new ByteArrayInputStream(certIt.next().getEncoded())); if (!signer .verify(new SignerInformationVerifier(new DefaultCMSSignatureAlgorithmNameGenerator(), new DefaultSignatureAlgorithmIdentifierFinder(), new JcaContentVerifierProviderBuilder() .setProvider(new BouncyCastleProvider()).build(cert), new BcDigestCalculatorProvider()))) { throw new CMSException("Firma no valida"); //$NON-NLS-1$ } } }
From source file:es.gob.afirma.signers.tsp.pkcs7.CMSTimestamper.java
License:Open Source License
/** Añade un sello de tiempo a las firmas encontradas dentro de una estructura PKCS#7. * @param pkcs7 Estructura que contiene las firmas a estampar un sello de tiempo * @param hashAlgorithm Algoritmo de huella digital a usar en los sellos de tiempo (si se indica <code>null</code> se usa SHA-1) * @param time Tiempo del sello/*from ww w . j ava 2 s.c o m*/ * @return Nueva estructura PKCS#7 con los sellos de tiempo añadidos * @throws NoSuchAlgorithmException Si no se soporta el algoritmo de huella digital del sello de tiempo * @throws AOException Cuando ocurren errores genéricos * @throws IOException Si hay errores de entrada / salida */ public byte[] addTimestamp(final byte[] pkcs7, final String hashAlgorithm, final Calendar time) throws NoSuchAlgorithmException, AOException, IOException { final String digestAlgorithm = AOSignConstants.getDigestAlgorithmName(hashAlgorithm); final CMSSignedData signedData; try { signedData = new CMSSignedData(pkcs7); } catch (final Exception e) { throw new IllegalArgumentException("Los datos de entrada no son un SignedData de CMS: " + e); //$NON-NLS-1$ } final SignerInformationStore origSignerInfoStore = signedData.getSignerInfos(); // Insertamos un sello de tiempo en cada una de las firmas encontradas en el PKCS#7 final List<SignerInformation> vNewSigners = new ArrayList<SignerInformation>(); final Collection<?> ovSigners = origSignerInfoStore.getSigners(); for (final Object name : ovSigners) { final SignerInformation si = (SignerInformation) name; final byte[] tsToken = getTimeStampToken( MessageDigest.getInstance(digestAlgorithm).digest(si.getSignature()), digestAlgorithm, time); final ASN1InputStream is = new ASN1InputStream(new ByteArrayInputStream(tsToken)); final ASN1Primitive derObj = is.readObject(); is.close(); final DERSet derSet = new DERSet(derObj); final Attribute unsignAtt = new Attribute(new ASN1ObjectIdentifier(SIGNATURE_TIMESTAMP_TOKEN_OID), derSet); final Hashtable<ASN1ObjectIdentifier, Attribute> ht = new Hashtable<ASN1ObjectIdentifier, Attribute>(); ht.put(new ASN1ObjectIdentifier(SIGNATURE_TIMESTAMP_TOKEN_OID), unsignAtt); final AttributeTable unsignedAtts = new AttributeTable(ht); vNewSigners.add(SignerInformation.replaceUnsignedAttributes(si, unsignedAtts)); } return CMSSignedData.replaceSigners(signedData, new SignerInformationStore(vNewSigners)).getEncoded(); }
From source file:eu.betaas.service.securitymanager.capability.utils.CapabilityUtils.java
License:Apache License
/** * Method to verify the signature of the exCap in a form of CMSSignedData * @param signedData: the signed data// ww w . j a v a2s . c o m * @return: true if the signature is valid, false otherwise * @throws CMSException * @throws OperatorException */ public static boolean validateCapSignature(CMSSignedData signedData) throws CMSException, OperatorException { Store certs = signedData.getCertificates(); SignerInformationStore signers = signedData.getSignerInfos(); Iterator it = signers.getSigners().iterator(); if (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); X509CertificateHolder cert = (X509CertificateHolder) certs.getMatches(signer.getSID()).iterator() .next(); SignerInformationVerifier verifier = new BcECDSASignerInfoVerifierBuilder( new DefaultCMSSignatureAlgorithmNameGenerator(), new DefaultSignatureAlgorithmIdentifierFinder(), new DefaultDigestAlgorithmIdentifierFinder(), new BcDigestCalculatorProvider()).build(cert); return signer.verify(verifier); } return false; }
From source file:eu.betaas.service.securitymanager.capability.utils.CapabilityUtils.java
License:Apache License
/** * Method to verify exCap's signature with the issuer certificate stored in * the signed data /*www. j a va2 s .c o m*/ * @param text: the original signed text * @param signature: the signature in byte[] * @return: true if signature is valid, false otherwise * @throws CMSException * @throws OperatorException */ public static boolean validateCapSignature(String text, byte[] signature) throws CMSException, OperatorException { CMSSignedData signedData = new CMSSignedData(new CMSProcessableByteArray(text.getBytes()), signature); Store certs = signedData.getCertificates(); SignerInformationStore signers = signedData.getSignerInfos(); Iterator it = signers.getSigners().iterator(); if (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); X509CertificateHolder cert = (X509CertificateHolder) certs.getMatches(signer.getSID()).iterator() .next(); SignerInformationVerifier verifier = new BcECDSASignerInfoVerifierBuilder( new DefaultCMSSignatureAlgorithmNameGenerator(), new DefaultSignatureAlgorithmIdentifierFinder(), new DefaultDigestAlgorithmIdentifierFinder(), new BcDigestCalculatorProvider()).build(cert); return signer.verify(verifier); } return false; }
From source file:eu.betaas.service.securitymanager.capability.utils.CapabilityUtils.java
License:Apache License
/** * Method to verify exCap's signature for the detached signature or the issuer * certificate is not stored in the signed data * @param text: the original signed text * @param signature: the signature in byte[] * @param cert: issuer certificate/* w ww .j a va 2 s .c o m*/ * @return: true if signature is valid, false otherwise * @throws CMSException * @throws OperatorException */ public static boolean validateCapSignature(String text, byte[] signature, X509CertificateHolder cert) throws CMSException, OperatorException { CMSSignedData signedData = new CMSSignedData(new CMSProcessableByteArray(text.getBytes()), signature); // Store certs = signedData.getCertificates(); SignerInformationStore signers = signedData.getSignerInfos(); Iterator it = signers.getSigners().iterator(); if (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); // X509CertificateHolder cert = (X509CertificateHolder)certs. // getMatches(signer.getSID()).iterator().next(); SignerInformationVerifier verifier = new BcECDSASignerInfoVerifierBuilder( new DefaultCMSSignatureAlgorithmNameGenerator(), new DefaultSignatureAlgorithmIdentifierFinder(), new DefaultDigestAlgorithmIdentifierFinder(), new BcDigestCalculatorProvider()).build(cert); return signer.verify(verifier); } return false; }