2010-05-09 68 views
0

我需要在C#上實現一些加密協議,並且想要說這是我在C#中的第一個項目。花了一些時間在C#上使用後,我發現我無法獲得兼容的AES矢量。.NET 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然後工作。 我粘貼了工作代碼。不管怎麼說,還是要謝謝你。

+0

C#沒有AES實現。 .NET Framework有一個AES實現。 – 2010-05-09 22:41:28

回答

0

嘗試解密;加密和解密方法有可能被交換(這在加密算法規範中有時是不明確的)。

0

您錯過了initialization vector - 沒有指定一個IV是隨機生成的,因此每次創建AES類的新實例時結果都會有所不同。

+0

ECB模式下沒有IV http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29 – 2010-05-09 22:19:34

+0

Ad doh確實沒有注意到ECB的設置。 – blowdart 2010-05-09 22:24:09

相關問題