Search in sources :

Example 21 with NHINDException

use of org.nhindirect.stagent.NHINDException in project nhin-d by DirectProject.

the class CertStoreUtils method certFromData.

public static X509Certificate certFromData(KeyStoreProtectionManager mgr, byte[] data) {
    X509Certificate retVal = null;
    try {
        // first check for wrapped data
        final CertContainer container = CertUtils.toCertContainer(data);
        if (container.getWrappedKeyData() != null) {
            // make sure we have a KeyStoreManager configured
            if (mgr == null) {
                throw new NHINDException(AgentError.Unexpected, "Resolved certifiate has wrapped data, but resolver has not been configured to unwrap it.");
            }
            // create a new wrapped certificate object
            retVal = WrappedOnDemandX509CertificateEx.fromX509Certificate(mgr, container.getCert(), container.getWrappedKeyData());
            return retVal;
        }
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        // lets try this a as a PKCS12 data stream first
        try {
            KeyStore localKeyStore = KeyStore.getInstance("PKCS12", CryptoExtensions.getJCEProviderName());
            localKeyStore.load(bais, "".toCharArray());
            Enumeration<String> aliases = localKeyStore.aliases();
            // we are really expecting only one alias 
            if (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                X509Certificate cert = (X509Certificate) localKeyStore.getCertificate(alias);
                // check if there is private key
                Key key = localKeyStore.getKey(alias, "".toCharArray());
                if (key != null && key instanceof PrivateKey) {
                    retVal = X509CertificateEx.fromX509Certificate(cert, (PrivateKey) key);
                } else
                    retVal = cert;
            }
        } catch (Exception e) {
        // must not be a PKCS12 stream, go on to next step
        }
        if (retVal == null) {
            //try X509 certificate factory next       
            bais.reset();
            bais = new ByteArrayInputStream(data);
            retVal = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(bais);
        }
        bais.close();
        // look in the keystore manager to check if they private key is store in the token
        if (mgr != null && !(retVal instanceof X509CertificateEx)) {
            // make sure this a mutable manager
            if (mgr instanceof MutableKeyStoreProtectionManager) {
                try {
                    final KeyStore ks = ((MutableKeyStoreProtectionManager) mgr).getKS();
                    // check to see if this certificate exists in the key store
                    final String alias = ks.getCertificateAlias(retVal);
                    if (!StringUtils.isEmpty(alias)) {
                        // get the private key if it exits
                        final PrivateKey pKey = (PrivateKey) ks.getKey(alias, "".toCharArray());
                        if (pKey != null)
                            retVal = X509CertificateEx.fromX509Certificate(retVal, pKey);
                    }
                } catch (Exception e) {
                    LOGGER.warn("Could not retrieve the private key from the PKCS11 token: " + e.getMessage(), e);
                }
            }
        }
    } catch (Exception e) {
        throw new NHINDException("Data cannot be converted to a valid X.509 Certificate", e);
    }
    return retVal;
}
Also used : PrivateKey(java.security.PrivateKey) ByteArrayInputStream(java.io.ByteArrayInputStream) WrappedOnDemandX509CertificateEx(org.nhindirect.stagent.cert.WrappedOnDemandX509CertificateEx) X509CertificateEx(org.nhindirect.stagent.cert.X509CertificateEx) MutableKeyStoreProtectionManager(org.nhindirect.common.crypto.MutableKeyStoreProtectionManager) NHINDException(org.nhindirect.stagent.NHINDException) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) CertContainer(org.nhindirect.config.model.utils.CertUtils.CertContainer) Key(java.security.Key) PrivateKey(java.security.PrivateKey) NHINDException(org.nhindirect.stagent.NHINDException)

Example 22 with NHINDException

use of org.nhindirect.stagent.NHINDException in project nhin-d by DirectProject.

the class ConfigServiceCertificateStore method getAllCertificates.

/**
	 * {@inheritDoc}
	 */
@Override
public Collection<X509Certificate> getAllCertificates() {
    // get everything from the configuration service.... no caching here
    org.nhind.config.Certificate[] certificates;
    try {
        // hard code to get everything
        certificates = proxy.listCertificates(0L, 0x8FFF, null);
    } catch (Exception e) {
        throw new NHINDException("WebService error getting all certificates: " + e.getMessage(), e);
    }
    // purge everything
    this.flush(true);
    if (certificates == null || certificates.length == 0)
        return Collections.emptyList();
    // convert to X509Certificates and store
    Collection<X509Certificate> retVal = new ArrayList<X509Certificate>();
    for (org.nhind.config.Certificate cert : certificates) {
        X509Certificate storeCert = CertStoreUtils.certFromData(mgr, cert.getData());
        retVal.add(storeCert);
        // add to JCS and cache
        try {
            if (cache != null)
                cache.put(cert.getOwner(), retVal);
        } catch (CacheException e) {
        /*
					 * TODO: handle exception
					 */
        }
        if (localStoreDelegate != null) {
            if (localStoreDelegate.contains(storeCert))
                localStoreDelegate.update(storeCert);
            else
                localStoreDelegate.add(storeCert);
        }
    }
    return retVal;
}
Also used : CacheException(org.apache.jcs.access.exception.CacheException) ArrayList(java.util.ArrayList) NHINDException(org.nhindirect.stagent.NHINDException) CacheException(org.apache.jcs.access.exception.CacheException) NHINDException(org.nhindirect.stagent.NHINDException) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate)

