Search in sources :

Example 6 with CertContainer

use of org.nhindirect.config.model.utils.CertUtils.CertContainer 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 7 with CertContainer

use of org.nhindirect.config.model.utils.CertUtils.CertContainer in project nhin-d by DirectProject.

the class ConfigServiceRESTCertificateStore method certFromData.

private X509Certificate certFromData(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 (this.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();
    } 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) 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) CacheException(org.apache.jcs.access.exception.CacheException) NHINDException(org.nhindirect.stagent.NHINDException)

Example 8 with CertContainer

use of org.nhindirect.config.model.utils.CertUtils.CertContainer in project nhin-d by DirectProject.

the class CertUtils_certAndWrappedKeyToRawByteFormatTest method testWrapToRawBytes_assertConverted.

@Test
public void testWrapToRawBytes_assertConverted() throws Exception {
    final byte[] key = FileUtils.readFileToByteArray(new File("./src/test/resources/certs/gm2552Key.der"));
    final X509Certificate cert = CertUtils.toX509Certificate(FileUtils.readFileToByteArray(new File("./src/test/resources/certs/gm2552.der")));
    byte[] rawBytes = CertUtils.certAndWrappedKeyToRawByteFormat(key, cert);
    assertNotNull(rawBytes);
    // convert back;
    final CertContainer container = CertUtils.toCertContainer(rawBytes);
    assertEquals(cert, container.getCert());
    assertTrue(Arrays.equals(key, container.getWrappedKeyData()));
    assertNull(container.getKey());
}
Also used : File(java.io.File) X509Certificate(java.security.cert.X509Certificate) CertContainer(org.nhindirect.config.model.utils.CertUtils.CertContainer) Test(org.junit.Test)

Example 9 with CertContainer

use of org.nhindirect.config.model.utils.CertUtils.CertContainer in project nhin-d by DirectProject.

the class CertificateResource method addCertificate.

/**
     * Adds a certificate to the system.
     * @param uriInfo Injected URI context used for building the location URI.
     * @param cert The certificate to add.
     * @return Returns a status of 201 if the certificate was added or a status of 409 if the certificate already exists.
     */
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public Response addCertificate(@Context UriInfo uriInfo, Certificate cert) {
    // check to see if it already exists
    CertContainer cont = null;
    try {
        cont = CertUtils.toCertContainer(cert.getData());
        if (certDao.load(cert.getOwner(), Thumbprint.toThumbprint(cont.getCert()).toString()) != null)
            return Response.status(Status.CONFLICT).cacheControl(noCache).build();
    } catch (Exception e) {
        log.error("Error looking up certificate.", e);
        return Response.serverError().cacheControl(noCache).build();
    }
    try {
        // get the owner if it doesn't alreay exists
        if ((cert.getOwner() == null || cert.getOwner().isEmpty())) {
            if (cont != null && cont.getCert() != null) {
                // now get the owner info from the cert
                final String theOwner = CertUtils.getOwner(cont.getCert());
                if (theOwner != null && !theOwner.isEmpty())
                    cert.setOwner(theOwner);
            }
        }
        final org.nhindirect.config.store.Certificate entCert = EntityModelConversion.toEntityCertificate(cert);
        certDao.save(entCert);
        final UriBuilder newLocBuilder = uriInfo.getBaseUriBuilder();
        final URI newLoc = newLocBuilder.path("certificate/" + entCert.getOwner() + "/" + entCert.getThumbprint()).build();
        return Response.created(newLoc).cacheControl(noCache).build();
    } catch (Exception e) {
        log.error("Error adding certificate.", e);
        return Response.serverError().cacheControl(noCache).build();
    }
}
Also used : UriBuilder(javax.ws.rs.core.UriBuilder) URI(java.net.URI) CertContainer(org.nhindirect.config.model.utils.CertUtils.CertContainer) Consumes(javax.ws.rs.Consumes) PUT(javax.ws.rs.PUT)

Aggregations

CertContainer (org.nhindirect.config.model.utils.CertUtils.CertContainer)9 X509Certificate (java.security.cert.X509Certificate)5 Key (java.security.Key)4 KeyStore (java.security.KeyStore)4 PrivateKey (java.security.PrivateKey)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 NHINDException (org.nhindirect.stagent.NHINDException)3 File (java.io.File)2 IOException (java.io.IOException)2 CacheException (org.apache.jcs.access.exception.CacheException)2 Test (org.junit.Test)2 MutableKeyStoreProtectionManager (org.nhindirect.common.crypto.MutableKeyStoreProtectionManager)2 ServiceException (org.nhindirect.common.rest.exceptions.ServiceException)2 Certificate (org.nhindirect.config.model.Certificate)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 URI (java.net.URI)1 KeyFactory (java.security.KeyFactory)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)1 ArrayList (java.util.ArrayList)1