Search in sources :

Example 1 with MutableKeyStoreProtectionManager

use of org.nhindirect.common.crypto.MutableKeyStoreProtectionManager 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 2 with MutableKeyStoreProtectionManager

use of org.nhindirect.common.crypto.MutableKeyStoreProtectionManager in project nhin-d by DirectProject.

the class PKCS11SecretKeyManager method main.

public static void main(String[] argv) {
    String[] passArgs = null;
    // provider... if not, assume the JVM has already been configured for one
    if (argv.length > 0) {
        // Check parameters
        for (int i = 0; i < argv.length; i++) {
            String arg = argv[i];
            // Options
            if (!arg.startsWith("-")) {
                System.err.println("Error: Unexpected argument [" + arg + "]\n");
                printUsage();
                System.exit(-1);
            } else if (arg.equalsIgnoreCase("-pkcscfg")) {
                if (i == argv.length - 1 || argv[i + 1].startsWith("-")) {
                    System.err.println("Error: Missing pkcs config file");
                    System.exit(-1);
                }
                pkcs11ProviderCfg = argv[++i];
            } else if (arg.equals("-keyStoreCfg")) {
                if (i == argv.length - 1 || argv[i + 1].startsWith("-")) {
                    System.err.println("Error: Missing keystore config file");
                    System.exit(-1);
                }
                keyStoreConfigFile = argv[++i];
            } else if (arg.equals("-help")) {
                printUsage();
                System.exit(-1);
            } else {
                System.err.println("Error: Unknown argument " + arg + "\n");
                printUsage();
                System.exit(-1);
            }
        }
    }
    if (keyStoreConfigFile != null) {
        try {
            // get additional properties
            final InputStream inStream = FileUtils.openInputStream(new File(keyStoreConfigFile));
            final Properties props = new Properties();
            props.load(inStream);
            keyStoreType = props.getProperty("keyStoreType");
            providerName = props.getProperty("keyStoreProviderName");
            keyStoreSource = props.getProperty("keyStoreSource");
        } catch (IOException e) {
            System.err.println("Error reading keystore config file to properties: " + e.getMessage());
            System.exit(-1);
        }
    }
    MutableKeyStoreProtectionManager mgr = null;
    // need to login
    try {
        mgr = tokenLogin();
    } catch (CryptoException e) {
        System.out.println("Failed to login to hardware token: " + e.getMessage());
        System.exit(-1);
    }
    final PKCS11SecretKeyManager mgmt = new PKCS11SecretKeyManager(mgr);
    boolean runCommand = false;
    if (mgmt != null) {
        runCommand = mgmt.run(passArgs);
    }
    if (exitOnEndCommands)
        System.exit(runCommand ? 0 : -1);
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) MutableKeyStoreProtectionManager(org.nhindirect.common.crypto.MutableKeyStoreProtectionManager) IOException(java.io.IOException) Properties(java.util.Properties) CryptoException(org.nhindirect.common.crypto.exceptions.CryptoException) File(java.io.File)

Example 3 with MutableKeyStoreProtectionManager

use of org.nhindirect.common.crypto.MutableKeyStoreProtectionManager in project nhin-d by DirectProject.

the class AbstractKeyStoreManagerCertificateStore method remove.

@Override
public void remove(X509Certificate cert) {
    if (!(storeMgr instanceof MutableKeyStoreProtectionManager))
        throw new IllegalStateException("The store manager is a MutableKeyStoreProtectionManager instance");
    try {
        String aliasToRemove = null;
        for (String alias : storeMgr.getAllEntries().keySet()) {
            final Entry entry = storeMgr.getEntry(alias);
            if (entry instanceof PrivateKeyEntry) {
                final PrivateKeyEntry privEntry = (PrivateKeyEntry) entry;
                if (cert.equals(privEntry.getCertificate())) {
                    aliasToRemove = alias;
                    break;
                }
            }
        }
        if (aliasToRemove != null) {
            final MutableKeyStoreProtectionManager mutMgr = (MutableKeyStoreProtectionManager) storeMgr;
            mutMgr.clearEntry(aliasToRemove);
        }
    }///CLOVER:OFF
     catch (Exception e) {
        throw new NHINDException(AgentError.Unexpected, "Failed to remove key entry from PKCS11 store.", e);
    }
///CLOVER:ON
}
Also used : PrivateKeyEntry(java.security.KeyStore.PrivateKeyEntry) Entry(java.security.KeyStore.Entry) MutableKeyStoreProtectionManager(org.nhindirect.common.crypto.MutableKeyStoreProtectionManager) PrivateKeyEntry(java.security.KeyStore.PrivateKeyEntry) NHINDException(org.nhindirect.stagent.NHINDException) NHINDException(org.nhindirect.stagent.NHINDException)