Example 23 with NHINDException

use of org.nhindirect.stagent.NHINDException in project nhin-d by DirectProject.

the class ConfigServiceRESTCertificateStore method getAllCertificates.

/**
	 * {@inheritDoc}
	 */
@Override
public Collection<X509Certificate> getAllCertificates() {
    // get everything from the configuration service.... no caching here
    Collection<org.nhindirect.config.model.Certificate> certificates;
    try {
        certificates = certService.getAllCertificates();
    } catch (Exception e) {
        throw new NHINDException("WebService error getting all certificates: " + e.getMessage(), e);
    }
    // purge everything
    this.flush(true);
    if (certificates == null || certificates.isEmpty())
        return Collections.emptyList();
    // convert to X509Certificates and store
    Collection<X509Certificate> retVal = new ArrayList<X509Certificate>();
    for (org.nhindirect.config.model.Certificate cert : certificates) {
        X509Certificate storeCert = CertStoreUtils.certFromData(mgr, cert.getData());
        retVal.add(storeCert);
        // add to JCS and cache
        try {
            if (cache != null)
                cache.put(cert.getOwner(), retVal);
        } catch (CacheException e) {
        /*
					 * TODO: handle exception
					 */
        }
    }
    return retVal;
}
Also used : CacheException(org.apache.jcs.access.exception.CacheException) ArrayList(java.util.ArrayList) NHINDException(org.nhindirect.stagent.NHINDException) CacheException(org.apache.jcs.access.exception.CacheException) NHINDException(org.nhindirect.stagent.NHINDException) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate)

Example 24 with NHINDException

use of org.nhindirect.stagent.NHINDException in project nhin-d by DirectProject.

the class SMIMECryptographerImpl method createSignatureEntity.

protected MimeMultipart createSignatureEntity(byte[] entity, Collection<X509Certificate> signingCertificates) {
    MimeMultipart retVal = null;
    try {
        final MimeBodyPart signedContent = new MimeBodyPart(new ByteArrayInputStream(entity));
        final ASN1EncodableVector signedAttrs = new ASN1EncodableVector();
        final SMIMECapabilityVector caps = new SMIMECapabilityVector();
        caps.addCapability(SMIMECapability.dES_EDE3_CBC);
        caps.addCapability(SMIMECapability.rC2_CBC, 128);
        caps.addCapability(SMIMECapability.dES_CBC);
        caps.addCapability(new DERObjectIdentifier("1.2.840.113549.1.7.1"));
        caps.addCapability(x509CertificateObjectsIdent);
        signedAttrs.add(new SMIMECapabilitiesAttribute(caps));
        final List<X509Certificate> certList = new ArrayList<X509Certificate>();
        final DirectSignedDataGenerator generator = sigFactory.createInstance();
        for (X509Certificate signer : signingCertificates) {
            if (signer instanceof X509CertificateEx) {
                generator.addSigner(((X509CertificateEx) signer).getPrivateKey(), signer, this.m_digestAlgorithm.getOID(), createAttributeTable(signedAttrs), null);
                certList.add(signer);
            }
        }
        final CertStore certsAndcrls = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), CryptoExtensions.getJCEProviderNameForTypeAndAlgorithm("CertStore", "Collection"));
        generator.addCertificatesAndCRLs(certsAndcrls);
        final CMSProcessableBodyPart content = new CMSProcessableBodyPart(signedContent);
        final CMSSignedData signedData = generator.generate(content);
        final String header = "signed; protocol=\"application/pkcs7-signature\"; micalg=" + CryptoAlgorithmsHelper.toDigestAlgorithmMicalg(this.m_digestAlgorithm);
        //String encodedSig = Base64.encodeBase64String(signedData.getEncoded());
        final String encodedSig = StringUtils.newStringUtf8(Base64.encodeBase64(signedData.getEncoded(), true));
        retVal = new MimeMultipart(header.toString());
        final MimeBodyPart sig = new MimeBodyPart(new InternetHeaders(), encodedSig.getBytes("ASCII"));
        sig.addHeader("Content-Type", "application/pkcs7-signature; name=smime.p7s; smime-type=signed-data");
        sig.addHeader("Content-Disposition", "attachment; filename=\"smime.p7s\"");
        sig.addHeader("Content-Description", "S/MIME Cryptographic Signature");
        sig.addHeader("Content-Transfer-Encoding", "base64");
        retVal.addBodyPart(signedContent);
        retVal.addBodyPart(sig);
    } catch (MessagingException e) {
        throw new MimeException(MimeError.InvalidMimeEntity, e);
    } catch (IOException e) {
        throw new SignatureException(SignatureError.InvalidMultipartSigned, e);
    } catch (Exception e) {
        throw new NHINDException(MimeError.Unexpected, e);
    }
    return retVal;
}
Also used : InternetHeaders(javax.mail.internet.InternetHeaders) MessagingException(javax.mail.MessagingException) ArrayList(java.util.ArrayList) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) IOException(java.io.IOException) DERObjectIdentifier(org.bouncycastle.asn1.DERObjectIdentifier) CMSSignedData(org.bouncycastle.cms.CMSSignedData) NHINDException(org.nhindirect.stagent.NHINDException) X509Certificate(java.security.cert.X509Certificate) MessagingException(javax.mail.MessagingException) MimeException(org.nhindirect.stagent.mail.MimeException) NHINDException(org.nhindirect.stagent.NHINDException) ParseException(javax.mail.internet.ParseException) IOException(java.io.IOException) SignatureValidationException(org.nhindirect.stagent.SignatureValidationException) CMSProcessableBodyPart(org.bouncycastle.mail.smime.CMSProcessableBodyPart) CollectionCertStoreParameters(java.security.cert.CollectionCertStoreParameters) MimeMultipart(javax.mail.internet.MimeMultipart) ByteArrayInputStream(java.io.ByteArrayInputStream) SMIMECapabilityVector(org.bouncycastle.asn1.smime.SMIMECapabilityVector) X509CertificateEx(org.nhindirect.stagent.cert.X509CertificateEx) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) MimeException(org.nhindirect.stagent.mail.MimeException) MimeBodyPart(javax.mail.internet.MimeBodyPart) DirectSignedDataGenerator(org.nhindirect.stagent.cryptography.activekeyops.DirectSignedDataGenerator) SMIMECapabilitiesAttribute(org.bouncycastle.asn1.smime.SMIMECapabilitiesAttribute) CertStore(java.security.cert.CertStore)

