Search in sources :

Example 6 with CMSProcessableByteArray

use of org.bouncycastle.cms.CMSProcessableByteArray in project nhin-d by DirectProject.

the class DefaultBundleRefreshProcessorImpl method convertRawBundleToAnchorCollection.

/**
	 * Converts a trust raw trust bundle byte array into a collection of {@link X509Certificate} objects.
	 * @param rawBundle The raw representation of the bundle.  This generally the raw byte string downloaded from the bundle's URL.
	 * @param existingBundle The configured bundle object in the DAO.  This object may contain the signing certificate
	 * used for bundle authenticity checking.
	 * @param processAttempStart The time that the update process started.
	 * @return
	 */
@SuppressWarnings("unchecked")
protected Collection<X509Certificate> convertRawBundleToAnchorCollection(byte[] rawBundle, final TrustBundle existingBundle, final Calendar processAttempStart) {
    Collection<? extends Certificate> bundleCerts = null;
    InputStream inStream = null;
    // check to see if its an unsigned PKCS7 container
    try {
        inStream = new ByteArrayInputStream(rawBundle);
        bundleCerts = CertificateFactory.getInstance("X.509").generateCertificates(inStream);
        // if its null and has no anchors, then try again as a signed bundle
        if (bundleCerts != null && bundleCerts.size() == 0)
            bundleCerts = null;
    } catch (Exception e) {
    /* no-op for now.... this may not be a p7b, so try it as a signed message*/
    } finally {
        IOUtils.closeQuietly(inStream);
    }
    // didnt work... try again as a CMS signed message
    if (bundleCerts == null) {
        try {
            final CMSSignedData signed = new CMSSignedData(rawBundle);
            // then verify the signature
            if (existingBundle.getSigningCertificateData() != null) {
                boolean sigVerified = false;
                final X509Certificate signingCert = existingBundle.toSigningCertificate();
                for (SignerInformation sigInfo : (Collection<SignerInformation>) signed.getSignerInfos().getSigners()) {
                    try {
                        if (sigInfo.verify(signingCert, CryptoExtensions.getJCEProviderName())) {
                            sigVerified = true;
                            break;
                        }
                    } catch (Exception e) {
                    /* no-op... can't verify */
                    }
                }
                if (!sigVerified) {
                    dao.updateLastUpdateError(existingBundle.getId(), processAttempStart, BundleRefreshError.UNMATCHED_SIGNATURE);
                    log.warn("Downloaded bundle signature did not match configured signing certificate.");
                    return null;
                }
            }
            final CMSProcessableByteArray signedContent = (CMSProcessableByteArray) signed.getSignedContent();
            inStream = new ByteArrayInputStream((byte[]) signedContent.getContent());
            bundleCerts = CertificateFactory.getInstance("X.509").generateCertificates(inStream);
        } catch (Exception e) {
            dao.updateLastUpdateError(existingBundle.getId(), processAttempStart, BundleRefreshError.INVALID_BUNDLE_FORMAT);
            log.warn("Failed to extract anchors from downloaded bundle at URL " + existingBundle.getBundleURL());
        } finally {
            IOUtils.closeQuietly(inStream);
        }
    }
    return (Collection<X509Certificate>) bundleCerts;
}
Also used : CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Collection(java.util.Collection) SignerInformation(org.bouncycastle.cms.SignerInformation) CMSSignedData(org.bouncycastle.cms.CMSSignedData) SocketTimeoutException(java.net.SocketTimeoutException) ConfigurationStoreException(org.nhindirect.config.store.ConfigurationStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) X509Certificate(java.security.cert.X509Certificate)

Example 7 with CMSProcessableByteArray

use of org.bouncycastle.cms.CMSProcessableByteArray in project sic by belluccifranco.

the class AfipWebServiceSOAPClient method crearCMS.

