use of org.nhindirect.common.tooling.Command in project nhin-d by DirectProject.
the class PKCS11Commands method testKeyUnwrap.
@Command(name = "TestKeyUnwrap", usage = UNWRAP_KEY)
public void testKeyUnwrap(String[] args) {
final String wrapperAlias = StringArrayUtil.getRequiredValue(args, 0);
final String file = StringArrayUtil.getRequiredValue(args, 1);
try {
final byte[] wrappedData = FileUtils.readFileToByteArray(new File(file));
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 (wrapperKey.getAlgorithm().startsWith("AES")) {
final IvParameterSpec iv = new IvParameterSpec(AbstractPKCS11TokenKeyStoreProtectionManager.IV_BYTES);
final Cipher unwrapCipher = Cipher.getInstance("AES/CBC/PKCS5Padding", ks.getProvider().getName());
unwrapCipher.init(Cipher.UNWRAP_MODE, wrapperKey, iv);
final Key unwrappedKey = unwrapCipher.unwrap(wrappedData, "RSA", Cipher.PRIVATE_KEY);
System.out.println("Succesfully unwrapped private key. Private key class: " + unwrappedKey.getClass().getName());
} else {
System.out.println("Wrapper key must be an AES key.");
}
} catch (Exception e) {
e.printStackTrace();
System.err.println("Failed to unwrap private key: " + e.getMessage());
}
}
Aggregations