Why won't 3DES encrypt one block?

冷暖自知 提交于 2019-12-23 03:28:09

问题


I'm trying to implement this question i asked in the past Securely Encrypt 64bits w/o per element overhead?

In the immediate window i entered TripleDES.Create().LegalBlockSizes.First() and got

{System.Security.Cryptography.KeySizes}
    MaxSize: 64
    MinSize: 64
    SkipSize: 0

64bits/8bits per byte is 8bytes. Exactly what length a long is. Anyways i run it through the code below and the exception throws. The length of the block is 16bytes. Not what i want to have... I would ask how to change it to 64bits but as the results say the min and max are both 64bits so why am i getting 128bits instead??

long enc(long v, byte[] iv)
{
    using (var m = new MemoryStream())
    {
        using (var c = des.CreateEncryptor(des.Key, iv))
        using (var s = new CryptoStream(m, c, CryptoStreamMode.Write))
        {
            var b = BitConverter.GetBytes(v);
            s.Write(b, 0, b.Length);
        }
        m.Flush();
        var arr = m.ToArray();
        if(arr.Length!=8)
            throw new Exception();
        return BitConverter.ToInt64(arr, 0);
    }
}

回答1:


I believe that this is due to padding. The default padding mode for symmetric ciphers in the .NET Framework is PKCS7:

The PKCS #7 padding string consists of a sequence of bytes, each of which is equal to the total number of padding bytes added.

If you add a line:

des.Padding = PaddingMode.None;

Before the rest of your encryption code, you should find the array is 8 bytes in length now. Of course, this means that you must ensure that any plaintext to be encrypted is exactly divisible by the block length.

And, also, you still need to transmit the IV which is another 8 bytes anyway. IVs should not be reused, so you've still doubled the size of storage/transmission compared to the plaintext.


Padding:

Cipher-block chaining (CBC) mode is a popular block cipher mode of operation. It requires messages whose length is a multiple of the block size (typically 8 or 16 bytes), so messages have to be padded to bring them to this length. One method is to fill out the last block with a 1-bit followed by zero bits. If the input happens to fill up an entire block, a “dummy block” is added to accommodate the padding; otherwise, the end of the input plaintext might be misinterpreted as padding.

(Emphasis added. CBC is the default mode for ciphers in .NET Framework)



来源:https://stackoverflow.com/questions/11877128/why-wont-3des-encrypt-one-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!