import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import javax.xml.bind.DatatypeConverter; import com.netegrity.policyserver.smapi.*; public class ActiveResponseSample implements ActiveExpression { private final String key = "Bar12345Bar12345"; // 128 bit key private final String initVector = "RandomInitVector"; // 16 bytes IV public int init(APIContext context) throws Exception { // This example needs no initialization so just return "success" return 0; } public String invoke(ActiveExpressionContext context, String param) throws Exception { if (context == null) { throw new IllegalArgumentException("ActiveResponseSample invoked without context"); } APIContext apicontxt=context.getAPIContext(); apicontxt.trace("Got user context successfully", ""); UserContext theUserContext = context.getUserContext(); apicontxt.trace("Trying to get User Context", ""); if (theUserContext == null) { context.setErrorText("No User Context."); return null; } // Get all the organizational units to which the user belongs. String userName = theUserContext.getUserName(); apicontxt.trace("Retrieved "+ userName , "using User Context"); apicontxt.trace("Trying to do Encryption" ,""); return encrypt(key, initVector, userName); } public int release(APIContext context) throws Exception { // This example needs no shutdown so just return "success" return 0; } public static String encrypt(String key, String initVector, String value) { try { IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8")); SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); byte[] encrypted = cipher.doFinal(value.getBytes()); System.out.println("encrypted string: " + DatatypeConverter.printBase64Binary(encrypted)); return DatatypeConverter.printBase64Binary(encrypted); } catch (Exception ex) { ex.printStackTrace(); } return null; } public static String decrypt(String key, String initVector, String encrypted) { try { IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8")); SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); byte[] original = cipher.doFinal( DatatypeConverter.parseBase64Binary(encrypted)); return new String(original); } catch (Exception ex) { ex.printStackTrace(); } return null; } } // end of file ActiveResponseSample.java