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