Example 25 with NHINDException

use of org.nhindirect.stagent.NHINDException in project nhin-d by DirectProject.

the class TrustChainValidator method downloadCertsFromAIA.

/**
	 * Downloads certificates from the AIA URL and returns the result as a collection of certificates.
	 * @param url The URL listed in the AIA extension to locate the certificates.
	 * @return The certificates downloaded from the AIA extension URL
	 */
@SuppressWarnings("unchecked")
protected Collection<X509Certificate> downloadCertsFromAIA(String url) throws NHINDException {
    InputStream inputStream = null;
    Collection<? extends Certificate> retVal = null;
    try {
        // in this case the cert is a binary representation
        // of the CERT URL... transform to a string
        final URL certURL = new URL(url);
        final URLConnection connection = certURL.openConnection();
        // the connection is not actually made until the input stream
        // is open, so set the timeouts before getting the stream
        connection.setConnectTimeout(DEFAULT_URL_CONNECTION_TIMEOUT);
        connection.setReadTimeout(DEFAULT_URL_READ_TIMEOUT);
        // open the URL as in input stream
        inputStream = connection.getInputStream();
        // download the 
        retVal = CertificateFactory.getInstance("X.509").generateCertificates(inputStream);
    } catch (Exception e) {
        throw new NHINDException("Failed to download certificates from AIA extension.", e);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
    return (Collection<X509Certificate>) retVal;
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) InputStream(java.io.InputStream) Collection(java.util.Collection) NHINDException(org.nhindirect.stagent.NHINDException) URL(java.net.URL) URLConnection(java.net.URLConnection) CertificateParsingException(java.security.cert.CertificateParsingException) AddressException(javax.mail.internet.AddressException) PolicyProcessException(org.nhindirect.policy.PolicyProcessException) NHINDException(org.nhindirect.stagent.NHINDException)

Aggregations

NHINDException (org.nhindirect.stagent.NHINDException)45 X509Certificate (java.security.cert.X509Certificate)30 ArrayList (java.util.ArrayList)14 ByteArrayInputStream (java.io.ByteArrayInputStream)13 IOException (java.io.IOException)11 Key (java.security.Key)10 PrivateKey (java.security.PrivateKey)10 KeyStore (java.security.KeyStore)9 CacheException (org.apache.jcs.access.exception.CacheException)7 X509CertificateEx (org.nhindirect.stagent.cert.X509CertificateEx)7 MessagingException (javax.mail.MessagingException)6 Collection (java.util.Collection)4 UnknownHostException (java.net.UnknownHostException)3 PrivateKeyEntry (java.security.KeyStore.PrivateKeyEntry)3 Certificate (java.security.cert.Certificate)3 InternetHeaders (javax.mail.internet.InternetHeaders)3 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)3 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)3 MutableKeyStoreProtectionManager (org.nhindirect.common.crypto.MutableKeyStoreProtectionManager)3 File (java.io.File)2