【问题标题】:Simple DES ECB encryption and decryption in C#C#中简单的DES ECB加解密
【发布时间】:2013-12-27 17:56:14
【问题描述】:

我正在尝试做一个练习,其中包括使用给定的共享密钥解密给定的加密会话密钥。我已经解密了会话密钥并在屏幕上打印了字节数组。 (当我运行程序时会打印相同的结果)。

然后为了检查我的工作,我试图再次加密解密的会话密钥(显然使用相同的共享密钥),但结果始终不同,什么时候应该把原始的加密会话密钥还给我。

我无法理解是我的错误....

谢谢

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace Crypto
{
    public class Program
    {
        static void Main(string[] args)
        {

        //Shared Master Key
        byte[] mkByteArray = { 0x12, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x23 };

        //Encrypted Session Key
        byte[] eskByteArray = { 0x4a, 0x4d, 0xe6, 0x87, 0x82, 0x47, 0xd3, 0x7b };

        PrintByteArray(eskByteArray);

        DES des = new DESCryptoServiceProvider();
        des.Mode = CipherMode.ECB;
        des.Padding = PaddingMode.None;
        des.Key = mkByteArray;

        ICryptoTransform ct1 = des.CreateDecryptor();
        byte[] resultArray1 = ct1.TransformFinalBlock(eskByteArray, 0, eskByteArray.Length);
        des.Clear();
        PrintByteArray(resultArray1);

        ICryptoTransform ct2 = des.CreateEncryptor();
        byte[] resultArray2 = ct2.TransformFinalBlock(resultArray1, 0, resultArray1.Length);
        des.Clear();
        PrintByteArray(resultArray2);
        }

        //-----Method to print the byte array on screen-----
        public static void PrintByteArray(byte[] bytes)
        {
            var sb = new StringBuilder("new byte[] { ");
            foreach (var b in bytes)
            {
                sb.Append(b + ", ");
            }
            sb.Append("}");
            Console.WriteLine(sb.ToString());
        }

    }
}

【问题讨论】:

    标签: c# encryption console des ecb


    【解决方案1】:

    我发现了你的问题,但现在我正在检查它发生的确切原因。

    你在加密和解密之间调用des.Clear();,如果你不这样做,输入和输出是一样的。


    来自Msdn:

    调用时,Clear 方法会用零覆盖对象内的所有敏感数据

    因此,您的 DES 对象中的主密钥设置为零,这就是您的输出不同的原因。

    【讨论】:

    • 像你说的那样解决了 Key 被赋予了默认值。
    【解决方案2】:

    发生这种情况是因为 初始化向量。这种行为是设计使然。您不希望加密算法为相同的输入产生完全相同的输出。这种算法容易受到纯文本攻击,攻击者可以从输入和产生的输出中推断出加密密钥。

    这发生在一行

    ICryptoTransform ct2 = des.CreateEncryptor();
    

    根据msdn

    如果当前 IV 属性为空, 调用 GenerateIV 方法来创建一个新的随机 IV。

    要解决此问题,您需要为加密器设置 IV。然后,您将 IV 与加密字节一起存储并将其用于解密。 IV,简单来说,是一些初始随机噪声,允许加密算法产生不同的输入。作为一种好的做法,每次加密调用的噪声必须不同。

    显然,DES 是一种非常弱的算法,您至少需要使用 3DES。但即使是 3DES 也仅用于遗留应用程序。现代应用程序使用 AES。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多