Example usage for org.bouncycastle.cms SignerInformation verify

List of usage examples for org.bouncycastle.cms SignerInformation verify

Introduction

In this page you can find the example usage for org.bouncycastle.cms SignerInformation verify.

Prototype

public boolean verify(SignerInformationVerifier verifier) throws CMSException 

Source Link

Document

Verify that the given verifier can successfully verify the signature on this SignerInformation object.

Usage

From source file:com.zotoh.crypto.CryptoUte.java

License:Open Source License

/**
 * @param mp//www  .jav a  2s . c  o m
 * @param certs
 * @param cte
 * @return
 * @throws MessagingException
 * @throws GeneralSecurityException
 * @throws IOException
 * @throws CertificateEncodingException
 */
public static Tuple verifySmimeDigSig(Multipart mp, Certificate[] certs, String cte)
        throws MessagingException, GeneralSecurityException, IOException, CertificateEncodingException {

    tstArgIsType("multipart", mp, MimeMultipart.class);
    tstObjArg("certs", certs);

    MimeMultipart mmp = (MimeMultipart) mp;
    SMIMESigned sc;
    SignerInformation si;
    byte[] digest = null;

    try {
        sc = isEmpty(cte) ? new SMIMESigned(mmp) : new SMIMESigned(mmp, cte);
    } catch (CMSException e) {
        throw new GeneralSecurityException(e);
    }

    Provider prov = Crypto.getInstance().getProvider();
    Store s = new JcaCertStore(asList(true, certs));
    Collection<?> c;
    JcaSimpleSignerInfoVerifierBuilder bdr;
    for (Object obj : sc.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 verify signature: no matching certificate");
    }
    //else
    return new Tuple(sc.getContentAsMimeMessage(newSession()).getContent(), digest);
}

From source file:com.zotoh.crypto.CryptoUte.java

License:Open Source License

/**
 * @param cert/*from  ww  w.  j a  va  2 s  . 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;
}

From source file:de.mendelson.util.security.BCCryptoHelper.java

/**
* Returns the digest OID algorithm from a signature. The return value
* for sha1 is e.g. "1.3.14.3.2.26"./*from  ww  w  .  ja  va 2s  . c  o m*/
*/
public String getDigestAlgOIDFromSignature(InputStream signed, Certificate cert) throws Exception {
    CMSSignedDataParser parser = new CMSSignedDataParser(
            new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(), signed);
    parser.getSignedContent().drain();
    SignerInformationStore signers = parser.getSignerInfos();
    Collection signerCollection = signers.getSigners();
    Iterator it = signerCollection.iterator();
    boolean verified = false;
    X509CertificateHolder certHolder = new X509CertificateHolder(cert.getEncoded());
    SignerInformationVerifier verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC")
            .build(certHolder);
    while (it.hasNext()) {
        SignerInformation signerInformation = (SignerInformation) it.next();
        if (!verified) {
            verified = signerInformation.verify(verifier);
            if (verified) {
                return (signerInformation.getDigestAlgOID());
            }
        }
    }
    throw new GeneralSecurityException("getDigestAlgOIDFromSignature: Unable to identify signature algorithm.");
}

From source file:de.mendelson.util.security.BCCryptoHelper.java

/**
 * Verifies a signature of a passed content against the passed certificate
 *///from  ww w .  ja va2s. co m
public boolean verify(byte[] content, byte[] signature, Certificate cert) throws Exception {
    if (content == null) {
        throw new GeneralSecurityException("verify: Content is absent");
    }
    if (signature == null) {
        throw new GeneralSecurityException("verify: Signature is absent");
    }
    if (signature.length == 0) {
        throw new Exception("verify: Signature length is 0");
    }
    CMSTypedStream signedContent = new CMSTypedStream(new ByteArrayInputStream(content));
    CMSSignedDataParser dataParser = new CMSSignedDataParser(new BcDigestCalculatorProvider(), signedContent,
            new ByteArrayInputStream(signature));
    dataParser.getSignedContent().drain();
    SignerInformationStore signers = dataParser.getSignerInfos();
    Collection signerCollection = signers.getSigners();
    Iterator it = signerCollection.iterator();
    X509CertificateHolder certHolder = new X509CertificateHolder(cert.getEncoded());
    SignerInformationVerifier verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC")
            .build(certHolder);
    boolean verified = false;
    while (it.hasNext()) {
        SignerInformation signerInformation = (SignerInformation) it.next();
        if (!verified) {
            verified = signerInformation.verify(verifier);
        }
        if (verified) {
            break;
        }
    }
    return (verified);
}

