【问题标题】:.NET AES returns wrong Test Vectors.NET AES 返回错误的测试向量
【发布时间】:2010-05-09 21:57:36
【问题描述】:

我需要在 C# 上实现一些加密协议,并且想说这是我在 C# 中的第一个项目。在花了一些时间使用 C# 之后,我发现我无法获得兼容的 AES 向量。

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

namespace ConsoleApplication1
{
    class Program
    {
        public static void Main()
        {
            try
            {

                byte[] key = { 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
                byte[] data = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
                byte[] encTest = { 0x0e, 0xdd, 0x33, 0xd3, 0xc6, 0x21, 0xe5, 0x46, 0x45, 0x5b, 0xd8, 0xba, 0x14, 0x18, 0xbe, 0xc8 };

                AesManaged aesAlg = new AesManaged();
                aesAlg.BlockSize = 128;
                aesAlg.Key = key;
                aesAlg.Mode = CipherMode.ECB;
                aesAlg.Padding = PaddingMode.None;
                ICryptoTransform encryptor = aesAlg.CreateEncryptor();

                MemoryStream msEncrypt = new MemoryStream();
                CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
                csEncrypt.Write(data, 0,data.Length);

                byte[] encr;
                encr = msEncrypt.ToArray();
                string datastr    = BitConverter.ToString(data);
                string encrstr    = BitConverter.ToString(encr);
                string encTestStr = BitConverter.ToString(encTest);

                Console.WriteLine("data:   {0}", datastr);
                Console.WriteLine("encr:   {0}", encrstr);
                Console.WriteLine("should: {0}", encTestStr);              
                Console.ReadKey();

            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e.Message);
            }
        }
    }
}

输出错误:

data:   00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
encr:   A0-3C-C2-22-A4-32-F7-C9-BA-36-AE-73-66-BD-BB-A3
should: 0E-DD-33-D3-C6-21-E5-46-45-5B-D8-BA-14-18-BE-C8

我确信 .NET 中存在正确的 AES 实现,因此我需要 .NET 向导的一些建议来帮助解决此问题。

编辑

我刚发现。 必须有 PaddingMode.None 然后才能工作。 我粘贴了工作代码。还是谢谢。

【问题讨论】:

  • C# 没有 AES 实现。 .NET Framework 具有 AES 实现。

标签: c# .net aes


【解决方案1】:

尝试解密;可能 Encrypt 和 Decrypt 方法被交换了(这在加密算法规范中有时是模棱两可的)。

【讨论】:

    【解决方案2】:

    您缺少initialization vector - 如果没有指定一个,IV 是随机生成的,因此每次创建 AES 类的新实例时结果都会有所不同。

    【讨论】:

    猜你喜欢
    • 2011-03-12
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 2011-02-24
    • 1970-01-01
    • 1970-01-01
    • 2018-05-07
    相关资源
    最近更新 更多