EnvelopedCms, как правильно определить сертификат для расшифровки и не запрашивать пароль? - PullRequest
0 голосов
/ 21 февраля 2019

Я расшифровываю вложения 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;
        }

Приведенный выше код получает только первый получатель RecipientInfo recein = recips [0];однако самый эффективный способ получить соответствующий сертификат для циклического прохождения через каждого получателя и проверить хранилище для SubjectIdentifier?

После получения правильного сертификата я использую этот

                X509Certificate2Collection col = new X509Certificate2Collection(x509_2);
                envDate.Decrypt(col);
               decData = envDate.ContentInfo.Content;

Это запрашиваетPIN-код, связанный с приватным ключом сертификата, как я могу добавить PIN-код перед расшифровкой вызова, чтобы не было подсказки?

1 Ответ

0 голосов
/ 21 февраля 2019

Класс EnvelopedCms в .NET Framework не позволяет легко программно применить PIN-код (или другой механизм разблокировки);особенно если сертификат существует в хранилищах CurrentUser \ My или LocalMachine \ My (потому что они ищутся до каких-либо сертификатов в коллекции extraStore).

В .NET Framework 4.7+ вы можете выполнить его очень быстро.обходной способ для ключей, доступных для CNG, при условии, что сертификат также отсутствует в хранилищах CurrentUser \ My или LocalMachine \ My:

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));
}

(и, конечно, вам необходимо определить P / Invoke для CertSetCertificateContextProperty)

В .NET Core 3.0 это становится проще (предварительный просмотр 2 в настоящее время доступен с этой функцией) ... хотя на вас и остается бремя определения, какой вы RecipientInfo, и какой ключ к нему подходит:

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);
}
...