We are having difficulty decrypting a string in ColdFusion that was previously encrypted with 3DES and C#. Here is the code we used to encrypt the string initially:
public static string EncryptTripleDES(string plaintext, string key)
{
TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();
MD5CryptoServiceProvider hashMD5 = new MD5CryptoServiceProvider();
DES.Key = hashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(key));
DES.Mode = CipherMode.ECB;
ICryptoTransform DESEncrypt = DES.CreateEncryptor();
byte[] Buffer = ASCIIEncoding.ASCII.GetBytes(plaintext);
string EncString = Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
EncString = EncString.Replace("+", "@@12");
return EncString;
}
We have tried using the suggestions here:
TripleDES Encryption - .NET and ColdFusion not playing nice
..with no luck. Here is our CF code and the error:
<cfset variables.theKey = "blahblah" />
<cfset variables.theAlgorithm = "DESede/CBC/PKCS5Padding">
<cfset variables.theEncoding = "Base64">
<cfset strTest = decrypt(#DB.PASSWORD#, variables.theKey, variables.theAlgorithm, variables.theEncoding)>
Error returned: An error occurred while trying to encrypt or decrypt your input string: '' Can not decode string "blahblah"
So, it looks like it's trying to decrypt the key and not the string, but that's not how the decrypt function is outlined in ColdFusion. Any ideas?
UPDATE: Attempted to use the following CF code, but the error returned is still "An error occurred while trying to encrypt or decrypt your input string: Given final block not properly padded."
<cfset dbPassword = "Hx41SYUrmnFPa31QCH1ArCHN1YOF8IAL">
<cfset finalText = replace(dbPassword, "@@12", "+", "all")>
<cfset theKey = "abcdefgh">
<cfset theKeyInBase64 = toBase64(theKey)>
<cfset hashedKey = hash( theKeyInBase64, "md5" )>
<cfset padBytes = left( hashedKey, 16 )>
<cfset keyBytes = binaryDecode( hashedKey & padBytes , "hex" )>
<cfset finalKey = binaryEncode( keyBytes, "base64" )>
<cfset decrypted = decrypt( finalText, finalKey, "DESede/ECB/PKCS5Padding", "base64" )>
Decrypted String: <cfdump var="#decrypted#">
UPDATE:
The solution if you follow the comments was to change:
<cfset hashedKey = hash( theKeyInBase64, "md5" )>
To:
<cfset hashedKey = hash( theKey, "md5" )>
The final code is this:
<cfset dbPassword = "Hx41SYUrmnFPa31QCH1ArCHN1YOF8IAL">
<cfset finalText = replace(dbPassword, "@@12", "+", "all")>
<cfset theKey = "abcdefgh">
<cfset hashedKey = hash( theKey, "md5" )>
<cfset padBytes = left( hashedKey, 16 )>
<cfset keyBytes = binaryDecode( hashedKey & padBytes , "hex" )>
<cfset finalKey = binaryEncode( keyBytes, "base64" )>
<cfset decrypted = decrypt( finalText, finalKey, "DESede/ECB/PKCS5Padding", "base64" )>
Decrypted String: <cfdump var="#decrypted#">