From source file:de.mendelson.util.security.BCCryptoHelper.java

/**
 * Verifies a signature against the passed certificate
 *
 * @param contentTransferEncoding one of 7bit quoted-printable base64 8bit
 * binary//from w w w.  j a va  2 s . c o  m
 */
public MimeBodyPart verify(Part part, String contentTransferEncoding, Certificate cert) throws Exception {
    if (part == null) {
        throw new GeneralSecurityException("Signature verification failed: Mime part is absent");
    }
    if (part.isMimeType("multipart/signed")) {
        MimeMultipart signedMultiPart = (MimeMultipart) part.getContent();
        //possible encoding: 7bit quoted-printable base64 8bit binary
        SMIMESigned signed = null;
        if (contentTransferEncoding == null) {
            //the default encoding in BC is 7bit but the default content transfer encoding in AS2 is binary.
            signed = new SMIMESigned(signedMultiPart, "binary");
        } else {
            signed = new SMIMESigned(signedMultiPart, contentTransferEncoding);
        }
        X509Certificate x509Cert = this.castCertificate(cert);
        X509CertificateHolder certHolder = new X509CertificateHolder(cert.getEncoded());
        SignerInformationVerifier verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC")
                .build(certHolder);
        SignerInformationStore signerStore = signed.getSignerInfos();
        Iterator<SignerInformation> iterator = signerStore.getSigners().iterator();
        while (iterator.hasNext()) {
            SignerInformation signerInfo = iterator.next();
            if (!signerInfo.verify(verifier)) {
                StringBuilder signatureCertInfo = new StringBuilder();
                //try to gain more information about the problem
                if (signerInfo.getSID() != null) {
                    if (signerInfo.getSID().getSerialNumber() != null) {
                        signatureCertInfo.append("Serial number (DEC): ");
                        signatureCertInfo.append(signerInfo.getSID().getSerialNumber());
                    }
                    if (signerInfo.getSID().getIssuer() != null) {
                        if (signatureCertInfo.length() > 0) {
                            signatureCertInfo.append("\n");
                        }
                        signatureCertInfo.append("Issuer: ");
                        signatureCertInfo.append(signerInfo.getSID().getIssuer().toString());
                    }
                }
                if (signatureCertInfo.length() > 0) {
                    signatureCertInfo.insert(0, "Signature certificate information:\n");
                }
                StringBuilder checkCertInfo = new StringBuilder();
                KeystoreCertificate certificate = new KeystoreCertificate();
                certificate.setCertificate(x509Cert);
                checkCertInfo.append("Verification certificate information:\n");
                checkCertInfo.append("Serial number (DEC): ");
                checkCertInfo.append(certificate.getSerialNumberDEC());
                checkCertInfo.append("\n");
                checkCertInfo.append("Serial number (HEX): ");
                checkCertInfo.append(certificate.getSerialNumberHEX());
                checkCertInfo.append("\n");
                checkCertInfo.append("Finger print (SHA-1): ");
                checkCertInfo.append(certificate.getFingerPrintSHA1());
                checkCertInfo.append("\n");
                checkCertInfo.append("Valid from: ");
                checkCertInfo.append(
                        DateFormat.getDateInstance(DateFormat.SHORT).format(certificate.getNotBefore()));
                checkCertInfo.append("\n");
                checkCertInfo.append("Valid to: ");
                checkCertInfo
                        .append(DateFormat.getDateInstance(DateFormat.SHORT).format(certificate.getNotAfter()));
                checkCertInfo.append("\n");
                checkCertInfo.append("Issuer: ");
                checkCertInfo.append(x509Cert.getIssuerX500Principal().toString());
                StringBuilder message = new StringBuilder("Verification failed");
                message.append("\n\n");
                message.append(signatureCertInfo);
                message.append("\n\n");
                message.append(checkCertInfo);
                throw new SignatureException(message.toString());
            }
        }
        return signed.getContent();
    } else {
        throw new GeneralSecurityException("Content-Type indicates data isn't signed");
    }
}

