3DES - 在C#中解密加密文本(由JAVA提供)

时间:2011-02-09 19:14:10

标签: java c#-2.0 3des

情况如下:

  1. 加密文本在JAVA中完成(我们根本没有JAVA背景)
  2. 方法是3DES
  3. 填充物是PKCS#5
  4. Base 64
  5. 解密将在C#中,这是代码:

        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);
        }
    

    但是,当尝试解密时,收到错误消息:BAD DATA

    我在哪里错过了?

    提前致谢。

    已添加,以及加密的工作方式:

    <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>
    

    更新 此问题已得到解决。问题是密钥需要从Base64转换。

1 个答案:

答案 0 :(得分:0)

答案:

而不是:

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

这样做:

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

解决了这个问题。