use of com.ingrian.security.nae.NAESession in project CipherTrust_Application_Protection by thalescpl-io.
the class KeyNameSample method main.
public static void main(String[] args) {
/**
* KeyName api if used with valid Key Manager user name and password then it
* fetches all the keys names belongs to the user and global keys
* as per the attribute passed. Please read Javadoc for their value.
*/
if (args.length > 14) {
System.err.println("Usage: java KeyNameSample -user [userName] -password [password] -attr [attributName]" + "-attrV [attributeValue] -fingerprint [fingerprint] -offset [keyOffset] -max [maxKeys]");
System.exit(-1);
}
String username = null;
String password = null;
String attributeName = null;
String attributeValue = null;
String fingerprint = null;
int offset = 0;
// maximum key needs to be fetched should be atleast 1
int max = 1;
// extracting values from the given input argument. May have null values.
for (int i = 0; i < args.length; i++) {
if ("-user".equals(args[i]))
username = args[i + 1];
else if ("-password".equals(args[i]))
password = args[i + 1];
else if ("-attr".equals(args[i]))
attributeName = args[i + 1];
else if ("-attrV".equals(args[i]))
attributeValue = args[i + 1];
else if ("-fingerprint".equals(args[i]))
fingerprint = args[i + 1];
else if ("-offset".equals(args[i]))
offset = Integer.parseInt(args[i + 1]);
else if ("-max".equals(args[i]))
max = Integer.parseInt(args[i + 1]);
}
if (username != null && password != null) {
NAESession session = null;
try {
session = NAESession.getSession(username, password.toCharArray());
CustomAttributes attr = new CustomAttributes();
if (attributeValue != null) {
attr.addAttributeForKeyName(attributeName, attributeValue);
attr.addAttributeForKeyName(attributeName + "-1", attributeValue);
}
UserKeysDetail keyNames = NAEKey.getKeyNames(attr, fingerprint, offset, max, session, ConjunctiveOperator.OR);
System.out.println("Key count: " + keyNames.getKeyCount());
System.out.println("Total Keys: " + keyNames.getTotalKeys());
System.out.println("KeyNames: " + keyNames.getKeyNames());
System.out.println("#####################");
} finally {
if (session != null)
session.closeSession();
}
} else {
// In this case all the global keys are fetched through global
// session.
System.out.println("Global Keys are: ");
UserKeysDetail keyNames = NAEKey.getKeyNames(null);
System.out.println("Key count: " + keyNames.getKeyCount());
System.out.println("Total Keys: " + keyNames.getTotalKeys());
System.out.println("KeyNames: " + keyNames.getKeyNames());
}
}
use of com.ingrian.security.nae.NAESession 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();
}
}
use of com.ingrian.security.nae.NAESession 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();
}
}
}
use of com.ingrian.security.nae.NAESession 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();
}
}
use of com.ingrian.security.nae.NAESession in project CipherTrust_Application_Protection by thalescpl-io.
the class Hello method doGet.
/**
* Respond to a GET request for the content produced by
* this servlet.
*
* @param request The servlet request we are processing
* @param response The servlet response we are producing
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<html>");
writer.println("<head>");
writer.println("<title>Sample Application Servlet Page</title>");
writer.println("</head>");
writer.println("<body bgcolor=white>");
writer.println("<table border=\"0\">");
writer.println("<tr>");
writer.println("<td>");
writer.println("<img src=\"images/key_hole.gif\">");
writer.println("</td>");
writer.println("<td>");
writer.println("<h1>Sample Application Servlet</h1>");
writer.println("</td>");
writer.println("<a href=\"reqparams.html\">");
writer.println("<img src=\"images/code.gif\" height=24 " + "width=24 align=right border=0 alt=\"view code\"></a>");
writer.println("<a href=\"index.html\">");
writer.println("<img src=\"images/return.gif\" height=24 " + "width=24 align=right border=0 alt=\"return\"></a>");
String userName = request.getParameter("username");
String password = request.getParameter("password");
String keyName = request.getParameter("keyname");
writer.println("Parameters in this request: " + "<br>");
if (userName != null && password != null && keyName != null) {
writer.println("User Name ");
writer.println(" = " + HTMLFilter.filter(userName) + "<br>");
writer.println("Password ");
writer.println(" = " + HTMLFilter.filter(password) + "<br>");
writer.println("Key Name ");
writer.println(" = " + HTMLFilter.filter(keyName) + "<br>");
} else {
writer.println("No Parameters, Please enter some");
}
writer.println("<P>");
writer.print("<form action=\"");
writer.print("Hello\"");
writer.println("method=POST>");
writer.println("User Name: ");
writer.println("<input type=text size=20 name=username>");
writer.println("<br>");
writer.println("Password: ");
writer.println("<input type=text size=20 name=password>");
writer.println("<br>");
writer.println("Key Name: ");
writer.println("<input type=text size=20 name=keyname>");
writer.println("<br>");
writer.println("<input type=submit>");
writer.println("</form>");
writer.println("</tr>");
writer.println("</table>");
if (userName != null && password != null && keyName != null) {
writer.println("<table border=\"0\">");
writer.println("<tr>");
writer.println("<td>");
writer.println("Start encryption.");
writer.println("<br>");
NAESession session = null;
try {
session = NAESession.getSession(userName, password);
NAESecretKey key = NAEKey.getSecretKey(keyName, session);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "IngrianProvider");
byte[] IV = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
IvParameterSpec IVSPEC = new IvParameterSpec(IV);
cipher.init(Cipher.ENCRYPT_MODE, key, IVSPEC);
String data = "Hello servlet. ";
byte[] inbuf = data.getBytes();
writer.println("Provider: " + Security.getProvider("IngrianProvider"));
writer.println("<br>");
writer.println(" Data to encrypt: " + data);
writer.println("<br>");
writer.println(" Encryption algorithm: " + key.getAlgorithm());
writer.println("<br>");
byte[] outbuf = cipher.doFinal(inbuf);
writer.println(" Encrypted data: " + outbuf);
writer.println("<br>");
cipher.init(Cipher.DECRYPT_MODE, key, IVSPEC);
byte[] newbuf = cipher.doFinal(outbuf);
String data_new = new String(newbuf);
writer.println(" Decrypted data: " + data_new);
writer.println("<br>");
} catch (NoSuchAlgorithmException exc) {
throw new IOException("No such alg. " + exc.getMessage());
} catch (NoSuchProviderException exc) {
throw new IOException("No such provider. " + exc.getMessage());
} catch (NoSuchPaddingException exc) {
throw new IOException("No such pad. " + exc.getMessage());
} catch (InvalidKeyException exc) {
throw new IOException("Invalid key. " + exc.getMessage());
} catch (InvalidAlgorithmParameterException exc) {
throw new IOException("Invalid alg params. " + exc.getMessage());
} catch (IllegalBlockSizeException exc) {
throw new IOException("Illegal block size. " + exc.getMessage());
} catch (BadPaddingException exc) {
throw new IOException("Bad Padding. " + exc.getMessage());
} finally {
if (session != null) {
session.closeSession();
}
}
writer.println(" Finish encryption.");
Provider[] providers = Security.getProviders();
writer.println("<h3> Registered providers: </h3>");
for (int i = 0; i < providers.length; i++) {
writer.println("<tr>");
writer.println(" <th align=\"right\">" + providers[i].toString() + "</th>");
writer.println("</tr>");
}
writer.println("</td>");
writer.println("</tr>");
writer.println("</table>");
}
writer.println("</body>");
writer.println("</html>");
}
Aggregations