Search in sources :

Example 6 with PKCS11Credential

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

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

the class ConfigServiceWSCertificateStore_getCertificateWithHSMKeyTest method getCertService.

protected ConfigServiceCertificateStore getCertService() throws Exception {
    if (StringUtils.isEmpty(TestUtils.setupSafeNetToken()))
        return null;
    final ConfigServiceCertificateStore certService = new ConfigServiceCertificateStore(proxy);
    final PKCS11Credential cred = new BootstrappedPKCS11Credential("1Kingpuff");
    final StaticPKCS11TokenKeyStoreProtectionManager mgr = new StaticPKCS11TokenKeyStoreProtectionManager(cred, "KeyStoreProtKey", "PrivKeyProtKey");
    certService.setKeyStoreProectionManager(mgr);
    return certService;
}
Also used : PKCS11Credential(org.nhindirect.common.crypto.PKCS11Credential) BootstrappedPKCS11Credential(org.nhindirect.common.crypto.impl.BootstrappedPKCS11Credential) StaticPKCS11TokenKeyStoreProtectionManager(org.nhindirect.common.crypto.impl.StaticPKCS11TokenKeyStoreProtectionManager) BootstrappedPKCS11Credential(org.nhindirect.common.crypto.impl.BootstrappedPKCS11Credential)

Example 8 with PKCS11Credential

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

the class PKCS11OperationTests method testImportEncryptedPrivateKeyWithWrapping.

/**
	 * This test will most likely kick out when executed, but can serve as sample code 
	 * for wrapping and unwrapping sensitive key material on a PKCS11 token.
	 * @throws Exception
	 */
@Test
public void testImportEncryptedPrivateKeyWithWrapping() throws Exception {
    /*
		 * The point of this test is to ensure encrypted private keys can be loaded 
		 * into the token without ever exposing any secret material in process memory.
		 */
    final String pkcs11ProvName = TestUtils.setupSafeNetToken();
    if (!StringUtils.isEmpty(pkcs11ProvName)) {
        final PKCS11Credential cred = new BootstrappedPKCS11Credential("1Kingpuff");
        final StaticPKCS11TokenKeyStoreProtectionManager mgr = new StaticPKCS11TokenKeyStoreProtectionManager(cred, "KeyStoreProtKey", "PrivKeyProtKey");
        /*
			 * 1. Create an AES128 secret key on the HSM that will be used to 
			 * encrypt and decrypt private key data.  Use the PrivKeyProtKey entry to store it
			 */
        final KeyGenerator keyGen = KeyGenerator.getInstance("AES", pkcs11ProvName);
        keyGen.init(128);
        final SecretKey keyStoreSecretKey = keyGen.generateKey();
        /*
			 * 2. Get an existing private key that was generated and is stored in a p12 file.  
			 * For real operations, the private key may be generated on an HSM and exported in wrapped format for
			 * storage in a database.  For this test, we'll just use an existing private key in a p12 file and 
			 * wrap it on the HSM.
			 */
        final KeyStore store = KeyStore.getInstance("pkcs12");
        store.load(FileUtils.openInputStream(new File("./src/test/resources/certs/gm2552encrypted.p12")), "1kingpuff".toCharArray());
        // there should only be on entry
        final String alias = store.aliases().nextElement();
        final PrivateKey entry = (PrivateKey) store.getKey(alias, "1kingpuff".toCharArray());
        /*
			 * 3. "Wrap" the private using secret key and AES128 encryption and write it to a file.  The encryption is done
			 * on the HSM so the secret key never leaves the HSM token.  We aren't actually "wrapping" the private key because
			 * it's not on the HSM.  Using "encrypt" instead.
			 */
        byte[] wrappedKey = null;
        try {
            wrappedKey = mgr.wrapWithSecretKey(keyStoreSecretKey, entry);
        } catch (CryptoException e) {
            // this HSM token does not support wrapping.... kick out
            return;
        }
        FileUtils.writeByteArrayToFile(new File("wrappedPrivateKey.der"), wrappedKey);
        /*
			 * 4. Now we have a wrap key in a file.  Let's install it into the token using the 
			 * secret key on the HSM.  This should return us with a private key object, but we should
			 * not be able to get access to the actual unencrypted key data.
			 */
        byte[] encryptedKey = FileUtils.readFileToByteArray(new File("wrappedPrivateKey.der"));
        final PrivateKey securedPrivateKey = (PrivateKey) mgr.unwrapWithSecretKey(keyStoreSecretKey, encryptedKey, "RSA", Cipher.PRIVATE_KEY);
        assertNotNull(securedPrivateKey);
    }
}
Also used : PKCS11Credential(org.nhindirect.common.crypto.PKCS11Credential) SecretKey(javax.crypto.SecretKey) PrivateKey(java.security.PrivateKey) CryptoException(org.nhindirect.common.crypto.exceptions.CryptoException) KeyGenerator(javax.crypto.KeyGenerator) KeyStore(java.security.KeyStore) File(java.io.File) Test(org.junit.Test)

