Search in sources :

Example 1 with CertificateConversionException

use of org.nhindirect.config.model.exceptions.CertificateConversionException in project nhin-d by DirectProject.

the class TrustBundleResource method updateSigningCert.

/**
     * Updates the signing certificate of a trust bundle.
     * @param bundleName The name of the trust bundle to update.
     * @param certData A DER encoded representation of the new signing certificate.
     * @return Status of 204 if the trust bundle's signing certificate was updated, status of 400 if the signing certificate is
     * invalid, or a status 404 if a trust bundle with the given name does not exist.
     */
@POST
@Path("{bundle}/signingCert")
@Consumes(MediaType.APPLICATION_JSON)
public Response updateSigningCert(@PathParam("bundle") String bundleName, byte[] certData) {
    X509Certificate signingCert = null;
    if (certData.length > 0) {
        try {
            signingCert = CertUtils.toX509Certificate(certData);
        } catch (CertificateConversionException ex) {
            log.error("Signing certificate is not in a valid format " + bundleName, ex);
            return Response.status(Status.BAD_REQUEST).cacheControl(noCache).build();
        }
    }
    // make sure the bundle exists
    org.nhindirect.config.store.TrustBundle entityBundle;
    try {
        entityBundle = bundleDao.getTrustBundleByName(bundleName);
        if (entityBundle == null)
            return Response.status(Status.NOT_FOUND).cacheControl(noCache).build();
    } catch (Exception e) {
        log.error("Error looking up bundle.", e);
        return Response.serverError().cacheControl(noCache).build();
    }
    // now update
    try {
        bundleDao.updateTrustBundleSigningCertificate(entityBundle.getId(), signingCert);
        return Response.noContent().cacheControl(noCache).build();
    } catch (Exception e) {
        log.error("Error updating trust bundle signing certificate.", e);
        return Response.serverError().cacheControl(noCache).build();
    }
}
Also used : CertificateConversionException(org.nhindirect.config.model.exceptions.CertificateConversionException) X509Certificate(java.security.cert.X509Certificate) CertificateConversionException(org.nhindirect.config.model.exceptions.CertificateConversionException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 2 with CertificateConversionException

use of org.nhindirect.config.model.exceptions.CertificateConversionException in project nhin-d by DirectProject.

the class TrustBundleResource method updateBundleAttributes.

/**
     * Updates multiple bundle attributes.  If the URL of the bundle changes, then the bundle is automatically refreshed.
     * @param bundleName The name of the bundle to update.
     * @param bundleData The data of the trust bundle to update.  Empty or null attributes indicate that the attribute should not be changed.
     * @return Status of 204 if the bundle attributes were updated, status of 400 if the signing certificate is
     * invalid, or a status 404 if a trust bundle with the given name does not exist.
     */
@POST
@Path("{bundle}/bundleAttributes")
@Consumes(MediaType.APPLICATION_JSON)
public Response updateBundleAttributes(@PathParam("bundle") String bundleName, TrustBundle bundleData) {
    // make sure the bundle exists
    org.nhindirect.config.store.TrustBundle entityBundle;
    try {
        entityBundle = bundleDao.getTrustBundleByName(bundleName);
        if (entityBundle == null)
            return Response.status(Status.NOT_FOUND).cacheControl(noCache).build();
    } catch (Exception e) {
        log.error("Error looking up bundle.", e);
        return Response.serverError().cacheControl(noCache).build();
    }
    final String oldBundleURL = entityBundle.getBundleURL();
    // if there is a signing certificate in the request, make sure it's valid
    X509Certificate newSigningCert = null;
    if (bundleData.getSigningCertificateData() != null) {
        try {
            newSigningCert = CertUtils.toX509Certificate(bundleData.getSigningCertificateData());
        } catch (CertificateConversionException ex) {
            log.error("Signing certificate is not in a valid format " + bundleName, ex);
            return Response.status(Status.BAD_REQUEST).cacheControl(noCache).build();
        }
    }
    // update the bundle
    try {
        bundleDao.updateTrustBundleAttributes(entityBundle.getId(), bundleData.getBundleName(), bundleData.getBundleURL(), newSigningCert, bundleData.getRefreshInterval());
        // if the URL changed, the bundle needs to be refreshed
        if (bundleData.getBundleURL() != null && !bundleData.getBundleURL().isEmpty() && !oldBundleURL.equals(bundleData.getBundleURL())) {
            entityBundle = bundleDao.getTrustBundleById(entityBundle.getId());
            template.sendBody(entityBundle);
        }
        return Response.noContent().cacheControl(noCache).build();
    } catch (Exception e) {
        log.error("Error updating trust bundle attributes.", e);
        return Response.serverError().cacheControl(noCache).build();
    }
}
Also used : CertificateConversionException(org.nhindirect.config.model.exceptions.CertificateConversionException) CertificateConversionException(org.nhindirect.config.model.exceptions.CertificateConversionException) X509Certificate(java.security.cert.X509Certificate) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 3 with CertificateConversionException

use of org.nhindirect.config.model.exceptions.CertificateConversionException in project nhin-d by DirectProject.

the class CertificateDaoImp_saveWithProtectionMgr method testStripP12ProtectionTest_NoP12ProtectionWithManager_assertP12Returned.

@Test
public void testStripP12ProtectionTest_NoP12ProtectionWithManager_assertP12Returned() throws Exception {
    final EntityManager manager = mock(EntityManager.class);
    doAnswer(new Answer<Object>() {

        public Object answer(InvocationOnMock invocation) {
            persistedCert = (Certificate) invocation.getArguments()[0];
            return "";
        }
    }).when(manager).persist(any());
    final BootstrappedKeyStoreProtectionManager mgr = new BootstrappedKeyStoreProtectionManager();
    mgr.setKeyStoreProtectionKey("12345");
    mgr.setPrivateKeyProtectionKey("67890");
    CertificateDaoImpl daoImpl = new CertificateDaoImpl();
    daoImpl.setKeyStoreProtectionManager(mgr);
    daoImpl.setEntityManager(manager);
    daoImpl.save(populateCert("gm2552.der", "gm2552Key.der"));
    assert (persistedCert.getData() != null);
    // make sure we can't access the P12 without a passphrase
    boolean exceptionOccured = false;
    try {
        CertUtils.toCertContainer(persistedCert.getData());
    } catch (CertificateConversionException e) {
        exceptionOccured = true;
    }
    assertTrue(exceptionOccured);
}
Also used : EntityManager(javax.persistence.EntityManager) InvocationOnMock(org.mockito.invocation.InvocationOnMock) CertificateConversionException(org.nhindirect.config.model.exceptions.CertificateConversionException) CertificateDaoImpl(org.nhindirect.config.store.dao.impl.CertificateDaoImpl) BootstrappedKeyStoreProtectionManager(org.nhindirect.common.crypto.impl.BootstrappedKeyStoreProtectionManager) Test(org.junit.Test)

Example 4 with CertificateConversionException

use of org.nhindirect.config.model.exceptions.CertificateConversionException in project nhin-d by DirectProject.

the class CertRecordPrinter method getColumnValue.

@SuppressWarnings("unused")
@Override
protected String getColumnValue(ReportColumn column, org.nhind.config.Certificate retCert) {
    String tpOrURL = null;
    boolean isURL = false;
    org.nhindirect.config.model.utils.CertUtils.CertContainer cont = null;
    try {
        cont = org.nhindirect.config.model.utils.CertUtils.toCertContainer(retCert.getData());
        tpOrURL = Thumbprint.toThumbprint(cont.getCert()).toString();
    } catch (CertificateConversionException e) {
    }
    if (tpOrURL == null) {
        try {
            tpOrURL = new String(retCert.getData());
            URL url = new URL(tpOrURL);
            isURL = true;
        } catch (Exception e) {
            // invalid URL
            return "";
        }
    }
    try {
        if (column.header.equals(CERT_NAME_COL))
            return retCert.getOwner();
        else if (column.header.equals(RECORD_TYPE_COL))
            return (isURL) ? "IPKIX" : "PKIX";
        else if (column.header.equals(TP_NAME_COL))
            return isURL ? tpOrURL : Thumbprint.toThumbprint(cont.getCert()).toString();
        else if (column.header.equals(EXPIRES_COL))
            return isURL ? "" : dateFormatter.format(cont.getCert().getNotAfter());
        else if (column.header.equals(PRIVATE_IND_COL))
            return retCert.isPrivateKey() ? "Y" : "N";
        else
            return super.getColumnValue(column, retCert);
    } catch (Exception e) {
        return "ERROR: " + e.getMessage();
    }
}
Also used : CertificateConversionException(org.nhindirect.config.model.exceptions.CertificateConversionException) URL(java.net.URL) CertificateConversionException(org.nhindirect.config.model.exceptions.CertificateConversionException)

Example 5 with CertificateConversionException

use of org.nhindirect.config.model.exceptions.CertificateConversionException in project nhin-d by DirectProject.

the class CertUtils method toX509Certificate.

/**
	 * Converts a byte stream to an X509Certificate.  The byte stream can either be an encoded X509Certificate or a PKCS12 byte stream.  
	 * <p>
	 * If the stream is a PKCS12 representation, then the pass phrase is used to decrypt the stream.  In addition the resulting X509Certificate
	 * implementation will contain the private key.
	 * @param data The byte stream representation to convert.
	 * @param passPhrase  If the byte stream is a PKCS12 representation, then the then the pass phrase is used to decrypt the stream.  Can be
	 * null if the stream is an encoded X509Certificate and not a PKCS12 byte stream.
	 * @return  An X509Certificate representation of the byte stream.
	 */
public static X509Certificate toX509Certificate(byte[] data, String passPhrase) {
    if (data == null || data.length == 0)
        throw new IllegalArgumentException("Byte stream cannot be null or empty.");
    // do not use a null pass phrase
    if (passPhrase == null)
        passPhrase = "";
    if (isByteDataWrappedKeyPair(data)) {
        final CertContainer cont = CertUtils.toCertContainer(data, null, null);
        return cont.getCert();
    }
    X509Certificate retVal = null;
    ByteArrayInputStream bais = new ByteArrayInputStream(data);
    try {
        // lets try this a as a PKCS12 data stream first
        try {
            KeyStore localKeyStore = KeyStore.getInstance("PKCS12", getJCEProviderName());
            localKeyStore.load(bais, passPhrase.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, passPhrase.toCharArray());
                if (key != null && key instanceof PrivateKey) {
                    retVal = cert;
                }
            }
        } catch (Exception e) {
        // must not be a PKCS12 stream, try next step
        }
        if (retVal == null) {
            //try X509 certificate factory next       
            bais.reset();
            bais = new ByteArrayInputStream(data);
            retVal = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(bais);
        }
    } catch (Exception e) {
        throw new CertificateConversionException("Failed to convert byte stream to a certificate.", e);
    } finally {
        try {
            bais.close();
        } catch (IOException ex) {
        }
    }
    return retVal;
}
Also used : PrivateKey(java.security.PrivateKey) ByteArrayInputStream(java.io.ByteArrayInputStream) CertificateConversionException(org.nhindirect.config.model.exceptions.CertificateConversionException) IOException(java.io.IOException) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) Key(java.security.Key) PrivateKey(java.security.PrivateKey) CertificateConversionException(org.nhindirect.config.model.exceptions.CertificateConversionException) CertificateParsingException(java.security.cert.CertificateParsingException) IOException(java.io.IOException)

Aggregations

CertificateConversionException (org.nhindirect.config.model.exceptions.CertificateConversionException)10 X509Certificate (java.security.cert.X509Certificate)6 IOException (java.io.IOException)4 CertificateParsingException (java.security.cert.CertificateParsingException)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 Key (java.security.Key)3 KeyStore (java.security.KeyStore)3 PrivateKey (java.security.PrivateKey)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 URL (java.net.URL)2 Consumes (javax.ws.rs.Consumes)2 POST (javax.ws.rs.POST)2 Path (javax.ws.rs.Path)2 RSAKey (java.security.interfaces.RSAKey)1 ArrayList (java.util.ArrayList)1 EntityManager (javax.persistence.EntityManager)1 Test (org.junit.Test)1 InvocationOnMock (org.mockito.invocation.InvocationOnMock)1 Certificate (org.nhind.config.Certificate)1 BootstrappedKeyStoreProtectionManager (org.nhindirect.common.crypto.impl.BootstrappedKeyStoreProtectionManager)1