Search in sources :

Example 16 with NAEParameterSpec

use of com.ingrian.security.nae.NAEParameterSpec in project CipherTrust_Application_Protection by thalescpl-io.

the class KMIPGenKeys method main.

public static void main(String[] args) {
    if (args.length != 4) {
        usage();
    }
    int length = Integer.valueOf(args[3]);
    // add Ingrian provider to the list of JCE providers
    Security.addProvider(new IngrianProvider());
    // create KMIP Session - specify client X.509 certificate and keystore password
    KMIPSession session = KMIPSession.getSession(new NAEClientCertificate(args[0], args[1].toCharArray()));
    KeyPair sunPair = null;
    try {
        // verify Key Manager supports key pair generation
        if (!queryKeyGen(session)) {
            System.err.println("Key Manager does not support key pair generation");
            System.exit(0);
        }
        deleteIfNecessary(NAEKey.getPublicKey(args[2].trim() + Config.s_publicKeyGenSuffix, session));
        deleteIfNecessary(NAEKey.getPrivateKey(args[2].trim() + Config.s_privateKeyGenSuffix, session));
        RSAKeyPairGenerator keyGen = new RSAKeyPairGenerator();
        NAEParameterSpec spec = new NAEParameterSpec(args[2].trim(), length, (KMIPAttributes) null, session);
        keyGen.initialize(spec, null);
        sunPair = keyGen.generateKeyPair();
        PrivateKey priv = sunPair.getPrivate();
        PublicKey pub = sunPair.getPublic();
        NAEPrivateKey naePriv = (NAEPrivateKey) priv;
        NAEPublicKey naePub = (NAEPublicKey) pub;
        System.out.println("\n\n----------------------------\n");
        System.out.println("Key length = " + length);
        System.out.println("Private key name           : " + naePriv.getName());
        System.out.println("Private key format         : " + naePriv.getFormat());
        System.out.println("Private key algorithm      : " + naePriv.getAlgorithm());
        System.out.println("Private key encoded length : " + naePriv.getKeySize());
        System.out.println("Public key name            : " + naePub.getName());
        System.out.println("Public key format          : " + naePub.getFormat());
        System.out.println("Public key algorithm      : " + "" + naePub.getAlgorithm());
        System.out.println("Public key encoded length  : " + naePub.getKeySize());
    /* ((NAEPrivateKey)priv).delete();
            ((NAEPublicKey)pub).delete();*/
    } catch (Exception e) {
        System.out.println("The Cause is " + e.getMessage() + ".");
        e.printStackTrace();
    } finally {
        if (session != null)
            session.closeSession();
    }
}
Also used : KeyPair(java.security.KeyPair) NAEParameterSpec(com.ingrian.security.nae.NAEParameterSpec) PrivateKey(java.security.PrivateKey) NAEPrivateKey(com.ingrian.security.nae.NAEPrivateKey) NAEPrivateKey(com.ingrian.security.nae.NAEPrivateKey) PublicKey(java.security.PublicKey) NAEPublicKey(com.ingrian.security.nae.NAEPublicKey) RSAKeyPairGenerator(com.ingrian.security.nae.RSAKeyPairGenerator) NAEPublicKey(com.ingrian.security.nae.NAEPublicKey) NAEClientCertificate(com.ingrian.security.nae.NAEClientCertificate) NAEException(com.ingrian.security.nae.NAEException) IngrianProvider(com.ingrian.security.nae.IngrianProvider) KMIPSession(com.ingrian.security.nae.KMIPSession)

Example 17 with NAEParameterSpec

use of com.ingrian.security.nae.NAEParameterSpec in project CipherTrust_Application_Protection by thalescpl-io.

the class KMIPCreateSymmetricKeySample method main.

