• 追加された行はこの色です。
  • 削除された行はこの色です。
#setlinebreak(on);
[[WP TIPS に戻る>wp7/tips]]

*AES でデータを暗号化する [#u3cae9e8]
Windows Phone7 の Silverlight で使用できる暗号化アルゴリズムは、Triple DES と AES を使用することが出来、文字列やバイナリ列などを暗号化してファイルに保存することが出来ます。
ここでは ProtectedData クラスを使用した Triple DES による暗号化を紹介します。
ここでは System.Security.Cryptography 名前空間を使用した AES による暗号化を紹介します。

**AES でデータを暗号化する [#bbcaacb8]
ProtectedData クラスを使用した暗号化と違い、AES 暗号化を使用する際にはいくつかの関連したクラスを使用します。

 using System.Security.Cryptography;
 
 // "ほげほげ" と言う文字列を パスワード == testtest, salt == testtest で暗号化する
 // 暗号化後 Base64 エンコードした文字列に変換する。
 byte[] data = Crypt("ほげほげ", "testtest", "testtest");
 string text = Convert.ToBase64String(data, 0, data.Length);
 System.Diagnostics.Debug.WriteLine(text);
 
 public static byte[] Crypt(byte[] data, string password, string salt)
 {
    AesManaged aes = null;
    MemoryStream ms = null;
    CryptoStream cs = null;
 
    try
    {
        // キー生成
        Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(password, Encoding.UTF8.GetBytes(salt));
 
        // AES 初期化 - 128bit
        aes = new AesManaged();
        aes.Key = rfc2898.GetBytes(16);
        aes.IV = rfc2898.GetBytes(16);
 
        // 暗号化
        ms = new MemoryStream();
        cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write);
        cs.Write(data, 0, data.Length);
        cs.FlushFinalBlock();
 
        // 返す
        return ms.ToArray();
    }
    finally
    {
        if (cs != null)
            cs.Dispose();
        if (ms != null)
            ms.Dispose();
        if (aes != null)
            aes.Clear();
    }
 }

**AES で暗号化したデータを復号化する [#u8bb6ec3]
復号化するには暗号化の逆を行なえば良いので、簡単です。

 // "ほげほげ" と言う文字列を暗号化した Base64 文字列を パスワード == testtest, salt == testtest で復号化する
 // 暗号化後 Base64 エンコードした文字列に変換する。
 byte[] data = Decrypt(Convert.FromBase64String("UU64pbN+HHL08VODfyjmIgTGeJr4o="), "testtest", "testtest");
 string text = Encoding.UTF.GetString(data, 0, data.Length);
 System.Diagnostics.Debug.WriteLine(text);
 
 public static byte[] Decrypt(byte[] data,  string password, string salt)
 {
    AesManaged aes = null;
    MemoryStream ms = null;
    CryptoStream cs = null;
 
    try
    {
        // キー生成
        Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(password, Encoding.UTF8.GetBytes(salt));
 
        // AES 初期化 - 128bit
        aes = new AesManaged();
        aes.Key = rfc2898.GetBytes(16);
        aes.IV = rfc2898.GetBytes(16);
 
        // 復号化
        ms = new MemoryStream();
        cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write);
        cs.Write(data, 0, data.Length);
        cs.FlushFinalBlock();
 
        // 返す
        return ms.ToArray();
    }
    finally
    {
        if (cs != null)
            cs.Dispose();
        if (ms != null)
            ms.Dispose();
        if (aes != null)
            aes.Clear();
    }
 }

参考
-Don’t forget to Encrypt your Windows Phone 7 Data
http://robtiffany.com/windows-phone-7/dont-forget-to-encrypt-your-windows-phone-7-data