Using Java code in ColdFusion

This was, until just recently, unexplored territory. I knew that it could be done, that other people had done it before, and that it was darn easy to do in ColdFusion.

I have spent the last two weeks on a very intensive integration project where there was a custom UI built in JSP that needed to have a single sign-on from an existing ColdFusion application. We decided to take advantage of some of the session variables available, the catch being that the information in the session variables were encrypted (using the ColdFusion en/decrypt functions... naturally). I figured that "it couldn't be that hard" to replicate the same functionality in JSP, get the session variable... decrypt it... look the info up in the database... and set some application variables on the JSP application side. That was two weeks ago. Yesterday I figured it all out in a blinding burst of code.

What I ended up doing was writing an entire custom Java class that does all the encryption / decryption of string information passed to it. We had to instantiate the class on the ColdFusion side and not use the built in CF functions.

And this is how I did it...

1. Write a custom Java Class


package com.zoobiesoft;
import java.io.*;
import java.security.*;
import java.security.spec.*;
import javax.crypto.spec.*;
import javax.crypto.*;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Crypt {
     
      public static byte[] encryptString(String plainText, String key) {
            return crypt(plainText.getBytes(), key, Cipher.ENCRYPT_MODE);
      }

    public static String encryptStringToString(String plainText, String key)
    {
        byte[] cipherText = encryptString(plainText, key);
        return new BASE64Encoder().encode(cipherText);
    }

    public static byte[] decryptString( String plainText, String key)
    {
        byte[] plainBytes;
        try
        {
            plainBytes = new BASE64Decoder().decodeBuffer(plainText);
        }
        catch (IOException ex)
        {
            throw new RuntimeException(ex.getMessage());
        }
        return crypt(plainBytes, key, Cipher.DECRYPT_MODE);
    }

      public static String decryptStringToString(String text, String key) {
            return new String(decryptString(text, key));
      }

    private static SecretKey generateKey() throws NoSuchAlgorithmException,InvalidKeySpecException {
            PBEKeySpec spec = new PBEKeySpec("Super Secret Key Info Here".toCharArray());
            return SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(spec);
      }

      public static byte[] crypt(byte[] input, String key, int mode) {

            byte[] result = null;
            try {
                  StringBuffer sb = new StringBuffer(key);
                  while (sb.length() < 8) {
                        sb.append(key);
                  }
                  key = sb.toString().substring(0, 8);
                  SecretKey _key = generateKey();
                  PBEParameterSpec spec = new PBEParameterSpec(key.getBytes(), 20);
                  Cipher ciph = Cipher.getInstance("PBEWithMD5AndDES");
                  ciph.init(mode, _key, spec);
                  result = ciph.doFinal(input);
            }
            catch (Exception e) {
                  return null;
            }
            return result;
      }

      public static void main(String[] argv) {
            if (argv.length != 3) {
                  System.err.println("Usage: Crypt [ -d | -e ] text key");
                  System.exit(1);
            }

            if (argv[0].equals("-e")) {
                  System.out.println(encryptStringToString(argv[1], argv[2]));
            }
            else if (argv[0].equals("-d")) {
                  System.out.println(decryptStringToString(argv[1], argv[2]));
            }

      }

}

2. Instantiate the code in ColdFusion to encrypt your string information

 <cfobject action="create" class="com.zoobiesoft.Crypt" name="Crypt" type="java"/>
<cfset key = "URPublicKeyHere"/>
<cfset txt = getJLLISuserID.JLLISuserid>
<cfset encryptedUserID = Crypt.encryptStringToString(txt, key)/>

3. Decrypt the information on the JSP application side

//We need to decrypt it to get the real user ID
String key = "URPublicKeyHere";    //Key/Password to decrypt the encrypted with
String dtxt = "";    //A place to put the decrypted user ID                               
String etxt = URLDecoder.decode(cookies[loopIndex].getValue());    //The encrypted user ID is stored as a URLEncoded string, so we have to URLDecode it before decrypting it
dtxt = Crypt.decryptStringToString(etxt, key);    //Decrypt the URLDecoded encoded user ID

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
BlogCFC was created by Raymond Camden. This blog is running version 5.9.1.001.
Skin By: StyleShout CSS Styling by: MacWebDiva Contact Yancy Wharton