2013-10-18 36 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

@ CodeInChaos「通常の暗号化」とはどういう意味ですか? –

関連する問題