Search in sources :

Example 11 with Command

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());
    }
}
Also used : IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) File(java.io.File) KeyStore(java.security.KeyStore) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey) Command(org.nhindirect.common.tooling.Command)

Aggregations

Command (org.nhindirect.common.tooling.Command)11 KeyStore (java.security.KeyStore)8 File (java.io.File)6 PrivateKey (java.security.PrivateKey)6 X509Certificate (java.security.cert.X509Certificate)5 SecretKey (javax.crypto.SecretKey)4 Key (java.security.Key)3 MessageDigest (java.security.MessageDigest)2 Cipher (javax.crypto.Cipher)2 IvParameterSpec (javax.crypto.spec.IvParameterSpec)2 X509Principal (org.bouncycastle.jce.X509Principal)2 AlgorithmParameters (java.security.AlgorithmParameters)1 KeyPair (java.security.KeyPair)1 KeyPairGenerator (java.security.KeyPairGenerator)1 SecureRandom (java.security.SecureRandom)1 ArrayList (java.util.ArrayList)1 Calendar (java.util.Calendar)1 Random (java.util.Random)1 Vector (java.util.Vector)1 KeyGenerator (javax.crypto.KeyGenerator)1