ストアからの証明書に問題があります。私のアプリでは、ユーザーはファイルからの証明書またはストアからの証明書を使用できます。証明書を読み込んだ後、署名データに証明書を使用します。
ファイルから証明書を使用しても問題ありませんが、ストアから同等のものを使用することはできません。
記号のコード:
// Sign data
using (RSACryptoServiceProvider csp = new RSACryptoServiceProvider())
{
byte[] dataToSign = Encoding.UTF8.GetBytes(plainText);
csp.ImportParameters(((RSACryptoServiceProvider)_certPopl.PrivateKey).ExportParameters(true));
byte[] signature = csp.SignData(dataToSign, "SHA256");
// Verify signature
if (!csp.VerifyData(dataToSign, "SHA256", signature))
throw new Exception("Nepodařilo se vytvořit platný podpisový kód poplatníka.");
PKP = Convert.ToBase64String(signature);
}
ファイルから証明書を読み取るためのコード:
X509Certificate2Collection certStore = new X509Certificate2Collection();
certStore.Import(fileName, password, X509KeyStorageFlags.Exportable);
foreach (X509Certificate2 cert in certStore)
{
// Find the first certificate with a private key
if (cert.HasPrivateKey)
{
_certPopl = cert;
break;
}
}
ストアから証明書を読み取るためのコード。ストアから証明書をロードした後、データに署名できません:
public void LoadCertificate(string certificateName, DateTime notAfter, string password)
{
var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.MaxAllowed);
foreach (var certificate in store.Certificates)
{
if (certificate.FriendlyName.Equals(certificateName) && certificate.NotAfter.Equals(notAfter))
{
//X509Certificate2Collection certStore = new X509Certificate2Collection();
//certStore.Import(certificate.Export(X509ContentType.SerializedCert), password, X509KeyStorageFlags.Exportable);
//_certPopl = certStore[0];
X509Certificate2Collection certStore = new X509Certificate2Collection();
certStore.Import(certificate.GetRawCertData());
foreach (X509Certificate2 cert in certStore)
{
// Find the first certificate with a private key
if (cert.HasPrivateKey)
{
_certPopl = cert;
break;
}
}
break;
}
}
}
証明書を扱った経験がありません。しかし、署名のためにストアから証明書を取得するのと同等のものが必要です。
System.Security.Cryptography.CryptographicException が ExportParameters(true) でスローされます。例外の追加情報: キーは指定された状態での使用には無効です。
ありがとう。