Example 9 with PKCS11Credential

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

the class StaticPKCS11TokenKeyStoreProtectionManagerTest method testSetKeysAsStringAndGetFromToken.

@Test
public void testSetKeysAsStringAndGetFromToken() throws Exception {
    final String pkcs11ProvName = TestUtils.setupSafeNetToken();
    if (!StringUtils.isEmpty(pkcs11ProvName)) {
        PKCS11Credential cred = new BootstrappedPKCS11Credential("1Kingpuff");
        final StaticPKCS11TokenKeyStoreProtectionManager mgr = new StaticPKCS11TokenKeyStoreProtectionManager(cred, "KeyStoreProtKey", "PrivKeyProtKey");
        // create the keys on the token
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        // cryptograph. secure random 
        SecureRandom random = new SecureRandom();
        keyGen.init(random);
        mgr.clearKeyStoreProtectionKey();
        mgr.setKeyStoreProtectionKeyAsString("12345");
        mgr.clearPrivateKeyProtectionKey();
        mgr.setPrivateKeyProtectionKeyAsString("67890");
        assertTrue(Arrays.equals("12345".getBytes(), mgr.getKeyStoreProtectionKey().getEncoded()));
        assertTrue(Arrays.equals("67890".getBytes(), mgr.getPrivateKeyProtectionKey().getEncoded()));
    }
}
Also used : PKCS11Credential(org.nhindirect.common.crypto.PKCS11Credential) SecureRandom(java.security.SecureRandom) KeyGenerator(javax.crypto.KeyGenerator) Test(org.junit.Test)

Example 10 with PKCS11Credential

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

the class StaticPKCS11TokenKeyStoreProtectionManagerTest method testGetAllKeys_StringKeys.

@Test
public void testGetAllKeys_StringKeys() throws Exception {
    final String pkcs11ProvName = TestUtils.setupSafeNetToken();
    if (!StringUtils.isEmpty(pkcs11ProvName)) {
        PKCS11Credential cred = new BootstrappedPKCS11Credential("1Kingpuff");
        final StaticPKCS11TokenKeyStoreProtectionManager mgr = new StaticPKCS11TokenKeyStoreProtectionManager(cred, "KeyStoreProtKey", "PrivKeyProtKey");
        // create the keys on the token
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        // cryptograph. secure random 
        SecureRandom random = new SecureRandom();
        keyGen.init(random);
        mgr.clearKeyStoreProtectionKey();
        mgr.setKeyStoreProtectionKeyAsString("12345");
        mgr.clearPrivateKeyProtectionKey();
        mgr.setPrivateKeyProtectionKeyAsString("67890");
        final Map<String, Key> keys = mgr.getAllKeys();
        assertEquals(2, keys.size());
        Iterator<Entry<String, Key>> entryIter = keys.entrySet().iterator();
        Key key = entryIter.next().getValue();
        assertTrue(Arrays.equals("67890".getBytes(), key.getEncoded()));
        key = entryIter.next().getValue();
        assertTrue(Arrays.equals("12345".getBytes(), key.getEncoded()));
    }
}
Also used : PKCS11Credential(org.nhindirect.common.crypto.PKCS11Credential) Entry(java.util.Map.Entry) SecureRandom(java.security.SecureRandom) KeyGenerator(javax.crypto.KeyGenerator) Key(java.security.Key) SecretKey(javax.crypto.SecretKey) Test(org.junit.Test)

Aggregations

PKCS11Credential (org.nhindirect.common.crypto.PKCS11Credential)12 Test (org.junit.Test)7 KeyGenerator (javax.crypto.KeyGenerator)6 SecureRandom (java.security.SecureRandom)5 SecretKey (javax.crypto.SecretKey)5 BootstrappedPKCS11Credential (org.nhindirect.common.crypto.impl.BootstrappedPKCS11Credential)5 StaticPKCS11TokenKeyStoreProtectionManager (org.nhindirect.common.crypto.impl.StaticPKCS11TokenKeyStoreProtectionManager)5 Key (java.security.Key)4 KeyStore (java.security.KeyStore)3 PrivateKey (java.security.PrivateKey)3 MutableKeyStoreProtectionManager (org.nhindirect.common.crypto.MutableKeyStoreProtectionManager)3 Certificate (java.security.cert.Certificate)2 X509Certificate (java.security.cert.X509Certificate)2 Entry (java.util.Map.Entry)2 X509CertificateEx (org.nhindirect.stagent.cert.X509CertificateEx)2 CacheableKeyStoreManagerCertificateStore (org.nhindirect.stagent.cert.impl.CacheableKeyStoreManagerCertificateStore)2 File (java.io.File)1 RecipientInformation (org.bouncycastle.cms.RecipientInformation)1 SMIMEEnveloped (org.bouncycastle.mail.smime.SMIMEEnveloped)1 CryptoException (org.nhindirect.common.crypto.exceptions.CryptoException)1