简体   繁体   中英

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

The encrypted text is done in JAVA (which we have no JAVA background at all)

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));
    // byte[] TDESKey = UTF8.GetBytes(Passphrase);
    TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
    TDESAlgorithm.Key = TDESKey;
    // TDESAlgorithm.Mode = CipherMode.CTS;
    TDESAlgorithm.Padding = PaddingMode.Zeros;

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

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

Encrypted Java code is

public  String encryptData(String privateKey, String rawData)  
{

    Cipher cipher = null;
    try 
    {
        cipher = Cipher.getInstance(DESEDE_ENCRYPTION_SCHEME);
        cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(privateKey));
        byte[] plainText = rawData.getBytes(UNICODE_FORMAT);
        byte[] encryptedText = cipher.doFinal(plainText);
        return new String(Base64.encodeBase64(encryptedText));
    } 
}

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

Where am I missing here?

You are not using MD5 in Java, so you should not be using it in your .NET for computing the hash.

Your key should have been generated using a specific encoding and same you should use in .NET.

Please note, there is some fundamental difference in java KeySpec and the Key being used for TripleDESCryptoServiceProvider . As mentioned by Microsfot https://msdn.microsoft.com/en-us/library/system.security.cryptography.tripledescryptoserviceprovider.aspx

Triple DES only supports "key lengths from 128 bits to 192 bits in increments of 64 bits"

So you need to convert your key appropriately before assigning. To do this you can use the Array.Resize method as following.

byte[] TDESKey = Encoding.UTF8.GetBytes(Passphrase);
System.Array.Resize(ref TDESKey , 192 / 8);

Hope this will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM