0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Xamarin.Androidでクライアント証明書を使った認証をしようとした話

Last updated at Posted at 2019-12-13

まだ解決してません

同じことで躓く人がいなくなりますように書き残します。

要件

Azureサーバーへの通信は特定多数のPC、android端末からのみを許可したい

1番目に試したこと

設定からクライアント証明書をandroid端末にインストールし、
プログラムで参照して、リクエストヘッダに載せたかった

できなった原因

http://dsas.blog.klab.org/archives/51995232.html
サイトを要約すると、設定から証明書をインストールした場合、
アプリから参照する方法がない。
アプリからインストールさせればできる。

2番目に試したこと

アプリから証明書をインストールさせる。
パスワードはユーザーに入力させ、証明書はファイルアプリ内のフォルダに置き、
初回パスワード入力で、証明書をインストールしたら、証明書を削除する想定。

2回目以降は証明書ストアから取得するよう書きました。

実際にインストールも、取り出しもできたのですが、問題がありました。

証明書を端末から取り出した場合のみ、証明書についている秘密鍵がnullになってしまい、サーバーで認証が通りません。

private getCert() 
{
    X509Certificate2Collection findResult;
    using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
    {
        store.Open(OpenFlags.MaxAllowed);
        findResult = store.Certificates.Find(X509FindType.FindBySubjectName, "subjectname", false);
        store.Close();
    }
    X509Certificate2 cert;
    if (findResult.Count == 1)
    {
        cert = findResult[0];
    }
    else
    {
        X509KeyStorageFlags flags = X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable;
        Stream fis = Android.App.Application.Context.Assets.Open("certfilename.pfx");
        cert = new X509Certificate2(GetByteArrayFromStream(fis), "password",flags);

        using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
        {
            store.Open(OpenFlags.ReadWrite);
            store.Add(cert);
            store.Close();
        } 
    }
    return cert;
}

解決案あったら教えてください

X509Certificate2.PriveteKeyは明示的に値いれようとすると、エラーになります。
Android特有の権限回りの問題なのか、ソースで解決できる問題なのかもわかってません。
Xamarin.Android触って2日目なので、実はもっと簡単だったりするかもですが、解決したら追記します。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?