Search in sources :

Example 71 with Key

use of java.security.Key in project nhin-d by DirectProject.

the class CreatePKCS12 method create.

/**
	 * Creates a PCKS12 file from the certificate and key files.
	 * @param certFile The X509 DER encoded certificate file.
	 * @param keyFile The PCKS8 DER encoded private key file.
	 * @param password Option password for the private key file.  This is required if the private key file is encrypted.  Should be null or empty
	 * if the private key file is not encrypted.
	 * @param createFile Optional file descriptor for the output file of the pkcs12 file.  If this is null, the file name is based on the 
	 * certificate file name.
	 * @return File descriptor of the created pcks12 file.  Null if an error occurred.  
	 */
public static File create(File certFile, File keyFile, String password, File createFile) {
    File pkcs12File = null;
    CreatePKCS12.certFile = certFile;
    CreatePKCS12.keyFile = keyFile;
    FileOutputStream outStr = null;
    InputStream inStr = null;
    // load cert file
    try {
        KeyStore localKeyStore = KeyStore.getInstance("PKCS12", CryptoExtensions.getJCEProviderName());
        localKeyStore.load(null, null);
        byte[] certData = loadFileData(certFile);
        byte[] keyData = loadFileData(keyFile);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        inStr = new ByteArrayInputStream(certData);
        java.security.cert.Certificate cert = cf.generateCertificate(inStr);
        IOUtils.closeQuietly(inStr);
        KeyFactory kf = KeyFactory.getInstance("RSA", CryptoExtensions.getJCEProviderName());
        PKCS8EncodedKeySpec keysp = null;
        if (password != null && !password.isEmpty()) {
            EncryptedPrivateKeyInfo encInfo = new EncryptedPrivateKeyInfo(keyData);
            PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
            String alg = encInfo.getAlgName();
            SecretKeyFactory secFactory = SecretKeyFactory.getInstance(alg, CryptoExtensions.getJCEProviderName());
            SecretKey secKey = secFactory.generateSecret(keySpec);
            keysp = encInfo.getKeySpec(secKey, CryptoExtensions.getJCEProviderName());
        } else {
            keysp = new PKCS8EncodedKeySpec(keyData);
        }
        Key privKey = kf.generatePrivate(keysp);
        char[] array = "".toCharArray();
        localKeyStore.setKeyEntry("privCert", privKey, array, new java.security.cert.Certificate[] { cert });
        pkcs12File = getPKCS12OutFile(createFile);
        outStr = new FileOutputStream(pkcs12File);
        localKeyStore.store(outStr, p12Pass.toCharArray());
    } catch (Exception e) {
        System.err.println("Failed to create pcks12 file: " + e.getMessage());
        e.printStackTrace(System.err);
        return null;
    } finally {
        IOUtils.closeQuietly(outStr);
        IOUtils.closeQuietly(inStr);
    }
    return pkcs12File;
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) KeyStore(java.security.KeyStore) CertificateFactory(java.security.cert.CertificateFactory) SecretKey(javax.crypto.SecretKey) ByteArrayInputStream(java.io.ByteArrayInputStream) FileOutputStream(java.io.FileOutputStream) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) EncryptedPrivateKeyInfo(javax.crypto.EncryptedPrivateKeyInfo) File(java.io.File) SecretKeyFactory(javax.crypto.SecretKeyFactory) KeyFactory(java.security.KeyFactory) SecretKeyFactory(javax.crypto.SecretKeyFactory) Key(java.security.Key) SecretKey(javax.crypto.SecretKey)

Example 72 with Key

use of java.security.Key in project nhin-d by DirectProject.

the class StripP12Passphrase method certFromData.

/*
	 * Load the exiting p12 file using the provided password and private key passphrase.
	 */
