Developer's Guide
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
SymmetricKeyExample.java
package com.p6r.example12;
import java.io.IOException;
import java.security.Key;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class SymmetricKeyExampleForDisplay {
public SymmetricKeyExampleForDisplay() {
}
public static void main(String[] args) {
try {
// [A] Get the P6R PKCS#11 security provider keytstore
// -> "12345678" is the keystore's password (i.e., the PKCS#11 token's PIN)
// -> "SunPKCS11-P6RPKCS11" defines the security provider
KeyStore ks = KeyStore.getInstance("PKCS11", "SunPKCS11-P6RPKCS11");
ks.load(null, "12345678".toCharArray());
// [B] Generate the symmetric key and store it into a PKCS#11 keystore
generateSymmetricKey(ks);
System.out.println("\nSearch for new AES key:\n");
Key secretKey = ks.getKey("example12_symmetric_aes_128_key", null);
if (secretKey != null) {
System.out.println("Key with alias 'example12_symmetric_aes_key' found: " + secretKey.toString());
// use a simple initialization vector
byte[] iv = new byte[16];
for (int i = 0; i < iv.length; i++) iv[i] = 0x03;
// first encrypt the data using the AES key
// -> since we are using "NoPadding" the test data has to be a multiple of AES block size of 16 bytes, so we are doing our own padding
String testData = new String("Simple string to encrypt for example12 123456789");
byte[] cipherText = encryptData(secretKey, iv, "AES/CBC/NoPadding", testData.getBytes());
// second decrypt the result to verify we get the original string back
String clearText = decryptData(secretKey, iv, "AES/CBC/NoPadding", cipherText);
if (!testData.equalsIgnoreCase(clearText)) {
System.out.println("\noriginal string: [" + testData + "]\n");
System.out.println("mismatch decrypted string: [" + clearText + "]\n");
} else System.out.println("\ndecrypted data matches original data: " + clearText + "\n");
} else System.out.println("Key with alias 'example12_symmetric_aes_key' not found\n");
} catch (CertificateException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
}
}
private static byte[] encryptData(Key secretKey, byte[] iv, String handling, byte[] clearText) {
byte[] cipherText = null;
try {
// with no security provider do the encrypt locally
Cipher encryptCipher = Cipher.getInstance(handling); //, "SunPKCS11-P6RPKCS11");
SecretKeySpec encryptSpec = new SecretKeySpec(secretKey.getEncoded(), secretKey.getAlgorithm());
IvParameterSpec IV = new IvParameterSpec(iv);
encryptCipher.init(Cipher.ENCRYPT_MODE, encryptSpec, IV);
cipherText = encryptCipher.doFinal(clearText);
} catch (Exception e) {
e.printStackTrace();
}
return cipherText;
}
private static String decryptData(Key secretKey, byte[] iv, String handling, byte[] cipherText) {
byte[] clearText = null;
try {
// with no security provider do the decrypt locally
Cipher decryptCipher = Cipher.getInstance(handling); //, "SunPKCS11-P6RPKCS11");
SecretKeySpec encryptSpec = new SecretKeySpec(secretKey.getEncoded(), secretKey.getAlgorithm());
IvParameterSpec IV = new IvParameterSpec(iv);
decryptCipher.init(Cipher.DECRYPT_MODE, encryptSpec, IV);
clearText = decryptCipher.doFinal(cipherText);
} catch (Exception e) {
e.printStackTrace();
}
return new String(clearText);
}
private static void generateSymmetricKey(KeyStore ks) throws NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException {
KeyGenerator keyGen = KeyGenerator.getInstance("AES", "SunPKCS11-P6RPKCS11");
keyGen.init(128);
Key key = keyGen.generateKey();
System.out.println("Successfully created symmetric key: " + key.getAlgorithm() + "\n");
// replace an older key
if (ks.containsAlias("example12_symmetric_aes_128_key")) ks.deleteEntry("example12_symmetric_aes_128_key");
ks.setKeyEntry("example12_symmetric_aes_128_key", key, null, null);
}
}