public static void main(String[] args) throws Exception {
    String keyName = null;
    int keyLength = 256;
    if (args.length != 3) {
        usage();
    }
    keyName = args[2];
    // add Ingrian provider to the list of JCE providers
    Security.addProvider(new IngrianProvider());
    KMIPSession session = null;
    try {
        // create KMIP Session - specify client X.509 certificate and keystore password
        session = KMIPSession.getSession(new NAEClientCertificate(args[0], args[1].toCharArray()));
        NAEKey key;
        try {
            /* does the key exist? if so, delete it */
            /* get..Key method is merely a placeholder for a managed object 
                * with that name. */
            key = NAEKey.getSecretKey(keyName, session);
            /* getUID() will throw an exception if the key does not exist */
            if (key.getUID() != null) {
                // exists if Unique Identifier is not null
                System.out.println("Deleting key " + keyName + " with UID=" + key.getUID());
                key.delete();
            }
        } catch (Exception notFound) {
        }
        /* create a secret key on the Key Manager using JCE key generator */
        KMIPAttributes initialAttributes = new KMIPAttributes();
        initialAttributes.add(KMIPAttribute.CryptographicUsageMask, (int) (UsageMask.Encrypt.getValue() | UsageMask.Decrypt.getValue()));
        NAEParameterSpec spec = new NAEParameterSpec(keyName, keyLength, (KMIPAttributes) initialAttributes, session);
        KeyGenerator kg = KeyGenerator.getInstance("AES", "IngrianProvider");
        kg.init(spec);
        SecretKey secretKey = kg.generateKey();
        System.out.println("Created key " + ((NAEKey) secretKey).getName());
        /* cast to NAEKey and list the default attribute names */
        Set<String> defaultAttributes = ((NAEKey) secretKey).listKMIPAttributes();
        System.out.println(defaultAttributes);
    } catch (Exception e) {
        System.out.println("The Cause is " + e.getMessage() + ".");
        e.printStackTrace();
    } finally {
        if (session != null)
            session.closeSession();
    }
}
Also used : KMIPAttributes(com.ingrian.security.nae.KMIPAttributes) NAEParameterSpec(com.ingrian.security.nae.NAEParameterSpec) SecretKey(javax.crypto.SecretKey) NAEKey(com.ingrian.security.nae.NAEKey) NAEClientCertificate(com.ingrian.security.nae.NAEClientCertificate) KeyGenerator(javax.crypto.KeyGenerator) NAEException(com.ingrian.security.nae.NAEException) IngrianProvider(com.ingrian.security.nae.IngrianProvider) KMIPSession(com.ingrian.security.nae.KMIPSession)

Example 18 with NAEParameterSpec

use of com.ingrian.security.nae.NAEParameterSpec in project CipherTrust_Application_Protection by thalescpl-io.

the class WrapKeySample method main.

