2013-10-18 64 views
5

我目前需要一種在C#中使用AES-128對稱加密來加密字符串並解密字節數組的方法。我找不到如何做到這一點的方法,但也許我錯過了一些東西。如何在沒有IV的情況下使用AES 128進行加密和解密?

+2

爲什麼你想避免的IV?它們是一個重要的安全功能。 – CodesInChaos

+0

展開@CodesInChaos評論。 IV可隨機生成並與密文一起以明文方式傳輸。 IV的保密不是安全所必需的。對IV的要求是,你不會重複使用相同的密鑰和IV組合,並且IV很難預測。 – Dev

+0

這個問題是一個項目,有人有興趣使用沒有IV的AES進行加密。我同意他們是一個重要的安全功能! – kdh

回答

11

導入命名空間

using System; 
using System.IO; 
using System.Text; 
using System.Security.Cryptography; 

    static void Main(string[] args) 
     { 
      string value = "@arifansari300<3>"; 

      string encryptedValue= EncryptDecrypt.Encrypt(value); 

      string decryptedValue = EncryptDecrypt.Decrypt(encryptedValue); 
     } 

    public static string Encrypt(string clearText) 
    { 
     string EncryptionKey = "MAKV2SPBNI99212"; 
     byte[] clearBytes = Encoding.Unicode.GetBytes(clearText); 
     using (Aes encryptor = Aes.Create()) 
     { 
      Rfc2898DeriveBytes pdb = new 
       Rfc2898DeriveBytes(EncryptionKey, new byte[] 
       { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); 
      encryptor.Key = pdb.GetBytes(32); 
      encryptor.IV = pdb.GetBytes(16); 
      using (MemoryStream ms = new MemoryStream()) 
      { 
       using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write)) 
       { 
        cs.Write(clearBytes, 0, clearBytes.Length); 
        cs.Close(); 
       } 
       clearText = Convert.ToBase64String(ms.ToArray()); 
      } 
     } 
     return clearText; 
    } 

    public static string Decrypt(string cipherText) 
    { 
     string EncryptionKey = "MAKV2SPBNI99212"; 
     byte[] cipherBytes = Convert.FromBase64String(cipherText); 
     using (Aes encryptor = Aes.Create()) 
     { 
      Rfc2898DeriveBytes pdb = new 
       Rfc2898DeriveBytes(EncryptionKey, new byte[] 
       { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); 
      encryptor.Key = pdb.GetBytes(32); 
      encryptor.IV = pdb.GetBytes(16); 
      using (MemoryStream ms = new MemoryStream()) 
      { 
       using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write)) 
       { 
        cs.Write(cipherBytes, 0, cipherBytes.Length); 
        cs.Close(); 
       } 
       cipherText = Encoding.Unicode.GetString(ms.ToArray()); 
      } 
     } 
     return cipherText; 
    } 
+1

當你必須使用由最終用戶輸入的密碼而不是生成正確的密鑰時,'Rfc2898DeriveBytes'只是一個不錯的選擇。但在這種情況下,你應該使用一個鹽(在你的例子中它是一個常數,它忽略了IV的重點)和更多的迭代(至少20K,最好是更多)。如果你有一個合適的密鑰,普通的加密更簡單,* *更快。 – CodesInChaos

+0

我該如何轉換這個函數PHP? – user3581428

+0

@CodesInChaos「正常加密」是什麼意思? –

相關問題