use of org.nhindirect.common.tooling.Command in project nhin-d by DirectProject.
the class PKCS11Commands method addRandomSecretKey.
@Command(name = "CreateRandomSecretKey", usage = ADD_RANDOM_SECRET_KEY)
public void addRandomSecretKey(String[] args) {
final String keyName = StringArrayUtil.getRequiredValue(args, 0);
// generate a new random secret key
try {
final KeyGenerator keyGen = KeyGenerator.getInstance("AES", mgr.getKS().getProvider().getName());
keyGen.init(128);
final SecretKey key = keyGen.generateKey();
mgr.clearKey(keyName);
mgr.setKey(keyName, key);
} catch (Exception e) {
System.err.println("Failed to add new random secret key: " + e.getMessage());
e.printStackTrace();
}
}
use of org.nhindirect.common.tooling.Command in project nhin-d by DirectProject.
the class PKCS11Commands method exportPrivateKey.
@Command(name = "ExportPrivateKey", usage = EXPORT_PRIVATE_KEY)
public void exportPrivateKey(String[] args) {
final String alias = StringArrayUtil.getRequiredValue(args, 0);
final String wrapperAlias = StringArrayUtil.getRequiredValue(args, 1);
final String file = StringArrayUtil.getOptionalValue(args, 2, alias + "-privKey.der");
try {
final KeyStore ks = mgr.getKS();
// get the wrapper key
final Key wrapperKey = mgr.getKey(wrapperAlias);
if (wrapperKey == null) {
System.out.println("Wrapper key with name " + wrapperKey + " does not exist.");
return;
}
if (!ks.containsAlias(alias)) {
System.out.println("Private key with name " + alias + " does not exist.");
return;
}
final PrivateKey privKey = (PrivateKey) ks.getKey(alias, "".toCharArray());
if (privKey == null) {
System.out.println("Key name " + alias + " does not contain a private key");
return;
}
// the algorithm used to wrap the key depends on the key type
Cipher myWrapper = null;
if (wrapperKey.getAlgorithm().startsWith("AES")) {
myWrapper = Cipher.getInstance("AES/CBC/PKCS5Padding", ks.getProvider().getName());
AlgorithmParameters mAlgParams = null;
try {
mAlgParams = AlgorithmParameters.getInstance("IV", ks.getProvider().getName());
mAlgParams.init(new IvParameterSpec(AbstractPKCS11TokenKeyStoreProtectionManager.IV_BYTES));
} catch (Exception e) {
}
if (mAlgParams == null)
myWrapper.init(Cipher.WRAP_MODE, wrapperKey, new IvParameterSpec(AbstractPKCS11TokenKeyStoreProtectionManager.IV_BYTES));
else
myWrapper.init(Cipher.WRAP_MODE, wrapperKey, mAlgParams);
} else if (wrapperKey.getAlgorithm().startsWith("RSA")) {
myWrapper = Cipher.getInstance("RSA/ECB/NoPadding", ks.getProvider().getName());
myWrapper.init(Cipher.WRAP_MODE, wrapperKey);
}
byte[] wrappedKey = null;
try {
wrappedKey = myWrapper.wrap(privKey);
} catch (Exception e) {
System.out.println("Private key with name " + alias + " could not be extracted. Your hardware may not allow exporting of private keys or " + "attributes on the key may not allow the key to be exported. \r\nError message: " + e.getMessage());
e.printStackTrace();
return;
}
final File fl = new File(file);
FileUtils.writeByteArrayToFile(fl, wrappedKey);
System.out.println("Wrapped private key written to file " + fl.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
System.err.println("Failed to export private key: " + e.getMessage());
}
}
use of org.nhindirect.common.tooling.Command in project nhin-d by DirectProject.
the class PKCS11Commands method exportPublicKeyCert.
@Command(name = "ExportKeyPairCert", usage = EXPORT_PUB_KEY_CERTIFICATE)
public void exportPublicKeyCert(String[] args) {
final String alias = StringArrayUtil.getRequiredValue(args, 0);
final String file = StringArrayUtil.getOptionalValue(args, 1, alias + ".der");
try {
final KeyStore ks = mgr.getKS();
if (!ks.containsAlias(alias)) {
System.out.println("Entry with key name " + alias + " does not exist.");
return;
}
final X509Certificate storedCert = (X509Certificate) ks.getCertificate(alias);
if (storedCert == null) {
System.out.println("Key name " + alias + " does not contain a certificate that can be exported. This key may not be an RSA key pair.");
return;
}
final File fl = new File(file);
FileUtils.writeByteArrayToFile(fl, storedCert.getEncoded());
System.out.println("Certificate written to file " + fl.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
System.err.println("Failed to export certificate: " + e.getMessage());
}
}
use of org.nhindirect.common.tooling.Command in project nhin-d by DirectProject.
the class PKCS11Commands method listAllKeys.
@Command(name = "ListAllKeys", usage = LIST_ALL_KEYS)
public void listAllKeys(String[] args) {
try {
final KeyStore ks = mgr.getKS();
// get all of the data from the token
final Enumeration<String> aliases = ks.aliases();
if (!aliases.hasMoreElements())
System.out.println("No keys found");
else {
final Collection<KeyModel> models = new ArrayList<KeyModel>();
while (aliases.hasMoreElements()) {
final String alias = aliases.nextElement();
if (ks.isKeyEntry(alias)) {
final Key key = ks.getKey(alias, null);
char[] keyText = (key.getEncoded() != null) ? "*****".toCharArray() : "Not Extractable".toCharArray();
final KeyModel keyModel = new KeyModel(alias, key, keyText);
models.add(keyModel);
}
}
keyPrinter.printRecords(models);
}
} catch (Exception e) {
e.printStackTrace();
}
}
use of org.nhindirect.common.tooling.Command in project nhin-d by DirectProject.
the class PKCS11Commands method createKeyPair.
@Command(name = "CreateKeyPair", usage = CREATE_KEY_PAIR)
public void createKeyPair(String[] args) {
final String alias = StringArrayUtil.getRequiredValue(args, 0);
final String keySize = StringArrayUtil.getOptionalValue(args, 1, "2048");
try {
// create a local keygen for a private key to sign the certificate
final KeyPairGenerator localKeyGen = KeyPairGenerator.getInstance("RSA", "BC");
final KeyPair localKeyPair = localKeyGen.generateKeyPair();
final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", mgr.getKS().getProvider().getName());
keyGen.initialize(Integer.parseInt(keySize));
final KeyPair keyPair = keyGen.generateKeyPair();
// create a self signed certificate
X509V3CertificateGenerator v1CertGen = new X509V3CertificateGenerator();
v1CertGen.setPublicKey(keyPair.getPublic());
v1CertGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
end.add(Calendar.DAY_OF_MONTH, 3000);
v1CertGen.setSerialNumber(BigInteger.valueOf(generatePositiveRandom()));
v1CertGen.setIssuerDN(new X509Principal("cn=test"));
v1CertGen.setNotBefore(start.getTime());
v1CertGen.setNotAfter(end.getTime());
// issuer and subject are the same for a CA
v1CertGen.setSubjectDN(new X509Principal("cn=test"));
v1CertGen.setPublicKey(keyPair.getPublic());
X509Certificate newCACert = v1CertGen.generate(localKeyPair.getPrivate(), "BC");
mgr.getKS().setKeyEntry(alias, keyPair.getPrivate(), "".toCharArray(), new X509Certificate[] { newCACert });
System.out.println("Key pair created and stored.");
} catch (Exception e) {
e.printStackTrace();
System.err.println("Failed to generate key pair: " + e.getMessage());
}
}
Aggregations