use of org.nhindirect.common.crypto.MutableKeyStoreProtectionManager in project nhin-d by DirectProject.
the class CertStoreUtils method certFromData.
public static X509Certificate certFromData(KeyStoreProtectionManager mgr, byte[] data) {
X509Certificate retVal = null;
try {
// first check for wrapped data
final CertContainer container = CertUtils.toCertContainer(data);
if (container.getWrappedKeyData() != null) {
// make sure we have a KeyStoreManager configured
if (mgr == null) {
throw new NHINDException(AgentError.Unexpected, "Resolved certifiate has wrapped data, but resolver has not been configured to unwrap it.");
}
// create a new wrapped certificate object
retVal = WrappedOnDemandX509CertificateEx.fromX509Certificate(mgr, container.getCert(), container.getWrappedKeyData());
return retVal;
}
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();
// look in the keystore manager to check if they private key is store in the token
if (mgr != null && !(retVal instanceof X509CertificateEx)) {
// make sure this a mutable manager
if (mgr instanceof MutableKeyStoreProtectionManager) {
try {
final KeyStore ks = ((MutableKeyStoreProtectionManager) mgr).getKS();
// check to see if this certificate exists in the key store
final String alias = ks.getCertificateAlias(retVal);
if (!StringUtils.isEmpty(alias)) {
// get the private key if it exits
final PrivateKey pKey = (PrivateKey) ks.getKey(alias, "".toCharArray());
if (pKey != null)
retVal = X509CertificateEx.fromX509Certificate(retVal, pKey);
}
} catch (Exception e) {
LOGGER.warn("Could not retrieve the private key from the PKCS11 token: " + e.getMessage(), e);
}
}
}
} catch (Exception e) {
throw new NHINDException("Data cannot be converted to a valid X.509 Certificate", e);
}
return retVal;
}
use of org.nhindirect.common.crypto.MutableKeyStoreProtectionManager in project nhin-d by DirectProject.
the class PKCS11SecretKeyManager method main.
public static void main(String[] argv) {
String[] passArgs = null;
// provider... if not, assume the JVM has already been configured for one
if (argv.length > 0) {
// Check parameters
for (int i = 0; i < argv.length; i++) {
String arg = argv[i];
// Options
if (!arg.startsWith("-")) {
System.err.println("Error: Unexpected argument [" + arg + "]\n");
printUsage();
System.exit(-1);
} else if (arg.equalsIgnoreCase("-pkcscfg")) {
if (i == argv.length - 1 || argv[i + 1].startsWith("-")) {
System.err.println("Error: Missing pkcs config file");
System.exit(-1);
}
pkcs11ProviderCfg = argv[++i];
} else if (arg.equals("-keyStoreCfg")) {
if (i == argv.length - 1 || argv[i + 1].startsWith("-")) {
System.err.println("Error: Missing keystore config file");
System.exit(-1);
}
keyStoreConfigFile = argv[++i];
} else if (arg.equals("-help")) {
printUsage();
System.exit(-1);
} else {
System.err.println("Error: Unknown argument " + arg + "\n");
printUsage();
System.exit(-1);
}
}
}
if (keyStoreConfigFile != null) {
try {
// get additional properties
final InputStream inStream = FileUtils.openInputStream(new File(keyStoreConfigFile));
final Properties props = new Properties();
props.load(inStream);
keyStoreType = props.getProperty("keyStoreType");
providerName = props.getProperty("keyStoreProviderName");
keyStoreSource = props.getProperty("keyStoreSource");
} catch (IOException e) {
System.err.println("Error reading keystore config file to properties: " + e.getMessage());
System.exit(-1);
}
}
MutableKeyStoreProtectionManager mgr = null;
// need to login
try {
mgr = tokenLogin();
} catch (CryptoException e) {
System.out.println("Failed to login to hardware token: " + e.getMessage());
System.exit(-1);
}
final PKCS11SecretKeyManager mgmt = new PKCS11SecretKeyManager(mgr);
boolean runCommand = false;
if (mgmt != null) {
runCommand = mgmt.run(passArgs);
}
if (exitOnEndCommands)
System.exit(runCommand ? 0 : -1);
}
use of org.nhindirect.common.crypto.MutableKeyStoreProtectionManager in project nhin-d by DirectProject.
the class AbstractKeyStoreManagerCertificateStore method remove.
@Override
public void remove(X509Certificate cert) {
if (!(storeMgr instanceof MutableKeyStoreProtectionManager))
throw new IllegalStateException("The store manager is a MutableKeyStoreProtectionManager instance");
try {
String aliasToRemove = null;
for (String alias : storeMgr.getAllEntries().keySet()) {
final Entry entry = storeMgr.getEntry(alias);
if (entry instanceof PrivateKeyEntry) {
final PrivateKeyEntry privEntry = (PrivateKeyEntry) entry;
if (cert.equals(privEntry.getCertificate())) {
aliasToRemove = alias;
break;
}
}
}
if (aliasToRemove != null) {
final MutableKeyStoreProtectionManager mutMgr = (MutableKeyStoreProtectionManager) storeMgr;
mutMgr.clearEntry(aliasToRemove);
}
}///CLOVER:OFF
catch (Exception e) {
throw new NHINDException(AgentError.Unexpected, "Failed to remove key entry from PKCS11 store.", e);
}
///CLOVER:ON
}
use of org.nhindirect.common.crypto.MutableKeyStoreProtectionManager in project nhin-d by DirectProject.
the class AbstractKeyStoreManagerCertificateStore method add.
@Override
public void add(X509Certificate cert) {
if (!(storeMgr instanceof MutableKeyStoreProtectionManager))
throw new IllegalStateException("The store manager is a MutableKeyStoreProtectionManager instance");
if (!(cert instanceof X509CertificateEx) || !((X509CertificateEx) cert).hasPrivateKey())
throw new IllegalArgumentException("PKCS11 certificates require a private key");
final X509CertificateEx exCert = (X509CertificateEx) cert;
// keys stores require aliases, and a given subject may include multiple certificates
// to avoid possible collisions, this will use the certificate thumbprint
final String alias = Thumbprint.toThumbprint(cert).toString();
final PrivateKeyEntry entry = new PrivateKeyEntry(exCert.getPrivateKey(), new Certificate[] { cert });
try {
((MutableKeyStoreProtectionManager) storeMgr).setEntry(alias, entry);
}///CLOVER:OFF
catch (Exception e) {
throw new NHINDException(AgentError.Unexpected, "Failed to add key entry into PKCS11 store.", e);
}
///CLOVER:ON
}
use of org.nhindirect.common.crypto.MutableKeyStoreProtectionManager in project nhin-d by DirectProject.
the class BaseKeyStoreManagerCertStoreTest method setUp.
@Override
public void setUp() throws Exception {
CertCacheFactory.getInstance().flushAll();
if (!StringUtils.isEmpty(TestUtils.setupSafeNetToken())) {
// clean out the token of all private keys
final PKCS11Credential cred = new BootstrappedPKCS11Credential("1Kingpuff");
final MutableKeyStoreProtectionManager mgr = new StaticPKCS11TokenKeyStoreProtectionManager(cred, "", "");
store = new CacheableKeyStoreManagerCertificateStore(mgr);
store.remove(store.getAllCertificates());
assertTrue(store.getAllCertificates().isEmpty());
}
}
Aggregations