use of com.ingrian.security.nae.NAESecureRandom in project CipherTrust_Application_Protection by thalescpl-io.
the class SecretKeyEncryptionSample method main.
public static void main(String[] args) throws Exception {
if (args.length != 3) {
System.err.println("Usage: java SecretKeyEncryptionSample user password keyname");
System.exit(-1);
}
String username = args[0];
String password = args[1];
String keyName = args[2];
// 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());
}
String dataToEncrypt = "2D2D2D2D2D424547494E2050455253495354454E54204346EB17960";
System.out.println("Data to encrypt \"" + dataToEncrypt + "\"");
NAESession session = null;
try {
// create NAE Session: pass in Key Manager user name and password
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);
// encrypt data
byte[] outbuf = encryptCipher.doFinal(dataToEncrypt.getBytes());
// get a cipher for decryption
Cipher decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "IngrianProvider");
// to decrypt data, initialize cipher to decrypt
decryptCipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
// decrypt data
byte[] newbuf = decryptCipher.doFinal(outbuf);
System.out.println("Decrypted data \"" + new String(newbuf) + "\"");
// to encrypt data in the loop
Cipher loopEncryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "IngrianProvider");
// initialize cipher to encrypt.
loopEncryptCipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
byte[] outbuffer = null;
for (int i = 0; i < 10; i++) {
// encrypt data in the loop
outbuffer = loopEncryptCipher.doFinal(dataToEncrypt.getBytes());
}
// to encrypt data in the loop
Cipher loopDecryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "IngrianProvider");
// to decrypt data in the loop
// initialize cipher to decrypt.
loopDecryptCipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
byte[] decrBuffer = null;
for (int i = 0; i < 10; i++) {
// decrypt data in the loop
decrBuffer = loopDecryptCipher.doFinal(outbuffer);
}
} catch (Exception e) {
System.out.println("The Cause is " + e.getMessage() + ".");
throw e;
} finally {
if (session != null) {
session.closeSession();
}
}
}
use of com.ingrian.security.nae.NAESecureRandom in project CipherTrust_Application_Protection by thalescpl-io.
the class KMIPCreateAndEncryptSample method main.
public static void main(String[] args) throws Exception {
if (args.length != 5) {
usage();
}
String keyName = args[4];
int keyLength = 256;
// add Ingrian provider to the list of JCE providers
Security.addProvider(new IngrianProvider());
KMIPSession kmipSession = null;
NAESession naeSession = null;
try {
// create KMIP Session - specify client X.509 certificate and keystore password
kmipSession = KMIPSession.getSession(new NAEClientCertificate(args[0], args[1].toCharArray()));
// create key custom attributes
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, kmipSession);
/* getUID() will throw an exception if the key does not exist */
if (key.getUID() != null) {
System.out.println("Deleting key " + keyName + " with UID=" + key.getUID());
key.delete();
}
} catch (NAEException missing) {
if (missing.getMessage().equals("Key not found on server.")) {
System.out.println("Key did not exist");
} else
throw missing;
}
/* create a secret key using KMIP JCE key generator */
KMIPAttributes initialAttributes = new KMIPAttributes();
initialAttributes.add(KMIPAttribute.CryptographicUsageMask, (int) (UsageMask.Encrypt.getValue() | UsageMask.Decrypt.getValue()));
Calendar c = Calendar.getInstance();
initialAttributes.addDate(KMIPAttribute.ActivationDate, c);
NAEParameterSpec spec = new NAEParameterSpec(keyName, keyLength, (KMIPAttributes) initialAttributes, kmipSession);
KeyGenerator kg = KeyGenerator.getInstance("AES", "IngrianProvider");
kg.init(spec);
SecretKey secretKey = kg.generateKey();
System.out.println("Created key " + ((NAEKey) secretKey).getName());
/* Once created, you may operate on the KMIP key. For example,
* add a KMIP group attribute to the KMIP - not required, just include
* as a sample of KMIP operations on the key */
KMIPAttributes ka = new KMIPAttributes();
ka.add(KMIPAttribute.ObjectGroup, 0, "group1");
secretKey = NAEKey.getSecretKey(keyName);
NAESecretKey sk = NAEKey.getSecretKey(keyName, kmipSession);
sk.addKMIPAttributes(ka);
/* Now use the NAEKey created for encryption using an NAESession
* to a Key Manager server. Essentially this is the same code as the
* SecretKeyEncryptionSample.java program
* Nothing new is required to use the KMIP-created key on the
* Key Manager server.
*/
// create NAE XML Session: pass in NAE user name and password
naeSession = NAESession.getSession(args[2], args[3].toCharArray());
// Get SecretKey (just a handle to it, key data does not leave the server
// Note: KMIP keys objects need to be re-retrieved on the XML session
key = NAEKey.getSecretKey(keyName, naeSession);
// get IV
NAESecureRandom rng = new NAESecureRandom(naeSession);
byte[] iv = new byte[16];
rng.nextBytes(iv);
IvParameterSpec ivSpec = new IvParameterSpec(iv);
// get a cipher
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "IngrianProvider");
// initialize cipher to encrypt.
cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
String dataToEncrypt = "2D2D2D2D2D424547494E2050455253495354454E54204346EB17960";
System.out.println("Data to encrypt \"" + dataToEncrypt + "\"");
// encrypt data
byte[] outbuf = cipher.doFinal(dataToEncrypt.getBytes());
// to decrypt data, initialize cipher to decrypt
cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
// decrypt data
byte[] newbuf = cipher.doFinal(outbuf);
System.out.println("Decrypted data \"" + new String(newbuf) + "\"");
} catch (Exception e) {
System.out.println("The Cause is " + e.getMessage() + ".");
e.printStackTrace();
} finally {
if (kmipSession != null)
kmipSession.closeSession();
if (naeSession != null)
naeSession.closeSession();
}
}
use of com.ingrian.security.nae.NAESecureRandom in project CipherTrust_Application_Protection by thalescpl-io.
the class FileEncryptionDecryptionSampleUsingRSA method main.
public static void main(String[] args) throws Exception {
if (args.length != 6) {
System.err.println("Usage: java FileEncryptionDecryptionSampleUsingRSA userName password asymKeyName fileToEncrypt encryptedFile decryptedFile");
System.exit(-1);
}
String userName = args[0];
String password = args[1];
String asymKeyName = args[2];
String fileToEncrypt = args[3];
String encryptedFile = args[4];
String decryptedFile = args[5];
// Add Ingrian provider to the list of JCE providers
Security.addProvider(new IngrianProvider());
NAESession session = null;
try {
// Creates NAE Session and pass in NAE userName and password
session = NAESession.getSession(userName, password.toCharArray());
// Creates NAEPublicKey object
NAEPublicKey asymPubKey = NAEKey.getPublicKey(asymKeyName, session);
// Get NAESecureRandom object
NAESecureRandom rng = new NAESecureRandom(session);
performEncryption(fileToEncrypt, encryptedFile, asymPubKey, rng);
// Creates NAEPrivateKey object
NAEPrivateKey asymPrivKey = NAEKey.getPrivateKey(asymKeyName, session);
performDecryption(encryptedFile, decryptedFile, asymPrivKey);
} catch (Exception e) {
System.err.println("The Cause is " + e.getMessage() + ".");
throw e;
} finally {
if (session != null) {
// Close NAESession
session.closeSession();
}
}
}
use of com.ingrian.security.nae.NAESecureRandom in project CipherTrust_Application_Protection by thalescpl-io.
the class FPEEncryptionDecryptionSample method main.
public static void main(String[] args) throws Exception {
if (args.length != 6) {
System.err.println("Usage: java FPEEncryptionDecryptionSample user password keyname IV TweakAlgorithm(Optional) TweakData(Optional)");
System.err.println("Mention null for optional parameter if you don't want to pass it");
/*
* Usage: keyname Supports AES Non-versioned key
* Usage: IV Must be 56 bytes Hex format string for AES key. IV must be of cardinality-10 that means each two characters (byte) of HEX IV must be 00-09
* IV must be provided when length of the data exceeds 56 bytes. FPE algorithm breaks the long data into 56 s-integer blocks and
* uses block chaining algorithm very similar to CBC mode to encrypt and chain the long data.
* when length of the data does not exceed MAXb value, the IV must be absent.
* Usage: TweakAlgorithm(Optional) must be from SHA1, SHA256 or None
* Usage: TweakData(Optional) If, tweak data algorithm is 'None' or absent,
the value must be HEX encoded string representing 64 bit long. In case of valid tweak Algorithm,
the tweak data value can be any ASCII string (not necessarily HEX).
Tweak Data is first processed using Tweak Hash Algorithm and the result is truncated to 64 bits
for input to the FPE algorithm
*/
System.exit(-1);
}
String username = args[0];
String password = args[1];
String keyName = args[2];
String _iv = args[3];
String tweakAlgo = null;
if (!args[4].contains("null")) {
tweakAlgo = args[4];
}
String tweakData = null;
if (!args[5].contains("null")) {
tweakData = args[5];
}
// 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());
}
String dataToEncrypt = "36253865463254715234987125394785127934571235487631254876512837451827635487123564875216384728347";
System.out.println("Data to encrypt \"" + dataToEncrypt + "\"");
NAESession session = null;
try {
// create NAE Session: pass in Key Manager user name and password
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);
byte[] iv = null;
NAESecureRandom rng;
iv = IngrianProvider.hex2ByteArray(_iv);
IvParameterSpec ivSpec = new IvParameterSpec(iv);
// Initializes IV and tweak parameters
NAEIvAndTweakDataParameter ivtweak = null;
ivtweak = new NAEIvAndTweakDataParameter(ivSpec, tweakData, tweakAlgo);
// get a cipher
Cipher encryptCipher = Cipher.getInstance("FPE/AES/CARD10", "IngrianProvider");
// initialize cipher to encrypt.
encryptCipher.init(Cipher.ENCRYPT_MODE, key, ivtweak);
// encrypt data
byte[] outbuf = encryptCipher.doFinal(dataToEncrypt.getBytes());
System.out.println("encrypted data data \"" + new String(outbuf) + "\"");
Cipher decryptCipher = Cipher.getInstance("FPE/AES/CARD10", "IngrianProvider");
// to decrypt data, initialize cipher to decrypt
decryptCipher.init(Cipher.DECRYPT_MODE, key, ivtweak);
// decrypt data
byte[] newbuf = decryptCipher.doFinal(outbuf);
System.out.println("Decrypted data \"" + new String(newbuf) + "\"");
// close the session
session.closeSession();
} catch (Exception e) {
System.out.println("The Cause is " + e.getMessage() + ".");
throw e;
} finally {
if (session != null) {
session.closeSession();
}
}
}
use of com.ingrian.security.nae.NAESecureRandom 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();
}
}
}
Aggregations