Archived Forum Post

Index of archived forum posts

Question:

Matching .NET Framework TripleDES

Feb 22 '17 at 14:14

Hello,

I have the following .NET class that I'm trying to re-write into Crypt2.

Actual keys from the byte array have been removed, but contains numbers such as {1, 2, 3, 4}.

The class below encrypts/decrypts a Base64 string.

Can anyone help me with what settings I need to use on the Crypt2 component so that my encrypted string will match the .NET encrypted string? I'm having trouble figuring out what to use for CipherMode, KeyLength, and PaddingScheme.

class Crypt
{

    //New Key
    //24 byte or 192 bit key and IV for TripleDES
    private static byte[] KEY_192 = {?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?};
    private static byte[] IV_192 = {?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?};

    //TRIPLE DES encryption
    public static string EncryptTripleDES(string value)
    {
        if (!string.IsNullOrEmpty(value))
        {
            TripleDESCryptoServiceProvider cryptoProvider = new TripleDESCryptoServiceProvider();
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, cryptoProvider.CreateEncryptor(KEY_192, IV_192), CryptoStreamMode.Write);
            StreamWriter sw = new StreamWriter(cs);

            sw.Write(value);
            sw.Flush();
            cs.FlushFinalBlock();
            ms.Flush();

            //convert back to a string
            return Convert.ToBase64String(ms.GetBuffer(), 0, Convert.ToInt32(ms.Length));
        }
        else
        {
            return null;
        }
    }

    //TRIPLE DES decryption
    public static string DecryptTripleDES(string value)
    {
        if (!string.IsNullOrEmpty(value))
        {
            TripleDESCryptoServiceProvider cryptoProvider = new TripleDESCryptoServiceProvider();

            //convert from string to byte array
            byte[] buffer = Convert.FromBase64String(value);
            MemoryStream ms = new MemoryStream(buffer);
            CryptoStream cs = new CryptoStream(ms, cryptoProvider.CreateDecryptor(KEY_192, IV_192), CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(cs);

            return sr.ReadToEnd();
        }
        else
        {
            return null;
        }
    }

Thank you!!