0

Its a very simple code. But what I don't understand, When the Blocksize is 8byte, Cipher size is 16bytes, why? I am expecting it to be same as the Blocksize. From simple thinking, I give 64bits as plaintext and expect to have 64bits as cipher. And I really don't see any reason to do any padding here. It seems that after every 8bytes(Blocksize) the Cipher becomes 8bytes more. 16bytes Block becomes 24bytes Cipher etc. Why is it like this? I really want to know.

And just for curiosity, is there any possibility/way to have 8bytes Cipher from 8bytes Block?

The 3DES code: (only encryption part)

static void Main(string[] args)
    {

        Console.WriteLine("Enter Plain Text: ");
        string original =Console.ReadLine();
        TripleDESCryptoServiceProvider myTripleDES = new TripleDESCryptoServiceProvider();
        byte[] encrypted = EncryptStringToBytes(original,myTripleDES.Key, myTripleDES.IV);
        string encrypt = Convert.ToBase64String(encrypted);
        string decrypted = DecryptStringFromBytes(encrypted,myTripleDES.Key, myTripleDES.IV);
        Console.WriteLine("encryted: " +encrypt);
        Console.WriteLine("decrypted: " +decrypted);
        Console.ReadLine();

    }



    static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
    {
        byte [] data= Encoding.UTF8.GetBytes(plainText);
        Console.WriteLine("The Block length: " +data.Length);
        TripleDESCryptoServiceProvider tdsAlg = new TripleDESCryptoServiceProvider();
        tdsAlg.BlockSize = 64;
        tdsAlg.KeySize = 128;
        tdsAlg.Key = Key;  
        tdsAlg.IV = IV;  
        ICryptoTransform encryptor = tdsAlg.CreateEncryptor(tdsAlg.Key, tdsAlg.IV);
        byte[] encrypted = encryptor.TransformFinalBlock(data, 0, data.Length);
        Console.WriteLine("The Cipher length: " + encrypted.Length);
        return encrypted;
    }

enter image description here

4

1 回答 1

2

.NET 中的默认填充模式TripleDESCryptoServiceProvider是 PKCS7。PKCS7 填充模式根据需要添加尽可能多的字节来填充块,但总是至少一个字节(!)。这意味着如果您的数据以块边界结束,则需要添加另一个仅由填充字节组成的块。

您可以通过显式设置来避免这种情况:

tdsAlg.Padding = PaddingMode.None;

您将设置现在您的密码长度将按预期为 8 个字节。

至于即使您的数据与块大小匹配也需要填充的原因:

想象一下,您的数据以看起来像有效填充字节的字节结尾。在这种情况下,您的消息的解密器会假设这些实际上是填充字节,并且您的消息会被缩短。为了避免这种情况,在所有情况下都至少添加一个填充字节。PKCS7 中的填充字节实际上说明了填充中的字节数。因此,如果填充消息以 0x07 结尾,则意味着使用了 7 个填充字节,并且可以在解码消息时将其删除。

于 2014-05-30T00:15:25.473 回答