public static void main(String[] args) {
    Security.addProvider(new IngrianProvider());
    if (args.length != 5) {
        System.err.println("Usage: java WrapKeySample user password keyToWrapName wrappingKeyName groupName");
        System.exit(-1);
    }
    String userName = args[0];
    String passWord = args[1];
    String keyToWrapName = "WrapSamplePair" + args[2];
    String wrappingKeyName = "WrapSampleKey" + args[3];
    String groupName = args[4];
    NAESession session = null;
    try {
        // Create an NAESession.
        session = NAESession.getSession(userName, passWord.toCharArray());
        NAEParameterSpec spec = new NAEParameterSpec(keyToWrapName, true, true, 256, session);
        // Delete any existing keys from this sample.
        NAEKey keyToDelete = NAEKey.getSecretKey(keyToWrapName, session);
        deleteExistingKeys(wrappingKeyName, session, keyToDelete);
        // Generate an AES key to be wrapped when exported.
        KeyGenerator generator = KeyGenerator.getInstance("AES", "IngrianProvider");
        // NAEEParameters to pass session
        generator.init(spec);
        NAEKey keyToBeWrapped = (NAEKey) generator.generateKey();
        // Create a public/private RSA key pair to do the key wrapping.
        // The AES key will be wrapped with the RSA Public Key, and
        // later unwrapped using the RSA Private Key.
        KeyPair pair = createKeyPair(session, groupName, wrappingKeyName);
        NAEPublicKey publicKey = NAEKey.getPublicKey(wrappingKeyName, session);
        NAEPrivateKey privateKey = NAEKey.getPrivateKey(wrappingKeyName, session);
        // Init a JCE Cipher in WRAP_MODE to do the key wrapping.
        Cipher cipher = Cipher.getInstance("RSA", "IngrianProvider");
        cipher.init(Cipher.WRAP_MODE, publicKey, spec);
        // Wrap and export the wrapped AES Key from the Key Manager
        // using the cipher.wrap method.
        // The key is wrapped with the Public key from the key pair
        // on the Key Manager which was generated earlier.
        byte[] wrappedKey = cipher.wrap(keyToBeWrapped);
        System.out.println("wrapped  : " + IngrianProvider.byteArray2Hex(wrappedKey));
        System.out.println("Length   : " + wrappedKey.length);
        // Unwrap the AES key using the private key of the
        // generated key pair using the SunJCE provider.
        // Export the NAEPrivate key as a JCE PrivateKey.
        PrivateKey prKey = privateKey.exportJCEKey();
        // Initialize a Cipher based on the SunJCE provider.
        // For IBM Java, change the provider from "SunJCE" to "IBMJCE"
        // Note the use of PKCS1Padding.
        Cipher cipher2 = Cipher.getInstance("RSA/ECB/PKCS1Padding", "SunJCE");
        cipher2.init(Cipher.UNWRAP_MODE, prKey);
        // Unwrap the wrapped key from the bytes returned from the
        // Key Manager.
        Key unWrappedKey = cipher2.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);
        System.out.println("Unwrapped: " + IngrianProvider.byteArray2Hex(unWrappedKey.getEncoded()));
        System.out.println("Original : " + IngrianProvider.byteArray2Hex(keyToBeWrapped.export()));
        if (Arrays.equals(keyToBeWrapped.export(), unWrappedKey.getEncoded()))
            System.out.println("Unwrapped key bytes equal original key bytes");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (session != null)
            session.closeSession();
    }
}
Also used : NAEParameterSpec(com.ingrian.security.nae.NAEParameterSpec) KeyPair(java.security.KeyPair) NAEKey(com.ingrian.security.nae.NAEKey) PrivateKey(java.security.PrivateKey) NAEPrivateKey(com.ingrian.security.nae.NAEPrivateKey) NAEPrivateKey(com.ingrian.security.nae.NAEPrivateKey) NAEPublicKey(com.ingrian.security.nae.NAEPublicKey) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) NoSuchProviderException(java.security.NoSuchProviderException) IngrianProvider(com.ingrian.security.nae.IngrianProvider) Cipher(javax.crypto.Cipher) KeyGenerator(javax.crypto.KeyGenerator) NAESession(com.ingrian.security.nae.NAESession) Key(java.security.Key) PrivateKey(java.security.PrivateKey) NAEKey(com.ingrian.security.nae.NAEKey) NAEPublicKey(com.ingrian.security.nae.NAEPublicKey) NAEPrivateKey(com.ingrian.security.nae.NAEPrivateKey)

Example 19 with NAEParameterSpec

use of com.ingrian.security.nae.NAEParameterSpec in project CipherTrust_Application_Protection by thalescpl-io.

the class IngrianKeySample method main.

