use of com.ingrian.security.nae.NAESecretKey in project CipherTrust_Application_Protection by thalescpl-io.
the class KMIPModifySample method main.
public static void main(String[] args) throws Exception {
if (args.length != 2) {
usage();
}
// 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());
KMIPSession session = null;
try {
// create a KMIPSession: pass in NAE client X.509 key and keyStore password
session = KMIPSession.getSession(new NAEClientCertificate(args[0], args[1].toCharArray()));
// create key KMIPAttribute object with a list of attributes to match
Set<String> managedObjectIdentifiers;
KMIPAttributes locateAttributes = new KMIPAttributes();
locateAttributes.add(KMIPAttribute.CryptographicAlgorithm, Algorithm.rsa);
locateAttributes.add(KMIPAttribute.CryptographicLength, 2048);
KMIPAttributes getAttributes = new KMIPAttributes();
getAttributes.add(KMIPAttribute.Name);
managedObjectIdentifiers = session.locate(locateAttributes);
if (managedObjectIdentifiers != null) {
System.out.println("\n\nFound " + managedObjectIdentifiers.size() + " managed objects matching criteria.");
System.out.println("\n\nKeys with attributes rsa, 2048 and object group");
for (String uid : managedObjectIdentifiers) {
System.out.println("\n\nManaged Object UniqueIdentifier: \t" + uid);
Object managedObject = session.getManagedObject(uid);
// not a key
if (managedObject == null)
continue;
if ((managedObject instanceof NAEPublicKey) || (managedObject instanceof NAEPrivateKey) || (managedObject instanceof NAESecretKey)) {
NAEKey key;
if (managedObject instanceof NAEPublicKey)
key = (NAEPublicKey) managedObject;
else if (managedObject instanceof NAEPrivateKey)
key = (NAEPrivateKey) managedObject;
else
key = (NAESecretKey) managedObject;
System.out.println("\tName: \t" + key.getName());
// Retrieve a KMIP attribute - in this case, Name.
KMIPAttributes returnedAttributes = key.getKMIPAttributes(getAttributes);
KMIPNameAttribute name = returnedAttributes.getNameAttribute();
System.out.println("Name attribute: " + name.getNameValue().getNameValue());
// Modify the Application Specific Information for this key - if it has any
KMIPAttributes modAttributes = new KMIPAttributes();
String ts = timestamp();
modAttributes.add(new KMIPApplicationSpecificInformation("namespace-" + ts, ts), 0);
try {
// throws NAE error if the key does not already have attribute being modified
key.modifyKMIPAttributes(modAttributes);
} catch (NAEException nae) {
if (!nae.getMessage().contains("Object does not have the specified attribute"))
throw nae;
}
} else if (managedObject instanceof KMIPSecretData) {
System.out.println(((KMIPSecretData) managedObject).getName());
}
}
}
} catch (Exception e) {
System.out.println("The Cause is " + e.getMessage() + ".");
e.printStackTrace();
} finally {
if (session != null)
session.closeSession();
}
}
use of com.ingrian.security.nae.NAESecretKey in project CipherTrust_Application_Protection by thalescpl-io.
the class ByokSample method wrapKeyFromKS.
private static byte[] wrapKeyFromKS(String username, String password, String aesKeyName, String wrappingKeyName, String wrappingAlgo, byte[] publicKey, String cloudName, String hash256Path) throws Exception {
String pemString = null;
if (publicKey != null) {
PemObject pemObject = new PemObject("RSA PUBLIC KEY", publicKey);
StringWriter stringWriter = new StringWriter();
PemWriter pemWriter = new PemWriter(stringWriter);
pemWriter.writeObject(pemObject);
pemWriter.close();
pemString = stringWriter.toString();
}
NAESession session = null;
try {
// create nae session
session = NAESession.getSession(username, password.toCharArray());
NAESecretKey secretKey = NAEKey.getSecretKey(aesKeyName, session);
if (isKeyNameValid(secretKey))
validateKeySize(secretKey, 256);
else {
createAES256Key(aesKeyName, session);
secretKey = NAEKey.getSecretKey(aesKeyName, session);
}
// Need not import if publicKey is null
if (publicKey != null) {
// key import spec
NAEParameterSpec rsaParamSpec = new NAEParameterSpec(wrappingKeyName, true, true, session, null);
// import the rsa public key
NAEPublicKey.importKey(pemString.getBytes("UTF-8"), "RSA", rsaParamSpec);
}
// get key handle to the imported RSA key
NAEPublicKey pubRSAKey = NAEKey.getPublicKey(wrappingKeyName, session);
// spec for key to be wrapped
NAEParameterSpec aesSpec = new NAEParameterSpec(aesKeyName, true, true, 256, session);
// setting padding format to wrap a key
aesSpec.setWrapPaddingFormat("PKCS1.5".equals(wrappingAlgo.toUpperCase()) ? WrapFormatPadding.DEFAULT : WrapFormatPadding.valueOf(wrappingAlgo.toUpperCase()));
// Init a JCE Cipher in WRAP_MODE to do the key wrapping.
Cipher cipher = Cipher.getInstance("RSA", "IngrianProvider");
cipher.init(Cipher.WRAP_MODE, pubRSAKey, aesSpec);
byte[] wrappedByte = cipher.wrap(secretKey);
// write hash
if (cloudName.equalsIgnoreCase("salesforce")) {
writeHashToTheFile(cloudName, secretKey.getKeyData(), hash256Path);
}
return wrappedByte;
} finally {
if (session != null)
session.closeSession();
}
}
use of com.ingrian.security.nae.NAESecretKey in project CipherTrust_Application_Protection by thalescpl-io.
the class KMIPBatchSample method main.
public static void main(String[] args) throws Exception {
KMIPSession session = null;
int keyLength = 256;
if (args.length != 3) {
usage();
}
String keyName = args[2];
// add Ingrian provider to the list of JCE providers
Security.addProvider(new IngrianProvider());
try {
// create KMIP Session - specify client X.509 certificate and keystore password
session = KMIPSession.getSession(new NAEClientCertificate(args[0], args[1].toCharArray()));
// create key custom attributes
session.startBatching();
System.out.println("Batching set to " + session.isBatching());
for (int i = 0; i < 10; i++) {
/* create a secret key using JCE key generator */
NAEParameterSpec spec = new NAEParameterSpec(keyName + "-" + i, keyLength, (KMIPAttributes) null, session);
KeyGenerator kg = KeyGenerator.getInstance("AES", "IngrianProvider");
kg.init(spec);
kg.generateKey();
}
KMIPBatchResults kbr = session.flushBatch();
for (KMIPBatchItemResult batchResult : kbr.values()) {
if (batchResult.getStatus() == Statuses.Success) {
System.out.println(batchResult.getOperation().getPrintName() + " : " + batchResult.getStatus().getPrintName());
System.out.println("UIDs affected: " + batchResult.getUIDs());
} else {
System.out.println(batchResult.getOperation().getPrintName() + " OPERATION FAILED: " + batchResult.getStatusMessage());
}
}
System.out.println("Batching set to " + session.isBatching());
// the KMIPsession is now not in batching mode. KMIP Operations will be sent
// to the server when the line of code is executed. Operations are shown
// which add, modify, or delete attributes in one request, with the KMIP CADP for JAVA
// session utilizing KMIP batching implicitly based on sets of UIDs
KMIPAttributes queryAttributes = new KMIPAttributes();
queryAttributes.add(KMIPAttribute.CryptographicAlgorithm, Algorithm.aes);
queryAttributes.add(KMIPAttribute.CryptographicLength, 256);
// Have the session locate the keys matching the queryAttributes:
Set<String> managedObjectIdentifiers = session.locate(queryAttributes);
// loop through the UIDs of the matching managed objects
KMIPAttributes addAttrs = new KMIPAttributes();
addAttrs.add(KMIPAttribute.ContactInformation, 0, "Contact Information");
for (String uid : managedObjectIdentifiers) {
System.out.println("Managed object Unique Identifier: " + uid);
// get the objects as Java client NAEKeys or KMIPSecretData objects
// (Note: Secret Data doesn't have KMIP attributes of
// algorithm or length, and will not be found by this query,
// but is included here for completeness.
Object managedObject = session.getManagedObject(uid);
if (managedObject instanceof NAESecretKey) {
NAESecretKey nsk = (NAESecretKey) managedObject;
nsk.refreshKMIPInfo();
if (nsk.getName().startsWith("KMIPBatch")) {
System.out.println(((NAESecretKey) managedObject).getName());
}
nsk.addKMIPAttributes(addAttrs);
}
}
waitForInput();
KMIPAttributes modAttrs = new KMIPAttributes();
modAttrs.add(KMIPAttribute.ContactInformation, 0, "Modified Contact Information");
Set<String> modUIDs = session.modifyAllAttributes(managedObjectIdentifiers, modAttrs);
System.out.println("Modified " + modUIDs.size() + " attributes in a single request.");
waitForInput();
Set<String> delUIDs = session.deleteAll(new ArrayList<String>(managedObjectIdentifiers));
System.out.println("Deleted " + delUIDs.size() + " managed objects in a single request.");
} catch (Exception e) {
System.out.println("The Cause is " + e.getMessage() + ".");
e.printStackTrace();
} finally {
if (session != null)
session.closeSession();
}
}
use of com.ingrian.security.nae.NAESecretKey in project CipherTrust_Application_Protection by thalescpl-io.
the class KMIPCertLocateSample method main.
public static void main(String[] args) throws Exception {
if (args.length != 3) {
usage();
}
// add Ingrian provider to the list of JCE providers
Security.addProvider(new IngrianProvider());
KMIPSession session = null;
try {
// create NAE Session: pass in NAE Client Certificate clicnt key and keystore password
session = KMIPSession.getSession(new NAEClientCertificate(args[0], args[1].toCharArray()));
// import the certificate
NAEParameterSpec spec = new NAEParameterSpec(args[2], 1024, (KMIPAttributes) null, session);
byte[] c = Hex.decodeHex(certBytes.toCharArray());
NAECertificate.importCertificate(c, null, spec);
// This set holds the managed object unique identifiers (UIDs)
Set<String> managedObjectIdentifiers;
// Locate managed objects with ObjectType Certificate and crypto length = 2048
// and Issuer Distinguished Name = "CN=KMIP,OU=OASIS,O=TEST,C=US"
// by adding the KMIPAttribute name and the value to a KMIPAttributes
// object
KMIPAttributes queryAttributes = new KMIPAttributes();
queryAttributes.add(KMIPAttribute.CryptographicLength, 2048);
queryAttributes.add(KMIPAttribute.ObjectType, ObjectType.ObjectTypes.Certificate);
// Have the session locate the keys matching the queryAttributes:
managedObjectIdentifiers = session.locate(queryAttributes);
System.out.println("Managed objects with attributes rsa, 2048:");
for (String uid : managedObjectIdentifiers) {
System.out.println("Managed object Unique Identifier: " + uid);
// get the objects as Java client NAEKeys or KMIPSecretData objects
// (Note: Secret Data doesn't have KMIP attributes of
// algorithm or length, and will not be found by this query,
// but is included here for completeness.
Object managedObject = session.getManagedObject(uid);
if (managedObject instanceof KMIPTemplate)
break;
if (managedObject instanceof NAEPublicKey)
System.out.println(((NAEPublicKey) managedObject).getName());
else if (managedObject instanceof NAEPrivateKey)
System.out.println(((NAEPrivateKey) managedObject).getName());
else if (managedObject instanceof NAESecretKey)
System.out.println(((NAESecretKey) managedObject).getName());
else if (managedObject instanceof KMIPSecretData) {
System.out.println(((KMIPSecretData) managedObject).getName());
} else if (managedObject instanceof NAECertificate) {
System.out.println("Object is a certificate");
System.out.println(((NAECertificate) managedObject).getName());
}
}
} catch (Exception e) {
System.out.println("The Cause is " + e.getMessage() + ".");
e.printStackTrace();
} finally {
if (session != null)
session.closeSession();
}
}
use of com.ingrian.security.nae.NAESecretKey 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