Example usage for org.bouncycastle.cms CMSException CMSException

List of usage examples for org.bouncycastle.cms CMSException CMSException

Introduction

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

Prototype

public CMSException(String msg) 

Source Link

Usage

From source file:com.yahoo.athenz.auth.util.CryptoExceptionTest.java

License:Apache License

@Test
public void testCryptoExceptions() {

    CryptoException ex = new CryptoException();
    assertNotNull(ex);/*from w ww. j  av  a 2s  .c om*/
    assertNotNull(new CryptoException(new NoSuchAlgorithmException()));
    assertNotNull(new CryptoException(new InvalidKeyException()));
    assertNotNull(new CryptoException(new NoSuchProviderException()));
    assertNotNull(new CryptoException(new SignatureException()));
    assertNotNull(new CryptoException(new FileNotFoundException()));
    assertNotNull(new CryptoException(new IOException()));
    assertNotNull(new CryptoException(new CertificateException()));
    assertNotNull(new CryptoException(new InvalidKeySpecException()));
    assertNotNull(new CryptoException(new OperatorCreationException("unit-test")));
    assertNotNull(new CryptoException(new PKCSException("unit-test")));
    assertNotNull(new CryptoException(new CMSException("unit-test")));
}

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./*from   w ww .ja  v  a2 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  . j a v a  2s .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 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:org.votingsystem.signature.util.CMSUtils.java

License:Open Source License

public static DERObject getSingleValuedSignedAttribute(AttributeTable signedAttrTable,
        DERObjectIdentifier attrOID, String printableName) throws CMSException {
    if (signedAttrTable == null)
        return null;
    ASN1EncodableVector vector = signedAttrTable.getAll(attrOID);
    switch (vector.size()) {
    case 0:/*from   w ww  .  jav a2s .c  o  m*/
        return null;
    case 1:
        Attribute t = (Attribute) vector.get(0);
        ASN1Set attrValues = t.getAttrValues();
        if (attrValues.size() != 1)
            throw new CMSException("A " + printableName + " attribute MUST have a single attribute value");
        return attrValues.getObjectAt(0).getDERObject();
    default:
        throw new CMSException(
                "The SignedAttributes in a signerInfo MUST NOT include multiple instances of the "
                        + printableName + " attribute");
    }
}

From source file:org.xipki.pki.ca.server.impl.scep.CaCertRespBytes.java

License:Open Source License

CaCertRespBytes(final X509Certificate caCert, final X509Certificate responderCert)
        throws CMSException, CertificateException {
    ParamUtil.requireNonNull("caCert", caCert);
    ParamUtil.requireNonNull("responderCert", responderCert);

    CMSSignedDataGenerator cmsSignedDataGen = new CMSSignedDataGenerator();
    try {/*  w  w  w  . j av  a  2s  . c o  m*/
        cmsSignedDataGen.addCertificate(new X509CertificateHolder(caCert.getEncoded()));
        cmsSignedDataGen.addCertificate(new X509CertificateHolder(responderCert.getEncoded()));
        CMSSignedData degenerateSignedData = cmsSignedDataGen.generate(new CMSAbsentContent());
        bytes = degenerateSignedData.getEncoded();
    } catch (IOException ex) {
        throw new CMSException("could not build CMS SignedDta");
    }
}

From source file:org.xipki.pki.ca.server.impl.scep.Scep.java

License:Open Source License

static CMSSignedData createDegeneratedSigendData(final X509Certificate... certs)
        throws CMSException, CertificateException {
    CMSSignedDataGenerator cmsSignedDataGen = new CMSSignedDataGenerator();
    try {//w  w  w  .  j  a  va  2 s  . c  o  m
        for (X509Certificate cert : certs) {
            cmsSignedDataGen.addCertificate(new X509CertificateHolder(cert.getEncoded()));
        }
        return cmsSignedDataGen.generate(new CMSAbsentContent());
    } catch (IOException ex) {
        throw new CMSException("could not build CMS SignedDta");
    }
}

From source file:org.xwiki.crypto.signer.internal.cms.BcCMSUtils.java

License:Open Source License

/**
 * Verify a CMS signature.//from  ww  w  . j a v a  2s.c o  m
 *
 * @param signer the signer to verify.
 * @param certKey the certified public key of the signer.
 * @param contentVerifierProviderBuilder a builder of content provider.
 * @param digestProvider a digest provider.
 * @return true if the signature is verified and the certificate was valid at the time of signature.
 * @throws CMSException if the verifier is unable to create appropriate ContentVerifiers or DigestCalculators.
 */
public static boolean verify(SignerInformation signer, CertifiedPublicKey certKey,
        BcContentVerifierProviderBuilder contentVerifierProviderBuilder, DigestFactory digestProvider)
        throws CMSException {
    if (certKey == null) {
        throw new CMSException("No certified key for proceeding to signature validation.");
    }

    return signer.verify(new SignerInformationVerifier(new DefaultCMSSignatureAlgorithmNameGenerator(),
            new DefaultSignatureAlgorithmIdentifierFinder(), contentVerifierProviderBuilder.build(certKey),
            (DigestCalculatorProvider) digestProvider));
}