public static void main(String[] args) throws Exception {
    if (args.length != 4) {
        System.err.println("Usage: java IngrianKeySample user password keyname group");
        System.exit(-1);
    }
    String username = args[0];
    String password = args[1];
    String keyName = args[2];
    String group = args[3];
    // add Ingrian provider to the list of JCE providers
    Security.addProvider(new IngrianProvider());
    // get the list of all registered JCE providers
    Provider[] providers = Security.getProviders();
    for (Provider provider : providers) {
        System.out.println(provider.getInfo());
    }
    NAESession session = null;
    try {
        // Create AES key on NAE server
        // create NAE Session: pass in NAE user name and password
        session = NAESession.getSession(username, password.toCharArray());
        // set the key permissions to the set of permissions granted to NAE group.
        NAEPermission permission = new NAEPermission(group);
        // add permission to sign
        permission.setSign(true);
        // add permission to verify signature
        permission.setSignV(true);
        NAEPermission[] permissions = { permission };
        // create key pair which is exportable and deletable
        // key owner is NAE user, default key length 1024 bits and
        // permissions granted to sign and verify
        NAEParameterSpec rsaParamSpec = new NAEParameterSpec(keyName, true, true, session, permissions);
        // create key custom attributes
        CustomAttributes attrs = new CustomAttributes("Attr1", "abc");
        attrs.addAttribute("Attr2", "1234");
        // create key which is exportable, deletable and versioned,
        // with custom attributes,
        // key owner is passed in NAE user and  key length 128 bits
        NAEParameterSpec spec = new NAEParameterSpec(keyName, true, true, true, 128, attrs, session);
        KeyGenerator kg = KeyGenerator.getInstance("AES", "IngrianProvider");
        kg.init(spec);
        SecretKey secret_key = kg.generateKey();
        NAEKey key = NAEKey.getSecretKey(keyName, session);
        // Get default IV assiciated with this key
        String defaultIV = key.getDefaultIV();
        System.out.println("Key " + keyName + " has default IV " + defaultIV);
        // Modify custom attributes.
        // Create new attribute to add
        CustomAttributes newAttrs = new CustomAttributes("Attr3", "ABC");
        // Create list of attribute names to delete
        String[] dAttrs = { "Attr1" };
        key.modifyCustomAttributes(false, dAttrs, newAttrs);
        // Create a new version of the key
        int newVersion = key.generateVersion();
        // and couple more
        newVersion = key.generateVersion();
        newVersion = key.generateVersion();
        // retire version 1
        key.modifyVersion(1, "Retired");
        // restrict version 2
        key.modifyVersion(2, "Restricted");
        // get key instance
        NAEKey newKey = NAEKey.getSecretKey(keyName, session);
        // get custom attributes
        CustomAttributes attributes = newKey.getCustomAttributes();
        Hashtable attrTable = attributes.getAttributes();
        for (Enumeration e = attrTable.keys(); e.hasMoreElements(); ) {
            String name = (String) e.nextElement();
            String value = (String) attrTable.get(name);
            System.out.println("Key custom attribute - name: " + name + " : value: " + value);
        }
        if (newKey.isVersioned()) {
            System.out.println("\nKey " + newKey.getName() + " is versioned.");
        }
        System.out.println("Number of key versions: " + newKey.getAllKeyVersions());
        System.out.println("Number of active versions: " + newKey.getActiveKeyVersions());
        System.out.println("Number of restricted versions: " + newKey.getRestrictedKeyVersions());
        System.out.println("Number of retired versions: " + newKey.getRetiredKeyVersions());
        System.out.println("Key Version: " + newKey.getKeyVersion() + "\n");
        // get key info for all versions of this key
        KeyInfoData[] infoData = newKey.getKeyInfoData(true);
        System.out.println("Key data for each version");
        for (KeyInfoData element : infoData) {
            System.out.println("Key version: " + element.getKeyVersion());
            System.out.println("Key fingerprint: " + element.getFingerprint());
            System.out.println("Key State: " + element.getKeyVersionState());
            System.out.println("Key iv: " + element.getDefaultIV() + "\n");
        }
        session.logEvent("Created versioned key.");
        // export all versions of this key
        KeyExportData[] keyData = newKey.export(true);
        System.out.println("Exported key data for each version");
        for (KeyExportData element : keyData) {
            System.out.println("Exported Key version: " + element.getKeyVersion());
            System.out.println("Exported Key fingerprint: " + element.getFingerprint());
            System.out.println("Exported Key data: " + element.getKeyData() + "\n");
        }
        // import the key back. we can import the key only as a non-versioned key.
        NAEParameterSpec spec_import = new NAEParameterSpec(keyName + "Import", true, true, session);
        NAEKey.importKey(IngrianProvider.hex2ByteArray(keyData[2].getKeyData()), "AES", spec_import);
        NAESecretKey importKey = NAEKey.getSecretKey(keyName + "Import", session);
        System.out.println("Imported key data; Key " + importKey.getName() + " was created on NAE Server.\n");
        // encrypt data with all key versions
        NAEKey allKey = NAEKey.getSecretKey(keyName + "#all", session);
        String dataToEncrypt = "2D2D2D2D2D424547494E2050455253495354454E54204346EB17960";
        System.out.println("Data to encrypt \"" + dataToEncrypt + "\"");
        // get IV
        NAESecureRandom rng = new NAESecureRandom(session);
        byte[] iv = new byte[16];
        rng.nextBytes(iv);
        IvParameterSpec ivSpec = new IvParameterSpec(iv);
        // get a cipher
        Cipher encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "IngrianProvider");
        // initialize cipher to encrypt.
        encryptCipher.init(Cipher.ENCRYPT_MODE, allKey, ivSpec);
        // encrypt data
        // outbuf is an array of ciphertexts; the size of this array is number of key versions;
        // each ciphertext is the data encrypted by one version of the key:
        // result[0] is the data encrypted with the latest key version.
        byte[] outbuf = encryptCipher.doFinal(dataToEncrypt.getBytes());
        byte[][] result = IngrianProvider.encryptAllResult(outbuf);
        for (byte[] element : result) {
            System.out.println("Ciphertext " + IngrianProvider.byteArray2Hex(element));
        }
        Cipher decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "IngrianProvider");
        // decrypt ciphertext
        // init cipher
        NAEKey dKey = NAEKey.getSecretKey(keyName, session);
        decryptCipher.init(Cipher.DECRYPT_MODE, dKey, ivSpec);
        // will use correct key version from cipher text header
        byte[] newbuf = decryptCipher.doFinal(result[0]);
        System.out.println("Decrypted data  \"" + new String(newbuf) + "\"");
    } catch (Exception e) {
        System.out.println("The Cause is " + e.getMessage() + ".");
        e.printStackTrace();
    } finally {
        if (session != null) {
            session.closeSession();
        }
    }
}
Also used : NAEParameterSpec(com.ingrian.security.nae.NAEParameterSpec) NAEPermission(com.ingrian.security.nae.NAEPermission) NAEKey(com.ingrian.security.nae.NAEKey) KeyExportData(com.ingrian.security.nae.KeyExportData) IngrianProvider(com.ingrian.security.nae.IngrianProvider) CustomAttributes(com.ingrian.security.nae.CustomAttributes) KeyInfoData(com.ingrian.security.nae.KeyInfoData) KeyGenerator(javax.crypto.KeyGenerator) Enumeration(java.util.Enumeration) NAESecureRandom(com.ingrian.security.nae.NAESecureRandom) Hashtable(java.util.Hashtable) NAESecretKey(com.ingrian.security.nae.NAESecretKey) Provider(java.security.Provider) IngrianProvider(com.ingrian.security.nae.IngrianProvider) SecretKey(javax.crypto.SecretKey) NAESecretKey(com.ingrian.security.nae.NAESecretKey) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) NAESession(com.ingrian.security.nae.NAESession)

