2011-12-09 8 views
0

私のWebアプリケーションでC#を使用してデータベースのいくつかのフィールドを暗号化する安全な方法を見つけようとしています。暗号化 - machinekey

私は暗号化/復号化を行うスクリプトとそのキーを保存する方法を見つける必要があります。私はあなたがキーとしてマシンキーを使うことができることを読んだ、それは正しい?

自動生成および非自動生成のマシンキーがあります。私はむしろ、私は別のサーバーに私のWebアプリケーションを配備するのは簡単だろうこのように自動生成されていないと行くと思う。私はそれがあなたのための1を生成し、このツールを見つけました:

http://aspnetresources.com/tools/machineKey

暗号化/復号化スクリプトはこののmachineKeyで動作するでしょうか?私が思っていた。また

、それは、web.configファイル内の非自動生成マシンのキーを格納する方法安全ですか?誰かがweb.configファイルを見ることができる場合、appSettingsの「通常の」キーの代わりにmachinekeyを使用するのはなぜですか?

おかげで

答えて

0

その記事によると、256ビットの復号鍵と512ビットの検証鍵が生成され、彼らはRijndaelアルゴリズムで行くので、あなたはすでにあり、それのC#実装を必要としますSystem.Security.Cryptography名前空間。

private static string EncryptString(string clearText, 
            string strKey, string strIv) { 

    byte[] plainText = Encoding.UTF8.GetBytes(clearText); 

    byte[] key = Encoding.UTF8.GetBytes(strKey); 

    // a simple initialization vector 
    byte[] iv = Encoding.UTF8.GetBytes(strIv); 


    RijndaelManaged rijndael = new RijndaelManaged(); 

    //Define the Mode 
    rijndael.Mode = CipherMode.CBC; 

    ICryptoTransform aesEncryptor = rijndael.CreateEncryptor(key, iv); 

    MemoryStream ms = new MemoryStream(); 

    // writing data to MemoryStream 
    CryptoStream cs = new CryptoStream(ms, aesEncryptor, CryptoStreamMode.Write); 
    cs.Write(plainText, 0, plainText.Length); 
    cs.FlushFinalBlock(); 

    byte[] CipherBytes = ms.ToArray(); 

    ms.Close(); 
    cs.Close(); 

    return Convert.ToBase64String(CipherBytes); 
} 

そして:

public static string DecryptString(string cipherText, 
            string strKey, string strIv) { 

      byte[] cipheredData = Convert.FromBase64String(cipherText); 
      byte[] key = Encoding.UTF8.GetBytes(strKey); 

      byte[] iv = Encoding.UTF8.GetBytes(strIv); 

      RijndaelManaged rijndael = new RijndaelManaged(); 
      rijndael.Mode = CipherMode.CBC; 

      ICryptoTransform decryptor = rijndael.CreateDecryptor(key, iv); 
      MemoryStream ms = new MemoryStream(cipheredData); 
      CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read); 

      byte[] plainTextData = new byte[cipheredData.Length]; 

      int decryptedByteCount = cs.Read(plainTextData, 0, plainTextData.Length); 

      ms.Close(); 
      cs.Close(); 

      return Encoding.UTF8.GetString(plainTextData, 0, decryptedByteCount); 
} 

そして、あなたの2番目の質問については、生成されたのmachineKeyは人間読み込み可能ですが、あなたが理解できない16進数の文字列である。ここ

は、仕事をする二つの機能でありますそれを出す。

このヘルプが欲しいです。

+0

これらはマシンキーと一致しますか? string strKey、string strIv – user441365

+0

strKeyはマシンキーです。初期化ベクトル文字列を表すstrIvは、必要な値を渡すことができる単純な文字列です。 – amrfaissal

+0

次にstrIvをハードコードできますか?また、strKEyはvalidationKeyまたはdecryptionKeyと一致する必要がありますか? – user441365