开发者

Sequential .NET DESCryptoServiceProvider encryption and decryption produces wrong bytes after 96th

开发者 https://www.devze.com 2023-01-28 09:35 出处:网络
Basically, here is the code: DES d开发者_StackOverflow中文版es = new DESCryptoServiceProvider();

Basically, here is the code:

        DES d开发者_StackOverflow中文版es = new DESCryptoServiceProvider();
        PasswordDeriveBytes pdb = new PasswordDeriveBytes(new byte[]{123}, new byte[0]);
        des.IV = new byte[8];
        des.Key = pdb.CryptDeriveKey("DES", "MD5", 0, des.IV);

        byte[] A = Enumerable.Range(1, 100).Select(i => (byte)i).Concat(new byte[4]).ToArray();
        byte[] B = new byte[A.Length];
        byte[] C = new byte[A.Length];

        using (var encryptor = des.CreateEncryptor())
            encryptor.TransformBlock(A, 0, A.Length, B, 0);

        using (var decryptor = des.CreateDecryptor())
            decryptor.TransformBlock(B, 0, B.Length, C, 0);

        for (int i = 0; i < A.Length; i++)
            if (A[i] != C[i])
                Debugger.Break();

It breaks at i == 96. Why?

Another small question: omitting of .Concat(new byte[4]) causes first TransformBlock to throw an ArgumentException. Why can't it encrypt an array of sorted bytes without 4 zeroes at the end?


DES is a block cypher of 64bit blocks, therefore your data to be encoded needs to be a multiple of the 64bit blocks. (see http://en.wikipedia.org/wiki/Data_Encryption_Standard)

Looking at the 96, i assume the last block is different based on the fact you are padding the 100 (not 64bit block) into the 104 (64bit block) but are not setting the values of those last 4 bytes to 0.

Hope this helps,


The actual solution is to use ITransform.TransformFinalBlock.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号