private static X509CertificateEx certFromData(byte[] data) {
    X509CertificateEx retVal = null;
    try {
        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, filePassPhrase.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, keyPassPhrase.toCharArray());
                if (key != null && key instanceof PrivateKey) {
                    retVal = X509CertificateEx.fromX509Certificate(cert, (PrivateKey) key);
                }
            }
        } catch (Exception e) {
            // must not be a PKCS12 stream, go on to next step
            System.out.println("Error decoding p12 input file: " + e.getMessage());
        }
        IOUtils.closeQuietly(bais);
    } 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) X509CertificateEx(org.nhindirect.stagent.cert.X509CertificateEx) ByteArrayInputStream(java.io.ByteArrayInputStream) KeyStore(java.security.KeyStore) NHINDException(org.nhindirect.stagent.NHINDException) X509Certificate(java.security.cert.X509Certificate) Key(java.security.Key) PrivateKey(java.security.PrivateKey) NHINDException(org.nhindirect.stagent.NHINDException)

Example 73 with Key

use of java.security.Key in project nhin-d by DirectProject.

the class SplitDirectRecipientInformation_getDecryptedContentTest method testGetDecryptedContent_safeNetHSMKeyEncProvider_differntEncCert_assertNotDecrypted.

public void testGetDecryptedContent_safeNetHSMKeyEncProvider_differntEncCert_assertNotDecrypted() 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)) {
        // 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;
                }
            }
        }
        encCert = TestUtils.getInternalCert("gm2552");
        final SMIMEEnveloped env = createSMIMEEnv(encCert);
        final RecipientInformation recipient = (RecipientInformation) env.getRecipientInfos().getRecipients().iterator().next();
        final SplitDirectRecipientInformationFactory factory = new SplitDirectRecipientInformationFactory(pkcs11ProvName, "BC");
        final SplitDirectRecipientInformation recInfo = (SplitDirectRecipientInformation) factory.createInstance(recipient, env);
        boolean exceptionOccured = false;
        try {
            recInfo.getDecryptedContent(decryptCert.getPrivateKey());
        } catch (Exception e) {
            exceptionOccured = true;
        }
        assertTrue(exceptionOccured);
    }
}
Also used : PrivateKey(java.security.PrivateKey) KeyStore(java.security.KeyStore) SMIMEEnveloped(org.bouncycastle.mail.smime.SMIMEEnveloped) X509Certificate(java.security.cert.X509Certificate) RecipientInformation(org.bouncycastle.cms.RecipientInformation) X509CertificateEx(org.nhindirect.stagent.cert.X509CertificateEx) Key(java.security.Key) PrivateKey(java.security.PrivateKey) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 74 with Key

use of java.security.Key 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 75 with Key

use of java.security.Key in project nhin-d by DirectProject.

the class TrustChainValidator_IntermidiateCert_Test method certFromData.

private X509Certificate certFromData(byte[] data) {
    X509Certificate retVal = null;
    try {
        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) KeyStore(java.security.KeyStore) NHINDException(org.nhindirect.stagent.NHINDException) X509Certificate(java.security.cert.X509Certificate) Key(java.security.Key) PrivateKey(java.security.PrivateKey) NHINDException(org.nhindirect.stagent.NHINDException)

Aggregations

Key (java.security.Key)302 PrivateKey (java.security.PrivateKey)112 SecretKey (javax.crypto.SecretKey)83 KeyStore (java.security.KeyStore)64 PublicKey (java.security.PublicKey)62 Cipher (javax.crypto.Cipher)60 X509Certificate (java.security.cert.X509Certificate)57 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)50 Test (org.junit.Test)44 IOException (java.io.IOException)42 ByteArrayInputStream (java.io.ByteArrayInputStream)38 Certificate (java.security.cert.Certificate)36 SecretKeySpec (javax.crypto.spec.SecretKeySpec)36 KeyFactory (java.security.KeyFactory)35 InvalidKeyException (java.security.InvalidKeyException)32 KeyGenerator (javax.crypto.KeyGenerator)32 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)26 KeyStoreException (java.security.KeyStoreException)22 SecureRandom (java.security.SecureRandom)21 IvParameterSpec (javax.crypto.spec.IvParameterSpec)21