Example usage for org.bouncycastle.cms SignerInformation getSID

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

Introduction

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

Prototype

public SignerId getSID() 

Source Link

Usage

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.  java 2 s  .c  o 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&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 .  ja 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 a  v  a 2 s . 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 /*from  w  ww.jav  a2  s. com*/
 * @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.europa.ec.markt.dss.signature.cades.CAdESProfileC.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override// ww w . j a  v  a2s. c o m
protected SignerInformation extendCMSSignature(CMSSignedData signedData, SignerInformation si,
        SignatureParameters parameters, Document originalData) throws IOException {

    /* Get parent unsigned attributes */
    SignerInformation newSi = super.extendCMSSignature(signedData, si, parameters, originalData);
    Hashtable<ASN1ObjectIdentifier, ASN1Encodable> unsignedAttrs = newSi.getUnsignedAttributes().toHashtable();

    /* Extends unsigned attributes */
    CAdESSignature signature = new CAdESSignature(signedData, si.getSID());
    unsignedAttrs = extendUnsignedAttributes(unsignedAttrs, signature.getSigningCertificate(), parameters,
            signature.getSigningTime(), signature.getCertificateSource());

    /* Return new SignerInformation */
    return SignerInformation.replaceUnsignedAttributes(newSi, new AttributeTable(unsignedAttrs));
}

From source file:eu.europa.ec.markt.dss.signature.cades.CAdESProfileT.java

License:Open Source License

@SuppressWarnings("unchecked")
protected SignerInformation extendCMSSignature(CMSSignedData signedData, SignerInformation si,
        SignatureParameters parameters, Document originalData) throws IOException {

    if (this.signatureTsa == null) {
        throw new ConfigurationException(MSG.CONFIGURE_TSP_SERVER);
    }//  w  ww  .  ja v a2  s . com

    LOG.info("Extend signature with id " + si.getSID());
    AttributeTable unsigned = si.getUnsignedAttributes();
    Hashtable<ASN1ObjectIdentifier, Attribute> unsignedAttrHash = null;
    if (unsigned == null) {
        unsignedAttrHash = new Hashtable<ASN1ObjectIdentifier, Attribute>();
    } else {
        unsignedAttrHash = si.getUnsignedAttributes().toHashtable();
    }

    Attribute signatureTimeStamp = getTimeStampAttribute(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken,
            this.signatureTsa, digestAlgorithm, si.getSignature());
    unsignedAttrHash.put(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken, signatureTimeStamp);

    SignerInformation newsi = SignerInformation.replaceUnsignedAttributes(si,
            new AttributeTable(unsignedAttrHash));
    return newsi;

    // Attribute signatureTimeStamp = getTimeStampAttribute(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken,
    // this.signatureTsa, digestAlgorithm, si.getSignature());
    //
    // AttributeTable table2 = si.getUnsignedAttributes().add(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken,
    // signatureTimeStamp);
    // /* If we add a timestamp, then we must remove every reference to timestamp -X and archive timestamp */
    // table2 = table2.remove(CAdESProfileA.id_aa_ets_archiveTimestampV2);
    // table2 = table2.remove(PKCSObjectIdentifiers.id_aa_ets_escTimeStamp);
    //
    // SignerInformation newsi = SignerInformation.replaceUnsignedAttributes(si, table2);
    // return newsi;
    //
}

From source file:eu.europa.ec.markt.dss.signature.cades.CAdESProfileXL.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/* ww  w .j  a v a  2s  . c  o  m*/
protected SignerInformation extendCMSSignature(CMSSignedData signedData, SignerInformation si,
        SignatureParameters parameters, Document originalData) throws IOException {
    si = super.extendCMSSignature(signedData, si, parameters, originalData);
    Hashtable<ASN1ObjectIdentifier, ASN1Encodable> unsignedAttrs = si.getUnsignedAttributes().toHashtable();

    /* Extends unsigned attributes */
    CAdESSignature signature = new CAdESSignature(signedData, si.getSID());
    Date signingTime = signature.getSigningTime();
    if (signingTime == null) {
        signingTime = parameters.getSigningDate();
    }
    if (signingTime == null) {
        signingTime = new Date();
    }
    unsignedAttrs = extendUnsignedAttributes(unsignedAttrs, signature.getSigningCertificate(), signingTime,
            signature.getCertificateSource());

    SignerInformation newsi = SignerInformation.replaceUnsignedAttributes(si,
            new AttributeTable(unsignedAttrs));
    return newsi;
}

From source file:eu.europa.ec.markt.dss.validation.cades.CAdESSignature.java

License:Open Source License

@Override
public List<AdvancedSignature> getCounterSignatures() {

    List<AdvancedSignature> counterSigs = new ArrayList<AdvancedSignature>();
    for (Object o : this.signerInformation.getCounterSignatures().getSigners()) {
        SignerInformation i = (SignerInformation) o;

        CAdESSignature info = new CAdESSignature(this.cmsSignedData, i.getSID());
        counterSigs.add(info);//from ww  w.  j a  va 2 s.co  m
    }

    return counterSigs;
}

From source file:eu.europa.ec.markt.dss.validation.cades.CMSDocumentValidator.java

License:Open Source License

@Override
public List<AdvancedSignature> getSignatures() {

    List<AdvancedSignature> infos = new ArrayList<AdvancedSignature>();

    for (Object o : this.cmsSignedData.getSignerInfos().getSigners()) {
        SignerInformation i = (SignerInformation) o;

        CAdESSignature info = new CAdESSignature(this.cmsSignedData, i.getSID());
        infos.add(info);/*  ww  w . java2 s.  co  m*/
    }

    return infos;
}

From source file:eu.peppol.as2.MimeMessageHelperTest.java

License:EUPL

/**
 * verify the signature (assuming the cert is contained in the message)
 *//*w w  w. j  a  v a2 s.  com*/
private boolean verify(String resourceName, boolean debug) {

    System.out.println("Verifying resource " + resourceName + " (debug=" + debug + ")");
    String resourcePath = "real-mdn-examples/" + resourceName;

    try {

        // add provider
        Security.addProvider(new BouncyCastleProvider());

        // shortcuts lots of steps in the above test (parseLegalMimeMessageWithHeaders)
        MimeMultipart multipartSigned = (MimeMultipart) MimeMessageHelper
                .createMimeMessage(
                        MimeMessageHelperTest.class.getClassLoader().getResourceAsStream(resourcePath))
                .getContent();
        assertNotNull(multipartSigned);

        // verify signature

        SMIMESigned signedMessage = new SMIMESigned(multipartSigned);
        Store certs = signedMessage.getCertificates();

        SignerInformationStore signers = signedMessage.getSignerInfos();

        for (Object signerInformation : signers.getSigners()) {
            SignerInformation signer = (SignerInformation) signerInformation;
            Collection certCollection = certs.getMatches(signer.getSID());

            Iterator certIterator = certCollection.iterator();

            X509Certificate cert = new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider())
                    .getCertificate((X509CertificateHolder) certIterator.next());

            if (debug)
                System.out.println("Signing certificate : " + cert);

            SignerInformationVerifier signerInformationVerifier = new JcaSimpleSignerInfoVerifierBuilder()
                    .setProvider(new BouncyCastleProvider()).build(cert);
            if (signer.verify(signerInformationVerifier))
                return true;

        }

    } catch (Exception ex) {
        System.out.println("Verification failed with exception " + ex.getMessage());
    }

    return false;

}