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);
}
}
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);
}
}
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);
}
}
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);
}
}
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);
}
}
Aggregations