Search in sources :

Example 1 with CryptoException

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

the class CertificatesController method toCertDataFormat.

/*
	 * Converts an incoming P12 format to an appropriate format to be store in the config store.  If a keystore protection manager
	 * has been configured, then the private key is wrapped before sending to the config store.
	 */
private byte[] toCertDataFormat(byte[] certOrP12Bytes, byte[] privateKeyBytes, PrivateKeyType privKeyType) throws CryptoException {
    try {
        // if there is no private key, then just return the encoded certificate
        if (privKeyType == PrivateKeyType.NONE)
            return certOrP12Bytes;
        final CertContainer cont = CertUtils.toCertContainer(certOrP12Bytes);
        // if this is a PKCS12 format, then either return the bytes as is, or if there is keystore manager, wrap the private keys
        if (privKeyType == PrivateKeyType.PKCS_12_PASSPHRASE | privKeyType == PrivateKeyType.PKCS_12_UNPROTECTED) {
            // as PKCS12 file
            if (this.keyManager == null) {
                this.log.info("Storing PKCS12 file in PKCS12 unprotected format");
                return certOrP12Bytes;
            } else {
                this.log.info("Storing PKCS12 file in wrapped format");
                // now wrap the private key
                final byte[] wrappedKey = this.keyManager.wrapWithSecretKey((SecretKey) ((KeyStoreProtectionManager) keyManager).getPrivateKeyProtectionKey(), cont.getKey());
                // return the wrapped key format
                return CertUtils.certAndWrappedKeyToRawByteFormat(wrappedKey, cont.getCert());
            }
        } else // when there is private key file, then either turn into a PKCS12 file (if there is no key manager), or wrap the key.
        {
            // cert and wrapped key format
            if (privKeyType == PrivateKeyType.PKCS8_WRAPPED) {
                this.log.info("Storing already wrapped PKCS8 file");
                return CertUtils.certAndWrappedKeyToRawByteFormat(privateKeyBytes, cont.getCert());
            }
            // get a private key object, the private key is normalized at this point into an unencrypted format
            final KeyFactory kf = KeyFactory.getInstance("RSA", CertUtils.getJCEProviderName());
            final PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(privateKeyBytes);
            final Key privKey = kf.generatePrivate(keysp);
            if (this.keyManager == null) {
                this.log.info("Storing PKCS8 private key in PKCS12 unprotected format");
                // if there is no keystore manager, we can't wrap the keys, so we'll just send them over the wire
                // as PKCS12 file.  need to turn this into a PKCS12 format
                final KeyStore localKeyStore = KeyStore.getInstance("PKCS12", CertUtils.getJCEProviderName());
                localKeyStore.load(null, null);
                localKeyStore.setKeyEntry("privCert", privKey, "".toCharArray(), new java.security.cert.Certificate[] { cont.getCert() });
                final ByteArrayOutputStream outStr = new ByteArrayOutputStream();
                localKeyStore.store(outStr, "".toCharArray());
                try {
                    return outStr.toByteArray();
                } finally {
                    IOUtils.closeQuietly(outStr);
                }
            } else {
                this.log.info("Storing PKCS8 private key in wrapped format");
                // wrap the key and turn the stream in the wrapped key format
                final byte[] wrappedKey = this.keyManager.wrapWithSecretKey((SecretKey) ((KeyStoreProtectionManager) keyManager).getPrivateKeyProtectionKey(), privKey);
                return CertUtils.certAndWrappedKeyToRawByteFormat(wrappedKey, cont.getCert());
            }
        }
    } catch (Exception e) {
        throw new CryptoException("Failed to conver certificate and key to cert data format: " + e.getMessage(), e);
    }
}
Also used : PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) MutableKeyStoreProtectionManager(org.nhindirect.common.crypto.MutableKeyStoreProtectionManager) KeyStoreProtectionManager(org.nhindirect.common.crypto.KeyStoreProtectionManager) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CryptoException(org.nhindirect.common.crypto.exceptions.CryptoException) KeyStore(java.security.KeyStore) CertContainer(org.nhindirect.config.model.utils.CertUtils.CertContainer) KeyFactory(java.security.KeyFactory) SecretKeyFactory(javax.crypto.SecretKeyFactory) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey) ServiceException(org.nhindirect.common.rest.exceptions.ServiceException) IOException(java.io.IOException) CryptoException(org.nhindirect.common.crypto.exceptions.CryptoException)

Example 2 with CryptoException

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

the class AbstractPKCS11TokenKeyStoreProtectionManager method wrapWithSecretKey.

/**
	 * {@inheritDoc}}
	 */
@Override
public byte[] wrapWithSecretKey(SecretKey kek, Key keyToWrap) throws CryptoException {
    final IvParameterSpec iv = new IvParameterSpec(IV_BYTES);
    try {
        final Cipher wrapCipher = Cipher.getInstance(WRAP_ALGO, ks.getProvider().getName());
        wrapCipher.init(Cipher.WRAP_MODE, kek, iv);
        return wrapCipher.wrap(keyToWrap);
    } catch (Exception e) {
        throw new CryptoException("Failed to wrap key: " + e.getMessage(), e);
    }
}
Also used : IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) CryptoException(org.nhindirect.common.crypto.exceptions.CryptoException) CryptoException(org.nhindirect.common.crypto.exceptions.CryptoException)