From source file:de.mendelson.util.security.BCCryptoHelper.java

public boolean verifySignatureCMS(InputStream signed, Certificate cert) throws Exception {
    CMSSignedDataParser parser = new CMSSignedDataParser(
            new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(), signed);
    parser.getSignedContent().drain();//from  ww  w  . j ava 2s. c  o m
    SignerInformationStore signers = parser.getSignerInfos();
    Collection signerCollection = signers.getSigners();
    Iterator it = signerCollection.iterator();
    boolean verified = false;
    X509CertificateHolder certHolder = new X509CertificateHolder(cert.getEncoded());
    SignerInformationVerifier verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC")
            .build(certHolder);
    while (it.hasNext()) {
        SignerInformation signerInformation = (SignerInformation) it.next();
        if (!verified) {
            verified = signerInformation.verify(verifier);
        }
        if (verified) {
            break;
        }
    }
    return (verified);
}

From source file:ee.ria.xroad.common.signature.TimestampVerifier.java

License:Open Source License

/**
 * Verifies that the time-stamp token is signed by a trusted
 * time-stamping authority./*from  ww w  .j ava2 s .  c  o  m*/
 * @param tsToken the time-stamp token
 * @param tspCerts list of TSP certificates
 * @throws Exception if the verification failed
 */
public static void verify(TimeStampToken tsToken, List<X509Certificate> tspCerts) throws Exception {
    if (tspCerts.isEmpty()) {
        throw new CodedException(X_INTERNAL_ERROR, "No TSP service providers are configured.");
    }

    SignerId signerId = tsToken.getSID();

    X509Certificate cert = getTspCertificate(signerId, tspCerts);
    if (cert == null) {
        throw new CodedException(X_INTERNAL_ERROR, "Could not find TSP certificate for timestamp");
    }

    SignerInformation signerInfo = tsToken.toCMSSignedData().getSignerInfos().get(signerId);
    if (signerInfo == null) {
        throw new CodedException(X_INTERNAL_ERROR,
                "Could not get signer information for " + signerId.getSerialNumber());
    }

    SignerInformationVerifier verifier = createVerifier(cert);
    if (!signerInfo.verify(verifier)) {
        throw new CodedException(X_TIMESTAMP_VALIDATION, "Failed to verify timestamp");
    }
}

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&aacute;lida, no hace nada. Si no es
 * v&aacute;lida, lanza una excepci&oacute;n.
 * @param sign Firma que se desea validar.
 * @param data Datos para la comprobaci&oacute;n.
 * @throws CMSException Cuando la firma no tenga una estructura v&aacute;lida.
 * @throws CertStoreException Cuando se encuentra un error en los certificados de
 * firma o estos no pueden recuperarse./* w ww  . j a v a 2  s. c  o  m*/
 * @throws CertificateExpiredException Cuando el certificado est&aacute;a caducado.
 * @throws CertificateNotYetValidException Cuando el certificado aun no es v&aacute;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&aacute;lida, no hace nada. Si no es
 * v&aacute;lida, lanza una excepci&oacute;n.
 * @param sign Firma que se desea validar.
 * @param data Datos para la comprobaci&oacute;n.
 * @throws CMSException Cuando la firma no tenga una estructura v&aacute;lida.
 * @throws CertStoreException Cuando se encuentra un error en los certificados de
 * firma o estos no pueden recuperarse.//from w ww .  j a  va  2s.c  om
 * @throws CertificateExpiredException Cuando el certificado est&aacute;a caducado.
 * @throws CertificateNotYetValidException Cuando el certificado aun no es v&aacute;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: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//from w w w  .  j  av a2  s. co 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;
}