为什么3DES不加密一个块? [英] Why won't 3DES encrypt one block?

查看:195
本文介绍了为什么3DES不加密一个块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现这个问题,我过去曾问过每个元件开销安全地加密64位?

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

在立即窗口中,我输入了 TripleDES.Create()。LegalBlockSizes.First()并获得

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

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

每个字节64位/ 8位为8字节。长短是多久。无论如何,我运行它通过下面的代码和异常抛出。块的长度为16字节。不是我想要的...我会问如何将其更改为64位,但结果说最小和最大都是64位,所以为什么我得到128位?

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);
    }
}


推荐答案

相信这是由于填补。默认的填充模式用于对称密码.NET Framework是PKCS7:

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


PKCS#7填充字符串由一系列字节组成,每个字节等于总数添加填充字节

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

如果添加一行:

des.Padding = PaddingMode.None;

在您的其余加密代码之前,您应该会发现该数组的长度为8个字节。当然,这意味着你必须确保任何要加密的明文都可以被块长度整除。

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.

而且,你还需要传输IV还有8个字节。 IV不应该重复使用,所以与明文相比,您的存储/传输规​​模仍然翻了一倍。

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.

< a href =http://en.wikipedia.org/wiki/Padding_%28cryptography%29 =nofollow> Padding :


密码块链接(CBC)模式是一种流行的块密码操作模式。它需要长度为块大小(通常为8或16字节)的倍数的消息,因此必须填充消息以使其达到此长度。一种方法是用1位后跟零位来填写最后一个块。如果输入恰好填满整个块,则添加一个虚拟块来容纳填充;输入明文的结尾可能被误解为填充。

(加重)CBC是默认的<对于.NET Framework中的密码,href =http://msdn.microsoft.com/en-us/library/system.security.cryptography.ciphermode =nofollow>模式)

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

这篇关于为什么3DES不加密一个块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