我在电子邮件中解密Smime.p7m附件。我目前有以下
EnvelopedCms envDate = new EnvelopedCms(new ContentInfo(data));
envDate.Decode(data);
RecipientInfoCollection recips = envDate.RecipientInfos;
RecipientInfo recipin = recips[0];
X509Certificate2 x509_2 = LoadCertificate2(StoreLocation.CurrentUser, (SubjectIdentifier)recipin.RecipientIdentifier);
和负载证书看起来像
public static X509Certificate2 LoadCertificate2(StoreLocation storeLocation, SubjectIdentifier identifier)
{
X509Store store = new X509Store(storeLocation);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certCollection = store.Certificates;
X509Certificate2 x509 = null;
X509IssuerSerial issuerSerial;
if (identifier.Type == SubjectIdentifierType.IssuerAndSerialNumber)
{
issuerSerial = (X509IssuerSerial)identifier.Value;
}
foreach (X509Certificate2 c in certCollection)
{
Console.WriteLine("{0}Valid Date: {1}{0}", Environment.NewLine, c.NotBefore);
if (c.SerialNumber == issuerSerial.SerialNumber && c.Issuer == issuerSerial.IssuerName)
{
x509 = c;
break;
}
}
if (x509 == null)
Console.WriteLine("A x509 certificate for was not found");
store.Close();
return x509;
}
上面的代码仅获取第一个收件人收件人focorn = recips [0];然而
获得正确的证书后,我会使用此
X509Certificate2Collection col = new X509Certificate2Collection(x509_2);
envDate.Decrypt(col);
decData = envDate.ContentInfo.Content;
这提示了与证书的私人键关联的PIN,我如何在调用解密之前添加PIN,以便没有提示?
.NET Framework中的emplackedCMS类无法让您轻松地编程使用PIN(或其他解锁机制);因此,特别是如果该证书存在于当前使用者我或LocalMachine 我的商店中(因为在Extrastore集合中的任何证书之前搜索了这些证书)。
在.NET框架4.7 上,您可以以一种非常回旋的方式来完成CNG访问的键,前提是证书也不在CurrentUser My或LocalMachine My My Stores中:
CngKey key = ExerciseLeftToTheReader();
key.SetProperty(new CngProperty("SmartCardPin", pin, CngPropertyOptions.None));
X509Certificate2 cert = DifferentExerciseLeftToTheReader();
// You need to use tmpCert because this won't do good things if the certificate
// already knows about/how-to-find its associated private key
using (key)
using (X509Certificate2 tmpCert = new X509Certificate2(cert.RawData))
{
// Need to NOT read the HasPrivateKey property until after the property set. Debugger beware.
NativeMethods.CertSetCertificateContextProperty(
tmpCert.Handle,
CERT_NCRYPT_KEY_HANDLE_PROP_ID,
CERT_SET_PROPERTY_INHIBIT_PERSIST_FLAG,
key.Handle);
envelopedCms.Decrypt(new X509Certificate2Collection(tmpCert));
}
(当然,您需要为certsetcertificatecontextextproperty定义P/Invoke)
在.net core 3.0中,这变得更容易(此功能当前可用预览2)...尽管它确实使您承担确定哪个收件人的负担,并且哪个钥匙随之而来:
RecipientInfo recipientInfo = FigureOutWhichOneYouCanMatch();
CngKey key = ExerciseLeftToTheReader();
key.SetProperty(new CngProperty("SmartCardPin", pin, CngPropertyOptions.None));
using (key)
using (RSA rsa = new RSACng(key))
{
envelopedCms.Decrypt(recipientInfo, rsa);
}