2007年10月5日星期五

C# Active Control で証明書を使って署名

目標

  • C# ActiveX Controlで証明書を使って署名する技術の紹介

開発環境

  • Microsoft Visual C# 2005 Express Edition

ポイント

ローカルマシンンから証明書を取得

  • Current Userの証明書集合を取得します(ICカードにある証明書も含まれています):
               X509Certificate2Collection cerCollection = null;
    //Get The Certificates of Current User
    X509Store store = new X509Store(StoreLocation.CurrentUser);
    store.Open(OpenFlags.ReadOnly);
    if (store.Certificates != null && store.Certificates.Count > 0)
    {
    cerCollection = (X509Certificate2Collection)store.Certificates;
    }
  • 証明書をcerCollectionから取得して処理します。
               if (cerCollection != null && cerCollection .Count > 0)
    {
    foreach (X509Certificate2 cer in cerCollection )
    {
    //証明書に対する処理
    Console.WriteLine(cer.Subject);
    }
    }

証明書を使って署名

       public byte[] sign(byte[] data, X509Certificate2 cert)
{
RSACryptoServiceProvider csp = (RSACryptoServiceProvider)cert.PrivateKey;
byte[] byteEncrypt = csp.SignData(data, "SHA1");
return byteEncrypt;
}

署名のCOM Componentの作成

  • タイプ「X509Certificate2」がJavascriptと直接に通信できないので、その代わりに、証明書のインデックスを使います
       [ClassInterface(ClassInterfaceType.AutoDual)]
    public class SignService
    {
    //data : 署名するデータ
    //index : 署名用の証明書が証明書集合にのインデックス
    //return : Base64でエンコードされた署名
    public String sign(String data, int index){
    X509Store store = new X509Store(StoreLocation.CurrentUser);
    store.Open(OpenFlags.ReadOnly);
    X509Certificate2Collection certCollection = (X509Certificate2Collection)store.Certificates;
    X509Certificate2 cert = certCollection[index];
    RSACryptoServiceProvider csp = (RSACryptoServiceProvider)cert.PrivateKey;
    byte[] sig = csp.SignData(data, "SHA1");
    String result = System.Convert.ToBase64String(sig);
    }
    }

参考資料

没有评论: