Search in sources :

Example 26 with X509CertificateEx

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

the class SplitDirectRecipientInformation_getDecryptedContentTest method testGetDecryptedContent_safeNetHSMKeyEncProvider_assertDecrypted.

public void testGetDecryptedContent_safeNetHSMKeyEncProvider_assertDecrypted() throws Exception {
    /**
         * This test is only run if a specific SafeNet eToken Pro HSM is connected to the testing 
         * system.  This can be modified for another specific machine and/or token.
         */
    pkcs11ProvName = TestUtils.setupSafeNetToken();
    if (!StringUtils.isEmpty(pkcs11ProvName)) {
        final PKCS11Credential cred = new BootstrappedPKCS11Credential("1Kingpuff");
        final MutableKeyStoreProtectionManager mgr = new StaticPKCS11TokenKeyStoreProtectionManager(cred, "", "");
        final CacheableKeyStoreManagerCertificateStore store = new CacheableKeyStoreManagerCertificateStore(mgr);
        store.add(TestUtils.getInternalCert("user1"));
        // get a certificate from the key store
        final KeyStore ks = KeyStore.getInstance("PKCS11");
        ks.load(null, "1Kingpuff".toCharArray());
        // get the decryption cert
        X509CertificateEx decryptCert = null;
        final Enumeration<String> aliases = ks.aliases();
        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            Certificate pkcs11Cert = ks.getCertificate(alias);
            if (pkcs11Cert != null && pkcs11Cert instanceof X509Certificate) {
                // check if there is private key
                Key key = ks.getKey(alias, null);
                if (key != null && key instanceof PrivateKey && CryptoExtensions.certSubjectContainsName((X509Certificate) pkcs11Cert, "user1@cerner.com")) {
                    decryptCert = X509CertificateEx.fromX509Certificate((X509Certificate) pkcs11Cert, (PrivateKey) key);
                    break;
                }
            }
        }
        final SMIMEEnveloped env = createSMIMEEnv();
        final RecipientInformation recipient = (RecipientInformation) env.getRecipientInfos().getRecipients().iterator().next();
        final SplitDirectRecipientInformationFactory factory = new SplitDirectRecipientInformationFactory(pkcs11ProvName, "BC");
        final SplitDirectRecipientInformation recInfo = (SplitDirectRecipientInformation) factory.createInstance(recipient, env);
        // this will be non-null if it works correctly
        assertNotNull(recInfo.getDecryptedContent(decryptCert.getPrivateKey()));
    }
}
Also used : PKCS11Credential(org.nhindirect.common.crypto.PKCS11Credential) BootstrappedPKCS11Credential(org.nhindirect.common.crypto.impl.BootstrappedPKCS11Credential) PrivateKey(java.security.PrivateKey) KeyStore(java.security.KeyStore) SMIMEEnveloped(org.bouncycastle.mail.smime.SMIMEEnveloped) X509Certificate(java.security.cert.X509Certificate) CacheableKeyStoreManagerCertificateStore(org.nhindirect.stagent.cert.impl.CacheableKeyStoreManagerCertificateStore) RecipientInformation(org.bouncycastle.cms.RecipientInformation) X509CertificateEx(org.nhindirect.stagent.cert.X509CertificateEx) MutableKeyStoreProtectionManager(org.nhindirect.common.crypto.MutableKeyStoreProtectionManager) StaticPKCS11TokenKeyStoreProtectionManager(org.nhindirect.common.crypto.impl.StaticPKCS11TokenKeyStoreProtectionManager) BootstrappedPKCS11Credential(org.nhindirect.common.crypto.impl.BootstrappedPKCS11Credential) Key(java.security.Key) PrivateKey(java.security.PrivateKey) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 27 with X509CertificateEx

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

the class ConfigServiceRESTCertificateStore_getCertificateWithHSMKeyTest method testGetCertifcateWithPrivKey_noPrivKeyInHSM.

public void testGetCertifcateWithPrivKey_noPrivKeyInHSM() throws Exception {
    if (certService == null)
        return;
    final X509Certificate cert = TestUtils.loadCertificate("digSigOnly.der", null);
    final Certificate modelCert = new Certificate();
    modelCert.setData(cert.getEncoded());
    final Collection<Certificate> certsReturned = new ArrayList<Certificate>();
    certsReturned.add(modelCert);
    when(proxy.getCertificatesByOwner((String) any())).thenReturn(certsReturned);
    final Collection<X509Certificate> retCerts = certService.getCertificates("test.com");
    assertEquals(1, retCerts.size());
    final X509Certificate retCert = retCerts.iterator().next();
    assertTrue(retCert instanceof X509CertificateEx);
    assertTrue(((X509CertificateEx) retCert).hasPrivateKey());
}
Also used : X509CertificateEx(org.nhindirect.stagent.cert.X509CertificateEx) ArrayList(java.util.ArrayList) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(org.nhindirect.config.model.Certificate)

Example 28 with X509CertificateEx

use of org.nhindirect.stagent.cert.X509CertificateEx 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 29 with X509CertificateEx

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

the class CertUtils method x509CertificateToBytes.

/**
	 * Converts an X509Certificate to a byte stream representation.  If the certificate contains a private key, the returned representation
	 * is a PKCS12 byte stream with no pass phrase protection or encryption.
	 * @param cert The certificate to convert.
	 * @return A byte stream representation of the certificate.
	 */
public static byte[] x509CertificateToBytes(X509Certificate cert) throws DNSException {
    if (cert instanceof X509CertificateEx) {
        final ByteArrayOutputStream outStr = new ByteArrayOutputStream();
        try {
            // return as a pkcs12 file with no encryption
            final KeyStore convertKeyStore = KeyStore.getInstance("PKCS12", CryptoExtensions.getJCEProviderName());
            convertKeyStore.load(null, null);
            final char[] emptyPass = "".toCharArray();
            convertKeyStore.setKeyEntry("privCert", ((X509CertificateEx) cert).getPrivateKey(), emptyPass, new java.security.cert.Certificate[] { cert });
            convertKeyStore.store(outStr, emptyPass);
            return outStr.toByteArray();
        }///CLOVER:OFF
         catch (Exception e) {
            throw new DNSException("Failed to convert certificate to a byte stream.");
        } finally ///CLOVER:ON
        {
            try {
                outStr.close();
            } catch (Exception e) {
            /* no-op */
            }
        }
    } else {
        try {
            return cert.getEncoded();
        }///CLOVER:OFF
         catch (Exception e) {
            throw new DNSException("Failed to convert certificate to a byte stream.");
        }
    ///CLOVER:ON
    }
}
Also used : X509CertificateEx(org.nhindirect.stagent.cert.X509CertificateEx) DNSException(org.nhindirect.dns.DNSException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) KeyStore(java.security.KeyStore) IOException(java.io.IOException) DNSException(org.nhindirect.dns.DNSException)

Example 30 with X509CertificateEx

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

the class ConfigServiceWSCertificateStore_getCertificateWithHSMKeyTest method testGetCertifcateWithPrivKey_noPrivKeyInHSM.

public void testGetCertifcateWithPrivKey_noPrivKeyInHSM() throws Exception {
    if (certService == null)
        return;
    final X509Certificate cert = TestUtils.loadCertificate("digSigOnly.der", null);
    final org.nhind.config.Certificate modelCert = new org.nhind.config.Certificate();
    modelCert.setData(cert.getEncoded());
    when(proxy.getCertificatesForOwner((String) any(), (CertificateGetOptions) any())).thenReturn(new org.nhind.config.Certificate[] { modelCert });
    final Collection<X509Certificate> retCerts = certService.getCertificates("test.com");
    assertEquals(1, retCerts.size());
    final X509Certificate retCert = retCerts.iterator().next();
    assertTrue(retCert instanceof X509CertificateEx);
    assertTrue(((X509CertificateEx) retCert).hasPrivateKey());
}
Also used : X509CertificateEx(org.nhindirect.stagent.cert.X509CertificateEx) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate)

Aggregations

X509CertificateEx (org.nhindirect.stagent.cert.X509CertificateEx)51 X509Certificate (java.security.cert.X509Certificate)39 MimeEntity (org.nhindirect.stagent.mail.MimeEntity)18 SMIMECryptographerImpl (org.nhindirect.stagent.cryptography.SMIMECryptographerImpl)13 IOException (java.io.IOException)11 KeyStore (java.security.KeyStore)11 NHINDException (org.nhindirect.stagent.NHINDException)9 ByteArrayInputStream (java.io.ByteArrayInputStream)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6 Key (java.security.Key)6 PrivateKey (java.security.PrivateKey)6 File (java.io.File)5 Certificate (java.security.cert.Certificate)5 MimeMultipart (javax.mail.internet.MimeMultipart)5 SMIMEEnveloped (org.bouncycastle.mail.smime.SMIMEEnveloped)5 LdapCertificateStoreProvider (org.nhindirect.stagent.cert.impl.provider.LdapCertificateStoreProvider)5 SignedEntity (org.nhindirect.stagent.cryptography.SignedEntity)5 ArrayList (java.util.ArrayList)4 MessagingException (javax.mail.MessagingException)4 RecipientInformation (org.bouncycastle.cms.RecipientInformation)4