Search in sources :

Example 36 with IngrianProvider

use of com.ingrian.security.nae.IngrianProvider 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 37 with IngrianProvider

use of com.ingrian.security.nae.IngrianProvider 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)

Example 38 with IngrianProvider

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

the class KMIPSecretDataGetCustomAttributeSample method main.

public static void main(String[] args) throws Exception {
    if (args.length != 4) {
        usage();
    }
    // add Ingrian provider to the list of JCE providers
    Security.addProvider(new IngrianProvider());
    String secretDataName = args[2];
    String custattrib = args[3];
    // create NAE Session: pass in Key Manager user name and password
    KMIPSession session = KMIPSession.getSession(new NAEClientCertificate(args[0], args[1].toCharArray()));
    KMIPAttributes getAttributes = new KMIPAttributes();
    if (custattrib.contains("#")) {
        String[] attrs = custattrib.split("#");
        for (String atr : attrs) {
            getAttributes.add(atr);
        }
    } else {
        getAttributes.add(custattrib);
    }
    try {
        // create the secret data object as a KMIP secret data Password type
        KMIPSecretData secretDataManagedObject = new KMIPSecretData(secretDataName, KMIPSecretData.SecretDataType.Password, session);
        KMIPAttributes returnedAttributes = secretDataManagedObject.getKMIPAttributes(getAttributes);
        printCustomAttribute(returnedAttributes);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (session != null)
            session.closeSession();
    }
}
Also used : KMIPAttributes(com.ingrian.security.nae.KMIPAttributes) KMIPSecretData(com.ingrian.security.nae.KMIPSecretData) NAEClientCertificate(com.ingrian.security.nae.NAEClientCertificate) IngrianProvider(com.ingrian.security.nae.IngrianProvider) KMIPSession(com.ingrian.security.nae.KMIPSession)

Example 39 with IngrianProvider

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

the class KMIPWrapUnwrapSample method main.