Example 20 with NAEParameterSpec

use of com.ingrian.security.nae.NAEParameterSpec in project CipherTrust_Application_Protection by thalescpl-io.

the class SecretKeySample method main.

public static void main(String[] args) throws Exception {
    if (args.length != 4) {
        System.err.println("Usage: java SecretKeySample user password keyname group");
        System.exit(-1);
    }
    String username = args[0];
    String password = args[1];
    String keyName = args[2];
    String group = args[3];
    // add Ingrian provider to the list of JCE providers
    Security.addProvider(new IngrianProvider());
    // get the list of all registered JCE providers
    Provider[] providers = Security.getProviders();
    for (int i = 0; i < providers.length; i++) System.out.println(providers[i].getInfo());
    NAESession session = null;
    try {
        // Create AES key on Key Manager
        // create NAE Session: pass in Key Manager user name and password
        session = NAESession.getSession(username, password.toCharArray());
        // create key which is exportable and deletable,
        // key owner is passed in Key Manager user and default key length 128 bits
        NAEParameterSpec spec = new NAEParameterSpec(keyName, true, true, session);
        KeyGenerator kg = KeyGenerator.getInstance("AES", "IngrianProvider");
        kg.init(spec);
        SecretKey secret_key = kg.generateKey();
        // Export key data
        NAEKey key = NAEKey.getSecretKey(keyName, session);
        byte[] keyData = key.export();
        System.out.println("Key " + key.getName() + " was created on Key Manager.");
        // Clone that key.
        key.cloneKey(keyName + "Cloned");
        key = NAEKey.getSecretKey(keyName + "Cloned", session);
        System.out.println("Key " + key.getName() + " was cloned on Key Manager.");
        // Delete that key from Key Manager
        key.delete();
        // Import that key back to the Key Manager
        // set the key permissions to the set of permissions granted to
        // NAE group.
        NAEPermission permission = new NAEPermission(group);
        // add permission to encrypt
        permission.setEncrypt(true);
        NAEPermission[] permissions = { permission };
        NAEParameterSpec spec_dup = new NAEParameterSpec(keyName + "Dup", true, true, session, permissions);
        NAEKey.importKey(keyData, "AES", spec_dup);
        key = NAEKey.getSecretKey(keyName + "Dup", session);
        System.out.println("Imported key data; Duplicate Key " + key.getName() + " was created on Key Manager.");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (session != null)
            session.closeSession();
    }
}
Also used : NAEParameterSpec(com.ingrian.security.nae.NAEParameterSpec) NAEKey(com.ingrian.security.nae.NAEKey) NAEPermission(com.ingrian.security.nae.NAEPermission) IngrianProvider(com.ingrian.security.nae.IngrianProvider) IngrianProvider(com.ingrian.security.nae.IngrianProvider) Provider(java.security.Provider) SecretKey(javax.crypto.SecretKey) KeyGenerator(javax.crypto.KeyGenerator) NAESession(com.ingrian.security.nae.NAESession)

