代码之家  ›  专栏  ›  技术社区  ›  Luka Rahne

.NET AES返回错误的测试向量

  •  0
  • Luka Rahne  · 技术社区  · 16 年前

    我需要在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向导的一些建议来帮助解决这个问题。

    我刚发现。 必须有填充模式。无然后工作。

    2 回复  |  直到 16 年前
        1
  •  0
  •   Andrew McGregor    16 年前

        2
  •  0
  •   blowdart    16 年前

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

    推荐文章