Example 3 with CryptoException

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

the class AbstractPKCS11TokenKeyStoreProtectionManager method setPrivateKeyProtectionKeyAsString.

/**
	 * {@inheritDoc}
	 */
@Override
public void setPrivateKeyProtectionKeyAsString(String key) throws CryptoException {
    try {
        final Key keySpec = new SecretKeySpec(key.getBytes(), "");
        safeSetKeyWithRetry(privateKeyPassPhraseAlias, keySpec);
    } catch (CryptoException e) {
        throw e;
    } catch (Exception e) {
        throw new CryptoException("Error storing key store protection into PKCS11 token", e);
    }
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) CryptoException(org.nhindirect.common.crypto.exceptions.CryptoException) Key(java.security.Key) SecretKey(javax.crypto.SecretKey) CryptoException(org.nhindirect.common.crypto.exceptions.CryptoException)

Example 4 with CryptoException

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

the class AbstractPKCS11TokenKeyStoreProtectionManager method loadProvider.

protected void loadProvider() throws CryptoException {
    try {
        if (!StringUtils.isEmpty(this.keyStoreProviderName)) {
            if (this.keyStoreProviderName.equals(SUNPKCS11_KEYSTORE_PROVIDER_NAME)) {
                // this provider requires a config file
                if (StringUtils.isEmpty(this.pcks11ConfigFile))
                    throw new IllegalStateException("SunPKCS11 providers require a configuration file.  There is not one set.");
                // check and see if this is one of the same providers that is already loaded
                final InputStream inStream = FileUtils.openInputStream(new File(this.pcks11ConfigFile));
                final Properties props = new Properties();
                props.load(inStream);
                IOUtils.closeQuietly(inStream);
                boolean providerFound = false;
                final String requestedName = props.getProperty("name");
                // check if this provider exists
                if (!StringUtils.isEmpty(requestedName) && Security.getProvider(requestedName) != null)
                    providerFound = true;
                if (!providerFound) {
                    // dynamic load... some class loaders may have issues, so use dynamic loading
                    final Class<?> provider = this.getClass().getClassLoader().loadClass("sun.security.pkcs11.SunPKCS11");
                    final Constructor<?> ctor = provider.getConstructor(String.class);
                    Security.addProvider((Provider) ctor.newInstance(this.pcks11ConfigFile));
                }
            } else {
                // create the new provider
                final Class<?> provider = this.getClass().getClassLoader().loadClass(this.keyStoreProviderName);
                // check if the provider is already loaded
                boolean providerFound = false;
                for (Provider existingProv : Security.getProviders()) {
                    if (existingProv.getClass().equals(provider)) {
                        providerFound = true;
                        break;
                    }
                }
                if (!providerFound)
                    Security.addProvider((Provider) provider.newInstance());
            }
        }
    } catch (Exception e) {
        throw new CryptoException("Error loading PKCS11 provder", e);
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Properties(java.util.Properties) CryptoException(org.nhindirect.common.crypto.exceptions.CryptoException) File(java.io.File) CryptoException(org.nhindirect.common.crypto.exceptions.CryptoException) Provider(java.security.Provider)

Example 5 with CryptoException

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

the class AbstractPKCS11TokenKeyStoreProtectionManager method setKeyStoreProtectionKeyAsBytes.

/**
	 * {@inheritDoc}
	 */
@Override
public void setKeyStoreProtectionKeyAsBytes(byte[] key) throws CryptoException {
    try {
        final Key keySpec = new SecretKeySpec(key, "");
        safeSetKeyWithRetry(keyStorePassPhraseAlias, keySpec);
    } catch (CryptoException e) {
        throw e;
    } catch (Exception e) {
        throw new CryptoException("Error storing key store protection into PKCS11 token", e);
    }
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) CryptoException(org.nhindirect.common.crypto.exceptions.CryptoException) Key(java.security.Key) SecretKey(javax.crypto.SecretKey) CryptoException(org.nhindirect.common.crypto.exceptions.CryptoException)

Aggregations

CryptoException (org.nhindirect.common.crypto.exceptions.CryptoException)20 SecretKey (javax.crypto.SecretKey)6 Key (java.security.Key)5 SecretKeySpec (javax.crypto.spec.SecretKeySpec)5 ByteArrayInputStream (java.io.ByteArrayInputStream)4 File (java.io.File)4 IOException (java.io.IOException)4 InputStream (java.io.InputStream)4 Cipher (javax.crypto.Cipher)4 IvParameterSpec (javax.crypto.spec.IvParameterSpec)4 Properties (java.util.Properties)3 KeyStore (java.security.KeyStore)2 PrivateKey (java.security.PrivateKey)2 MutableKeyStoreProtectionManager (org.nhindirect.common.crypto.MutableKeyStoreProtectionManager)2 Point (java.awt.Point)1 BufferedReader (java.io.BufferedReader)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 Console (java.io.Console)1 InputStreamReader (java.io.InputStreamReader)1 KeyFactory (java.security.KeyFactory)1