public byte[] crearCMS(byte[] p12file, String p12pass, String signer, String service, long ticketTime) {
    PrivateKey pKey = null;
    X509Certificate pCertificate = null;
    byte[] asn1_cms = null;
    CertStore cstore = null;
    try {
        KeyStore ks = KeyStore.getInstance("pkcs12");
        InputStream is;
        is = Utilidades.convertirByteArrayToInputStream(p12file);
        ks.load(is, p12pass.toCharArray());
        is.close();
        pKey = (PrivateKey) ks.getKey(signer, p12pass.toCharArray());
        pCertificate = (X509Certificate) ks.getCertificate(signer);
        ArrayList<X509Certificate> certList = new ArrayList<>();
        certList.add(pCertificate);
        if (Security.getProvider("BC") == null) {
            Security.addProvider(new BouncyCastleProvider());
        }
        cstore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC");
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException | InvalidAlgorithmParameterException | NoSuchProviderException ex) {
        LOGGER.error(ex.getMessage());
        throw new BusinessServiceException(ResourceBundle.getBundle("Mensajes").getString("mensaje_certificado_error"));
    }
    String loginTicketRequest_xml = this.crearTicketRequerimientoAcceso(service, ticketTime);
    try {
        CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
        generator.addSigner(pKey, pCertificate, CMSSignedDataGenerator.DIGEST_SHA1);
        generator.addCertificatesAndCRLs(cstore);
        CMSProcessable data = new CMSProcessableByteArray(loginTicketRequest_xml.getBytes());
        CMSSignedData signed = generator.generate(data, true, "BC");
        asn1_cms = signed.getEncoded();
    } catch (IllegalArgumentException | CertStoreException | CMSException | NoSuchAlgorithmException | NoSuchProviderException | IOException ex) {
        LOGGER.error(ex.getMessage());
        throw new BusinessServiceException(ResourceBundle.getBundle("Mensajes").getString("mensaje_firmando_certificado_error"));
    }
    return asn1_cms;
}
Also used : CMSSignedDataGenerator(org.bouncycastle.cms.CMSSignedDataGenerator) PrivateKey(java.security.PrivateKey) ArrayList(java.util.ArrayList) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CollectionCertStoreParameters(java.security.cert.CollectionCertStoreParameters) BusinessServiceException(sic.service.BusinessServiceException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) InputStream(java.io.InputStream) CertStoreException(java.security.cert.CertStoreException) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) KeyStore(java.security.KeyStore) CMSSignedData(org.bouncycastle.cms.CMSSignedData) X509Certificate(java.security.cert.X509Certificate) CMSProcessable(org.bouncycastle.cms.CMSProcessable) NoSuchProviderException(java.security.NoSuchProviderException) CertStore(java.security.cert.CertStore) CMSException(org.bouncycastle.cms.CMSException)

Example 8 with CMSProcessableByteArray

use of org.bouncycastle.cms.CMSProcessableByteArray in project athenz by yahoo.

the class Crypto method validatePKCS7Signature.

public static boolean validatePKCS7Signature(String data, String signature, PublicKey publicKey) {
    try {
        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;
}
Also used : CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) SignerInformation(org.bouncycastle.cms.SignerInformation) JcaSimpleSignerInfoVerifierBuilder(org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder) IOException(java.io.IOException) CMSSignedData(org.bouncycastle.cms.CMSSignedData) CMSProcessable(org.bouncycastle.cms.CMSProcessable) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) CMSException(org.bouncycastle.cms.CMSException) PKCSException(org.bouncycastle.pkcs.PKCSException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) SignatureException(java.security.SignatureException) FileNotFoundException(java.io.FileNotFoundException) CertificateParsingException(java.security.cert.CertificateParsingException) PEMException(org.bouncycastle.openssl.PEMException) CertificateException(java.security.cert.CertificateException) NoSuchProviderException(java.security.NoSuchProviderException) SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) ByteArrayInputStream(java.io.ByteArrayInputStream) SignerInformationVerifier(org.bouncycastle.cms.SignerInformationVerifier) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) CMSException(org.bouncycastle.cms.CMSException)

Aggregations

CMSProcessableByteArray (org.bouncycastle.cms.CMSProcessableByteArray)8 IOException (java.io.IOException)7 CMSException (org.bouncycastle.cms.CMSException)7 CMSSignedData (org.bouncycastle.cms.CMSSignedData)7 InputStream (java.io.InputStream)6 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)6 X509Certificate (java.security.cert.X509Certificate)6 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)5 ByteArrayInputStream (java.io.ByteArrayInputStream)4 NoSuchProviderException (java.security.NoSuchProviderException)4 CertificateException (java.security.cert.CertificateException)4 CMSSignedDataGenerator (org.bouncycastle.cms.CMSSignedDataGenerator)4 KeyStoreException (java.security.KeyStoreException)3 UnrecoverableKeyException (java.security.UnrecoverableKeyException)3 ArrayList (java.util.ArrayList)3 JcaCertStore (org.bouncycastle.cert.jcajce.JcaCertStore)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 File (java.io.File)2 FileInputStream (java.io.FileInputStream)2 FileOutputStream (java.io.FileOutputStream)2