Android 4.3 からKeyStore という仕組みができて、パスワードや暗号キーなどの重要情報を安全に保存ができるようになったとのこと。
そして、Xamarin では Xamarin.Auth を使えば簡単に KeyStore を扱うことができます。
Xamarin.Android と Xamarin.iOSで、ほぼ共通のロジックになりますね。
違いがあるとすれば、Xamarin.Android では「パスワードを保存するためのパスワード 」を設定する必要があることでしょうか。
このパスワードを設定しないと、以下の警告で怒られます。
This version is insecure, because of default password. Please use version with supplied password for AccountStore. AccountStore.Create(Contex, string) or AccountStore.Create(string);
パスワードを保存するために、パスワードをハードコーディングするなんてナンセンスだとも思うのですが、以前の Xamarin.Auth ではライブラリにパスワードをハードコーディングしていたようなので、それよりはましということなのでしょう。
具体的なソースコードは以下のようになります。
以下の名前空間の宣言を追加します。
using Xamarin.Auth; using System.Linq;
パスワードの保存は以下のようにします。"somePassword"というのがハードコーディングのパスワードになります。
Account account = new Account { Username = "userName" }; account.Properties.Add("password", "password"); AccountStore.Create("somePassword").Save(account, "serviceId");
KeyStore に保存したパスワードは以下のように読み込みます。
var account = AccountStore.Create("somePassword") .FindAccountsForService("serviceId") .FirstOrDefault(); System.Diagnostics.Debug.WriteLine(account.Properties["password"]);
読み込みの実行結果は以下のようになり問題ありませんでした。
password
なお、このソースコードでは値が null だった場合や例外を考慮していないので、実装の際は参考サイトを確認してみてください。
・参考サイト
- recipes/Recipes/xamarin-forms/General/store-credentials at master · xamarin/recipes
- oauth - Xamarin Auth account store - Stack Overflow
- AccountStore usage produces warning "This version is insecure, because of default password..." · Issue #293 · xamarin/Xamarin.Auth
- Android 4.3 で Android Keystore を使う
- Androidで暗号化のための秘密鍵を(なるべく)安全に保持する