I have been doing work with Encrypting something in ColdFusion and decrypting it in ColdFusion. I've wrote about these experiments before. I've been trying to figure out the best way to create a key.

In ColdFusion I could easily use the GenerateSecretKey function. However, if I do that, how would I pass that key to Flex? It would have to be hard coded in some manner into the Flex Component that needed the encryption algorithm.

What I wanted was a way to generate the key on the fly. Flex and ColdFusion could both use the same algorithm for generating the key, and as long as I passed it appropriate parameters it would generate the same key, thus allowing Flex to decrypt something that was encrypted in ColdFusion.

So, how do you do it?

A 128 bit key is needed. This turns into 16 text characters. So, I started like this:

view plain print about
1<cffunction name="generateEncryptionKey" access="private" output="true" returntype="string">
2 <cfset var HexKey = "">
3 <cfset var Filler = "abcdefghijklmnop">
4 <cfset var keyInText = "">

This is a function definition. It defines 3 local variables, one is HexKey. This will be the key, in hex, that we return from the function. The next variable is filler. If our algorithm generates a key that is less than 16 characters, we'll want to pad it. The final local variable is the keyInText. This will be the text representation of the key.

view plain print about
1Write some algorithm to generate a key here.

It wouldn't be appropriate for me to share the algorithm we are using for key generation. But, the next chunk of code would generate it based on some factors that can be determined on the server in CF and on the Flex client.

view plain print about
1<cfif len(keyInText) LT 16>
2 <cfset keyInText = keyInText & Filler>
3</cfif>
4
5<cfset keyInText = left(keyInText,16)>

IF the key is less than 16 characters, it adds in the filler. Then it truncates the key, removing all but the first 16 characters. We now have a 16 character key, no matter what the results of our "dynamically generate a key" algorithm.

view plain print about
1<cfset HexKey = stringToHex(keyInText)>

Next we turn the text key into Hex. I'm using the stringToHex function from cflib to do this.

view plain print about
1<cfreturn ToBase64(BinaryDecode(HexKey, "Hex"))>
2</cffunction>
And finally, we decode the key, base64 it, and pass it out of the function, ready to be used with ColdFusion's Encrypt or Decrypt functions.

I'm undecided on the wisdom in an approach like this. When sharing between systems in the past, I have used a hard-coded key that was pre-generated for the purposes of sharing. Is a "semi-random" key generator more or less secure than a hard coded key that was randomly generated?

Discuss amongst yourselves!