OpenSSLを使用して秘密鍵と公開鍵のペアを作成し、.p12ファイルを生成してWindows証明書ストアにインポートしました。キーペアと.p12ファイルはWindowsXPで作成されており、Windows 7で使用しようとしています。IISのWebサービス(.svc)内からキーにアクセスしようとしています。スタンドアロンアプリから秘密鍵を読み取ろうとすると問題なく実行できますが、Webアプリから秘密鍵を読み取ろうとすると、常に次の例外が発生します。
'cert.PrivateKey' threw an exception of type 'System.Security.Cryptography.CryptographicException'
そして、これはスタックトレース全体です。
en System.Security.Cryptography.Utils.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)
en System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType, CspParameters parameters, Boolean randomKeyContainer, Int32 dwKeySize, SafeProvHandle& safeProvHandle, SafeKeyHandle& safeKeyHandle)
en System.Security.Cryptography.RSACryptoServiceProvider.GetKeyPair()
en System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 dwKeySize, CspParameters parameters, Boolean useDefaultKeySize)
en System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey()
en ValidKeyDll.ValidKey.getLlaveDeAlmacen(String almacen, Boolean esLlavePrivada) en C:\Users\desarrollo\Documents\ValidKeyDll\ValidKeyDll\ValidKey.cs:línea 58
en ValidKeyDll.ValidKey.firmaCadena(String almacen, String cadenaFirmar) en C:\Users\desarrollo\Documents\ValidKeyDll\ValidKeyDll\ValidKey.cs:línea 117
そして、これはキーを読み取るコードの私の部分です:
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
RSACryptoServiceProvider csp = null;
foreach (X509Certificate2 cert in store.Certificates)
{
if (cert.Subject.Contains(almacen))
{
if (cert.NotAfter.CompareTo(System.DateTime.Now) <= 0)
throw new CertificadoVencidoException();
if (isPrivateKey)
csp = (RSACryptoServiceProvider)cert.PrivateKey;
else
csp = (RSACryptoServiceProvider)cert.PublicKey.Key;
break;
}
}
なんらかの許可の問題と関係があると思いますが、それが何なのかわかりません…何か提案があれば大歓迎です。
考慮事項:
- 秘密鍵はエクスポート可能です。
- ユーザーIIS_IUSRSには、証明書に対するアクセス許可があります。