Example 4 with MutableKeyStoreProtectionManager

use of org.nhindirect.common.crypto.MutableKeyStoreProtectionManager in project nhin-d by DirectProject.

the class AbstractKeyStoreManagerCertificateStore method add.

@Override
public void add(X509Certificate cert) {
    if (!(storeMgr instanceof MutableKeyStoreProtectionManager))
        throw new IllegalStateException("The store manager is a MutableKeyStoreProtectionManager instance");
    if (!(cert instanceof X509CertificateEx) || !((X509CertificateEx) cert).hasPrivateKey())
        throw new IllegalArgumentException("PKCS11 certificates require a private key");
    final X509CertificateEx exCert = (X509CertificateEx) cert;
    // keys stores require aliases, and a given subject may include multiple certificates
    // to avoid possible collisions, this will use the certificate thumbprint
    final String alias = Thumbprint.toThumbprint(cert).toString();
    final PrivateKeyEntry entry = new PrivateKeyEntry(exCert.getPrivateKey(), new Certificate[] { cert });
    try {
        ((MutableKeyStoreProtectionManager) storeMgr).setEntry(alias, entry);
    }///CLOVER:OFF
     catch (Exception e) {
        throw new NHINDException(AgentError.Unexpected, "Failed to add key entry into PKCS11 store.", e);
    }
///CLOVER:ON
}
Also used : X509CertificateEx(org.nhindirect.stagent.cert.X509CertificateEx) MutableKeyStoreProtectionManager(org.nhindirect.common.crypto.MutableKeyStoreProtectionManager) PrivateKeyEntry(java.security.KeyStore.PrivateKeyEntry) NHINDException(org.nhindirect.stagent.NHINDException) NHINDException(org.nhindirect.stagent.NHINDException)

Example 5 with MutableKeyStoreProtectionManager

use of org.nhindirect.common.crypto.MutableKeyStoreProtectionManager in project nhin-d by DirectProject.

the class BaseKeyStoreManagerCertStoreTest method setUp.

@Override
public void setUp() throws Exception {
    CertCacheFactory.getInstance().flushAll();
    if (!StringUtils.isEmpty(TestUtils.setupSafeNetToken())) {
        // clean out the token of all private keys
        final PKCS11Credential cred = new BootstrappedPKCS11Credential("1Kingpuff");
        final MutableKeyStoreProtectionManager mgr = new StaticPKCS11TokenKeyStoreProtectionManager(cred, "", "");
        store = new CacheableKeyStoreManagerCertificateStore(mgr);
        store.remove(store.getAllCertificates());
        assertTrue(store.getAllCertificates().isEmpty());
    }
}
Also used : PKCS11Credential(org.nhindirect.common.crypto.PKCS11Credential) BootstrappedPKCS11Credential(org.nhindirect.common.crypto.impl.BootstrappedPKCS11Credential) MutableKeyStoreProtectionManager(org.nhindirect.common.crypto.MutableKeyStoreProtectionManager) StaticPKCS11TokenKeyStoreProtectionManager(org.nhindirect.common.crypto.impl.StaticPKCS11TokenKeyStoreProtectionManager) BootstrappedPKCS11Credential(org.nhindirect.common.crypto.impl.BootstrappedPKCS11Credential)

Aggregations

MutableKeyStoreProtectionManager (org.nhindirect.common.crypto.MutableKeyStoreProtectionManager)11 KeyStore (java.security.KeyStore)7 PrivateKey (java.security.PrivateKey)7 X509Certificate (java.security.cert.X509Certificate)7 IOException (java.io.IOException)5 Key (java.security.Key)4 ArrayList (java.util.ArrayList)4 ServiceException (org.nhindirect.common.rest.exceptions.ServiceException)4 Certificate (org.nhindirect.config.model.Certificate)4 CertificateForm (org.nhindirect.config.ui.form.CertificateForm)4 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)4 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)4 ModelAndView (org.springframework.web.servlet.ModelAndView)4 PKCS11Credential (org.nhindirect.common.crypto.PKCS11Credential)3 CryptoException (org.nhindirect.common.crypto.exceptions.CryptoException)3 BootstrappedPKCS11Credential (org.nhindirect.common.crypto.impl.BootstrappedPKCS11Credential)3 StaticPKCS11TokenKeyStoreProtectionManager (org.nhindirect.common.crypto.impl.StaticPKCS11TokenKeyStoreProtectionManager)3 SearchDomainForm (org.nhindirect.config.ui.form.SearchDomainForm)3 SimpleForm (org.nhindirect.config.ui.form.SimpleForm)3 NHINDException (org.nhindirect.stagent.NHINDException)3