public static void main(String[] args) {
    if (args.length != 4) {
        usage();
    }
    // add Ingrian provider to the list of JCE providers
    Security.addProvider(new IngrianProvider());
    String wrapping_key = args[2];
    String wrapped_key = args[3];
    // key bytes
    String wrapping_keybytes = "49E3BD09F079E4F8842F1C6620FFF6EC";
    String wrapped_keybytes = "92F6355221CC38DF5F374275631C774D";
    System.out.println("wrapped_keybytes Key-1 " + wrapped_keybytes);
    System.out.println("wrapping_keybytes Key-2" + wrapping_keybytes);
    // key specification and key wrapping data
    String wrappingMethod = "Encrypt";
    String uniqueIdentifier_wrappingkey = null;
    String uniqueIdentifier_wrappedkey = null;
    String blockCipherMode = "NISTKeyWrap";
    // not required as of now
    String paddingMethod = null;
    // not required as of now
    String hashingAlgorithm = null;
    // not required as of now
    String keyRoleType = null;
    String encodingOption = "NoEncoding";
    // initiate KMIP session
    KMIPSession session = KMIPSession.getSession(new NAEClientCertificate(args[0], args[1].toCharArray()));
    // KMIP attributes for to declare an encrypting key
    KMIPAttributes initialAttribute = new KMIPAttributes();
    initialAttribute.add(KMIPAttribute.CryptographicUsageMask, (int) (UsageMask.WrapKey.getValue() | UsageMask.UnwrapKey.getValue()));
    // KMIP attribute to declare a plain key
    KMIPAttributes initialAttributes2 = new KMIPAttributes();
    initialAttributes2.add(KMIPAttribute.CryptographicUsageMask, (int) (UsageMask.Encrypt.getValue() | UsageMask.Decrypt.getValue()));
    NAEParameterSpec spec = new NAEParameterSpec(wrapping_key, 128, initialAttribute, (KMIPSession) session);
    NAEParameterSpec spec2 = new NAEParameterSpec(wrapped_key, 128, initialAttributes2, (KMIPSession) session);
    NAEKey key3 = NAEKey.getSecretKey(wrapping_key, session);
    NAEKey key4 = NAEKey.getSecretKey(wrapped_key, session);
    // register wrapping key
    try {
        uniqueIdentifier_wrappingkey = key3.registerKey(IngrianProvider.hex2ByteArray(wrapping_keybytes), algorithm, keyFormat, spec);
    } catch (NAEException e) {
        if (e.getMessage().contains("Key already exists")) {
            System.out.println("this key already exist");
            try {
                // updating UID for wrapping key
                uniqueIdentifier_wrappingkey = key3.getUID();
            } catch (NAEException e1) {
                e1.printStackTrace();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }
    // register wrapped key
    try {
        uniqueIdentifier_wrappedkey = key4.registerKey(IngrianProvider.hex2ByteArray(wrapped_keybytes), algorithm, keyFormat, spec2);
    } catch (NAEException e) {
        if (e.getMessage().contains("Key already exists")) {
            System.out.println("this key already exist");
            try {
                // updating UID for wrapped key
                uniqueIdentifier_wrappedkey = key4.getUID();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }
    // KMIP attribute to get a wrapped key
    KMIPAttributes initialAttributes1 = new KMIPAttributes();
    initialAttributes1.add(new KMIPKeyWrapSpecification(wrappingMethod, uniqueIdentifier_wrappingkey, blockCipherMode, paddingMethod, hashingAlgorithm, keyRoleType, encodingOption), 0);
    // Getting wrapped key bytes
    byte[] x = session.wrapKey(wrapped_key, initialAttributes1);
    System.out.println("Encrypted key bytes Key 1 " + IngrianProvider.byteArray2Hex(x));
    // KMIP attribute to register a new key using encrypted key bytes
    KMIPAttributes unwrapAttribute = new KMIPAttributes();
    unwrapAttribute.add(new KMIPKeyWrappingData(wrappingMethod, uniqueIdentifier_wrappingkey, blockCipherMode, paddingMethod, hashingAlgorithm, keyRoleType, encodingOption), 0);
    unwrapAttribute.add(KMIPAttribute.CryptographicUsageMask, (int) (UsageMask.Encrypt.getValue() | UsageMask.Decrypt.getValue()));
    String new_unwrapkeyuid = null;
    // register a new key using wrapped key bytes
    try {
        new_unwrapkeyuid = session.registerKey(x, algorithm, null, length, unwrapAttribute);
    } catch (NAEException e) {
        if (e.getMessage().contains("Key already exists"))
            System.out.println("this key already exist");
    }
    // Getting plain key bytes of new key
    System.out.println("Plain key bytes of Key-3 " + IngrianProvider.byteArray2Hex(session.getKeyBytes(new_unwrapkeyuid)));
    session.closeSession();
}
Also used : KMIPAttributes(com.ingrian.security.nae.KMIPAttributes) NAEParameterSpec(com.ingrian.security.nae.NAEParameterSpec) NAEException(com.ingrian.security.nae.NAEException) NAEKey(com.ingrian.security.nae.NAEKey) KMIPKeyWrapSpecification(com.ingrian.security.nae.KMIPKeyWrapSpecification) KMIPKeyWrappingData(com.ingrian.security.nae.KMIPKeyWrappingData) 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 40 with IngrianProvider

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

the class FileEncryptionSample method main.

public static void main(String[] args) throws Exception {
    if (args.length != 6) {
        System.err.println("Usage: java FileEncryptionSample user password keyname fileToEncrypt encryptedFile decryptedFile");
        System.exit(-1);
    }
    String username = args[0];
    String password = args[1];
    String keyName = args[2];
    String srcName = args[3];
    String dstName = args[4];
    String decrName = args[5];
    // how many bytes of data to read from the input stream - can be any size
    int BUFSIZE = 512;
    // 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());
    }
    // create NAE Session: pass in Key Manager user name and password
    NAESession session = null;
    try {
        session = NAESession.getSession(username, password.toCharArray());
        // Get SecretKey (just a handle to it, key data does not leave the Key Manager
        NAEKey key = NAEKey.getSecretKey(keyName, session);
        // 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, key, ivSpec);
        // create CipherInputStream that will read in data from file and encrypt it
        CipherInputStream cis = new CipherInputStream(new FileInputStream(srcName), encryptCipher);
        FileOutputStream fos = new FileOutputStream(dstName);
        // Read the file as blocks of data
        byte[] inbuf = new byte[BUFSIZE];
        for (int inlen = 0; (inlen = cis.read(inbuf)) != -1; ) {
            fos.write(inbuf, 0, inlen);
        }
        System.out.println("Done encrypting file.  Closing files");
        cis.close();
        fos.close();
        Cipher decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "IngrianProvider");
        // initialize cipher to decrypt.
        decryptCipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
        // create CipherInputStream that will read in data from file and decrypt it
        cis = new CipherInputStream(new FileInputStream(dstName), decryptCipher);
        fos = new FileOutputStream(decrName);
        for (int inlen = 0; (inlen = cis.read(inbuf)) != -1; ) {
            fos.write(inbuf, 0, inlen);
        }
        System.out.println("Done decrypting file.  Closing files");
        cis.close();
        fos.close();
    } catch (Exception e) {
        System.out.println("The Cause is " + e.getMessage() + ".");
        throw e;
    } finally {
        if (session != null) {
            session.closeSession();
        }
    }
}
Also used : NAEKey(com.ingrian.security.nae.NAEKey) NAESecureRandom(com.ingrian.security.nae.NAESecureRandom) CipherInputStream(javax.crypto.CipherInputStream) FileInputStream(java.io.FileInputStream) IngrianProvider(com.ingrian.security.nae.IngrianProvider) IngrianProvider(com.ingrian.security.nae.IngrianProvider) Provider(java.security.Provider) FileOutputStream(java.io.FileOutputStream) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) NAESession(com.ingrian.security.nae.NAESession)

Aggregations

IngrianProvider (com.ingrian.security.nae.IngrianProvider)45 NAESession (com.ingrian.security.nae.NAESession)27 NAEKey (com.ingrian.security.nae.NAEKey)25 KMIPSession (com.ingrian.security.nae.KMIPSession)19 NAEClientCertificate (com.ingrian.security.nae.NAEClientCertificate)19 Provider (java.security.Provider)19 NAEParameterSpec (com.ingrian.security.nae.NAEParameterSpec)17 NAEPrivateKey (com.ingrian.security.nae.NAEPrivateKey)17 NAEPublicKey (com.ingrian.security.nae.NAEPublicKey)17 KMIPAttributes (com.ingrian.security.nae.KMIPAttributes)16 KeyGenerator (javax.crypto.KeyGenerator)11 Cipher (javax.crypto.Cipher)10 NAEException (com.ingrian.security.nae.NAEException)9 KMIPSecretData (com.ingrian.security.nae.KMIPSecretData)8 NAESecretKey (com.ingrian.security.nae.NAESecretKey)8 SecretKey (javax.crypto.SecretKey)8 IvParameterSpec (javax.crypto.spec.IvParameterSpec)7 NAESecureRandom (com.ingrian.security.nae.NAESecureRandom)6 KeyPair (java.security.KeyPair)6 NAEPermission (com.ingrian.security.nae.NAEPermission)5