Aggregations

NAEParameterSpec (com.ingrian.security.nae.NAEParameterSpec)25 IngrianProvider (com.ingrian.security.nae.IngrianProvider)17 KeyGenerator (javax.crypto.KeyGenerator)12 NAESession (com.ingrian.security.nae.NAESession)11 KMIPSession (com.ingrian.security.nae.KMIPSession)10 NAEClientCertificate (com.ingrian.security.nae.NAEClientCertificate)10 NAEKey (com.ingrian.security.nae.NAEKey)10 KMIPAttributes (com.ingrian.security.nae.KMIPAttributes)9 SecretKey (javax.crypto.SecretKey)7 NAEPublicKey (com.ingrian.security.nae.NAEPublicKey)6 NAESecretKey (com.ingrian.security.nae.NAESecretKey)6 KeyPair (java.security.KeyPair)6 Provider (java.security.Provider)6 NAEPermission (com.ingrian.security.nae.NAEPermission)5 NAEPrivateKey (com.ingrian.security.nae.NAEPrivateKey)5 NAEException (com.ingrian.security.nae.NAEException)4 KeyPairGenerator (java.security.KeyPairGenerator)4 PrivateKey (java.security.PrivateKey)4 PublicKey (java.security.PublicKey)4 Cipher (javax.crypto.Cipher)4