3DES - Decrypt encrypted text (by JAVA) in C#

2.8k views Asked by At

Here is the situation:

  1. The encrypted text is done in JAVA (which we have no JAVA background at all)
  2. The method is 3DES
  3. The padded is PKCS#5
  4. Base 64

The decryption will be in C#, and here is the code:

    public static string DecryptString(string Message, string Passphrase)
    {
        byte[] Results;
        UTF8Encoding UTF8 = new UTF8Encoding();

        MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
        byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));

        TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

        TDESAlgorithm.Key = TDESKey;
        TDESAlgorithm.Mode = CipherMode.ECB;
        TDESAlgorithm.Padding = PaddingMode.PKCS7;

        byte[] DataToDecrypt = Convert.FromBase64String(Message);

        try
        {
            ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
            Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
        }
        finally
        {
            TDESAlgorithm.Clear();
            HashProvider.Clear();
        }

        return UTF8.GetString(Results);
    }

However, when tried to decrypt, got the error message: BAD DATA

Where am I missing here?

Thanks in advance.

Added, and here's how the encryption works:

<cffunction name="getToken" returntype="String" output="false">
    <cfscript>
        plainText = getPlainText();
        rawSecretKey = CreateObject("java","sun.misc.BASE64Decoder").decodeBuffer(variables.encryptionKey);

        secretKeySpec = CreateObject("java","javax.crypto.spec.SecretKeySpec").init(rawSecretKey,"DESEDE");

        cipher = CreateObject("java","javax.crypto.Cipher").getInstance("DESEDE");
        cipher.init(Cipher.ENCRYPT_MODE, secretkeySpec);

        encrypted = cipher.doFinal(plainText.getBytes()); // a byte array (a binary in CF)

        return URLEncodedFormat(ToString(ToBase64(encrypted)));
    </cfscript>
</cffunction>

Update: This issue has been resolved. The problem was that the key needed to be converted from Base64.

1

There are 1 answers

0
Danny On

The answer:

Instead of:

byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));

Do this:

byte[] TDESKey = Convert.FromBase64String(Passphrase);

That solves this issue.