c# Triple DES encryption with two keys

2019-08-13 02:09发布

I have to encrypt a hex string with two keys. My code for this looks like that:

public byte[] TripleDes(byte[] inputBuffer, byte[] key)
{
    byte[] result;

    using (TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider())
    using (MemoryStream stream = new MemoryStream())
    using (CryptoStream cryptoStream = new CryptoStream(stream, des.CreateEncryptor(), CryptoStreamMode.Write))
    {
       des.Key = key;
       // des.KeySize = 128;   <- wrong, overrides the values of the key
       des.Mode = CipherMode.ECB;
       des.Padding = PaddingMode.None;

       cryptoStream.Write(inputBuffer, 0, inputBuffer.Length);
       cryptoStream.FlushFinalBlock();
       result = stream.ToArray();
    }

    return result;
}

The key which is set is 16 bytes and consist of two parts: first part = key to encrypt, second part = key to decrypt. The inputBuffer is 8 bytes. When I do the encryption like that, my result is 16 bytes instead of 8 bytes. What am I doing wrong?

2条回答
beautiful°
2楼-- · 2019-08-13 02:28

The code was correct but the order not. The configuration of the "TripleDESCryptoServiceProvider" instance happened after the "CreateEncryptor()" method was instanziated. So the correct code is:

public byte[] TripleDes(byte[] inputBuffer, byte[] key)
{
    using (TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider())
    {
        des.Key = key;
        des.Mode = CipherMode.ECB;
        des.Padding = PaddingMode.None;

        byte[] result;

        using (MemoryStream stream = new MemoryStream())
        using (CryptoStream cryptoStream = new CryptoStream(stream, des.CreateEncryptor(), CryptoStreamMode.Write))
        {
            cryptoStream.Write(inputBuffer, 0, inputBuffer.Length);
            cryptoStream.Flush();
            //cryptoStream.FlushFinalBlock();
            result = stream.ToArray();
        }

        return result;
    }
}

The "Flush()" and the "FlushFinalBlock()" method return both the same result, except the "FlushFinalBlock" has 8 bytes additional data which I don't need and I don't know what it is.

查看更多
唯我独甜
3楼-- · 2019-08-13 02:50

check stream.Length. Use this function to change stream to byte array

 public static byte[] ReadFully(Stream input)
        {
            if (input is MemoryStream)
            {
                return ((MemoryStream)input).ToArray();
            }
            else
            {
                return ReadFully(input);
            }
        }
查看更多
登录 后发表回答