【问题标题】:Encrypted data size while using Triple DES使用三重 DES 时的加密数据大小
【发布时间】:2009-04-20 08:35:08
【问题描述】:

我打算在我的一个项目中使用 TripleDES。我正在做一些实验以适应它。我知道三重 DES 的块大小是 8 个字节,所以我假设如果给出 8 个字节的数据,我应该得到 8 个字节的加密数据。但我得到的是:

输入大小 |加密大小 . | . . | . 6 字节 | 8 个字节 7 个字节 | 8 个字节 8 字节 | 16 字节 9 个字节 | 16 字节 . | . . | .

正常吗?这是它应该工作的方式。以下是我尝试使用三重 DES 的方法:

class TripleDESEncryption
{
    private readonly TripleDESCryptoServiceProvider engine;

    public TripleDESEncryption () : this (256) { }

    public TripleDESEncryption (int keySizeInBits) {
        engine = new TripleDESCryptoServiceProvider { KeySize = keySizeInBits };
        engine.GenerateKey ();
    }

    public byte[] Encrypt (byte[] plain) {
        return engine.CreateEncryptor ().TransformFinalBlock (plain, 0, plain.Length);
    }

    public byte[] Decrypt (byte[] encrypted) {
        return engine.CreateDecryptor ().TransformFinalBlock (encrypted, 0, encrypted.Length);
    }
}

class Program
{
    static readonly int MAX_TEXT_LENGTH = 128;

    static void Main (string[] args) {
        Console.WriteLine ("{0,10}{1,10}{2,10}{3,10}", "Algo", "Key Size", "Input Size", "Encrypted Size");

        var tripleDES = new TripleDESEncryption ();
        var input = new List<byte> ();

        for (int i = 0; i <= MAX_TEXT_LENGTH; i++) {
            var plain = input.ToArray ();
            var encrypted = tripleDES.Encrypt (plain);
            Console.WriteLine ("{0,10}{1,10}{2,10}{3,10}", "Triple DES", keySize, input.Count, encrypted.Length);
            input.Add (0x65);
        }

        Console.ReadLine ();
    }
}

【问题讨论】:

    标签: c# .net encryption cryptography 3des


    【解决方案1】:

    TripleDESCryptoServiceProvider 默认使用PKCS7-padding。这会将任何消息填充到块大小的下一个倍数。

    为避免使用填充,只需将Padding-property 设置为PaddingMode.None

    new TripleDESCryptoServiceProvider { 
      KeySize = keySizeInBits, 
      Padding = PaddingMode.None 
    };
    

    【讨论】:

    • 非常感谢。你的解决方案奏效了。我只是不明白实现。如果给出的块是块大小的精确倍数,它不应该填充任何东西。我想,任何理智的程序员都会这样做。
    • 可逆填充需要在明文中添加一些数据来传达应该如何删除它。因此它必须将 n*8 字节扩展为 (n+1)*8 字节。
    猜你喜欢
    • 2011-10-22
    • 2011-07-30
    • 2012-03-30
    • 1970-01-01
    • 2015-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多