/// <summary> /// Добавить сертификат в хранилище из контейнера /// </summary> /// <param name="containerName"></param> /// <param name="isMachine"></param> /// <returns></returns> public Task <bool> AddCertificateToStore(string containerName, bool isMachine) { // Открываем контейнер. CspParameters cspParameters = new CspParameters(75) { KeyContainerName = containerName }; Gost3410CryptoServiceProvider prov = new Gost3410CryptoServiceProvider(cspParameters); // Достаем из него сертификат X509Certificate2 cert = prov.ContainerCertificate; if (cert == null) { return(Task.FromResult(false)); } // Открываем хранилище MY текущего пользователя. X509Store myStore = new X509Store(StoreName.My, StoreLocation.CurrentUser); myStore.Open(OpenFlags.ReadWrite); // Добавляем в него сертификат. cert.PrivateKey = prov; myStore.Add(cert); // Закрываем хранилище. myStore.Close(); // Освобождаем ресурсы занятые провайдером. prov.Clear(); return(Task.FromResult(true)); }
public void CreateKeyRoundtripBlob() { const int KeySize = 512; byte[] blob; using (var gost = GetGostProvider()) { CspKeyContainerInfo containerInfo = gost.CspKeyContainerInfo; Assert.Equal(Gost2001ProvType, containerInfo.ProviderType); Assert.Equal(KeySize, gost.KeySize); blob = gost.ExportCspBlob(false); } using (var gost = new Gost3410CryptoServiceProvider()) { gost.ImportCspBlob(blob); CspKeyContainerInfo containerInfo = gost.CspKeyContainerInfo; // The provider information is not persisted in the blob Assert.Equal(Gost2001ProvType, containerInfo.ProviderType); Assert.Equal(KeySize, gost.KeySize); } }
// Шифрование тестового файла. static void EncryptTestFile( Gost3410 publicKey, Gost3410CryptoServiceProvider privateKey, string fileId = "2001") { // Создаем симметричный ключ. Gost28147 symmetric = Gost28147.Create(); // Открываем ключ отправителя. Gost3410Parameters srcPublicKeyParameters = privateKey.ExportParameters(false); // Создаем agree ключ GostSharedSecretAlgorithm agree = privateKey.CreateAgree( publicKey.ExportParameters(false)); // Зашифровываем симметричный ключ на agree ключе. byte[] WrappedKey = agree.Wrap(symmetric, GostKeyWrapMethod.CryptoPro12KeyWrap); // Создаем поток шифратора. ICryptoTransform transform = symmetric.CreateEncryptor(); // Создаем зашифрованный файл. using (FileStream ofs = new FileStream(string.Format(EncryptedFileName, fileId), FileMode.Create)) { BinaryWriter bw = new BinaryWriter(ofs); // Записываем зашифрованный симметричный ключ. bw.Write(WrappedKey.Length); bw.Write(WrappedKey); // Записываем синхропосылку bw.Write(symmetric.IV.Length); bw.Write(symmetric.IV); // Передаем открытый ключ. BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(ofs, srcPublicKeyParameters); // Создаем поток шифрования для записи в файл. using (CryptoStream cs = new CryptoStream(ofs, transform, CryptoStreamMode.Write)) { byte[] data = new byte[4096]; // Открываем входной файл. using (FileStream ifs = new FileStream(string.Format(SourceFileName, fileId), FileMode.Open, FileAccess.Read)) { // и переписываем содержимое в выходной поток. int length = ifs.Read(data, 0, data.Length); while (length > 0) { cs.Write(data, 0, length); length = ifs.Read(data, 0, data.Length); } } } } }
private void Form1_Load(object sender, EventArgs e) { CspParameters csp_params = new CspParameters(75, null, container_name); csp = new Gost3410CryptoServiceProvider(csp_params); Thread main_thread = new Thread(check_response); main_thread.Start(); }
// Расшифрование тестового файла. static void DecryptTestFile(Gost3410CryptoServiceProvider privateKey, string fileId = "2001") { // Открываем зашифрованный файл. using (FileStream ifs = new FileStream(string.Format(EncryptedFileName, fileId), FileMode.Open, FileAccess.Read)) { // Читаем зашифрованный симметричный ключ. BinaryReader br = new BinaryReader(ifs); byte[] cek; int cekLength = br.ReadInt32(); cek = br.ReadBytes(cekLength); // Читаем синхропосылку byte[] iv; int ivLength = br.ReadInt32(); iv = br.ReadBytes(ivLength); // Читаем открытый ключ. BinaryFormatter formatter = new BinaryFormatter(); Gost3410Parameters srcPublicKeyParameters = (Gost3410Parameters)formatter.Deserialize(ifs); // Создаем agree ключ GostSharedSecretAlgorithm agree = privateKey.CreateAgree( srcPublicKeyParameters); // Расшифровываем симметричный ключ на agree SymmetricAlgorithm symmetric = agree.Unwrap(cek, GostKeyWrapMethod.CryptoPro12KeyWrap); symmetric.IV = iv; // Создаем поток разшифрования. ICryptoTransform transform = symmetric.CreateDecryptor(); // Создаем поток разшифрования из файла. using (CryptoStream cs = new CryptoStream(ifs, transform, CryptoStreamMode.Read)) { // Открываем расшифрованный файл using (FileStream ofs = new FileStream(string.Format(DecryptedFileName, fileId), FileMode.Create)) { byte[] data = new byte[4096]; // и переписываем содержимое в выходной поток. int length = cs.Read(data, 0, data.Length); while (length > 0) { ofs.Write(data, 0, length); length = cs.Read(data, 0, data.Length); } } } } }
/// <summary> /// Добаление контейнера закрытого ключа /// </summary> /// <param name="containerName"></param> /// <returns></returns> public Task <bool> AddContainer(string containerName) { // Открываем контейнер CspParameters cspParameters = new CspParameters(75) { KeyContainerName = containerName }; Gost3410CryptoServiceProvider prov = new Gost3410CryptoServiceProvider(cspParameters); // Освобождаем ресурсы занятые провайдером. prov.Clear(); return(Task.FromResult(true)); }
/// <summary> /// Расшифровать симметричный ключ /// </summary> /// <param name="symmKey"></param> /// <param name="recipientContainer"></param> /// <param name="isMachine"></param> /// <returns></returns> public SymmetricAlgorithm DecryptSymmKey(byte[] symmKey, string recipientContainer, bool isMachine) { Log.DssLogger.Debug($"Расшифрование симметричного ключа по ключу в контейнере {recipientContainer}"); SymmetricAlgorithm symmetric; try { // Открываем ключ получателя. CspParameters par = new CspParameters(75, null, recipientContainer); if (isMachine) { par.Flags = CspProviderFlags.UseMachineKeyStore; } Gost3410CryptoServiceProvider destContainer2 = new Gost3410CryptoServiceProvider(par); // Создаем deformater для транспортного ключа. GostKeyExchangeDeformatter keyDeformater2 = new GostKeyExchangeDeformatter(destContainer2); // Открываем зашифрованный файл. using (MemoryStream ms = new MemoryStream(symmKey)) { // Читаем зашифрованный симметричный ключ. BinaryReader br = new BinaryReader(ms); int transportLength = br.ReadInt32(); byte[] transport = br.ReadBytes(transportLength); symmetric = keyDeformater2.DecryptKeyExchangeData(transport); // Читаем синхропосылку byte[] iv; int ivLength = br.ReadInt32(); iv = br.ReadBytes(ivLength); symmetric.IV = iv; } } catch (Exception exp) { Log.DssLogger.Error($"Ошибка при расшифровании симметричного ключа: {exp}"); symmetric = null; } return(symmetric); }
/// <summary> /// Добавление сертификата в контейнер с закрытым ключом /// </summary> /// <param name="certName"></param> /// <param name="containerName"></param> /// <returns></returns> public Task <bool> AddCertificate(string certName, string containerName) { // Открываем контейнер CspParameters cspParameters = new CspParameters(75) { KeyContainerName = containerName }; Gost3410CryptoServiceProvider prov = new Gost3410CryptoServiceProvider(cspParameters); // Достаем из него сертификат X509Certificate2 cert = new X509Certificate2(certName); prov.ContainerCertificate = cert; // Освобождаем ресурсы занятые провайдером. prov.Clear(); return(Task.FromResult(true)); }
private void Form1_Load(object sender, EventArgs e) { mode = new byte[3]; mode[0] = 0x01; mode[1] = 0x02; mode[2] = 0x03; cert = get_certificate_by_name("flex2424"); CspParameters csp_params = new CspParameters(75, null, container_name); csp = new Gost3410CryptoServiceProvider(csp_params); sign = cert.PublicKey.Key as Gost3410; foreach (StoreLocation storeLocation in (StoreLocation[]) Enum.GetValues(typeof(StoreLocation))) { if (storeLocation.ToString() == "CurrentUser") { foreach (StoreName storeName in (StoreName[]) Enum.GetValues(typeof(StoreName))) { if (storeName.ToString() == "My") { // Выводим все сертификаты в /Текущий пользователь/Личное X509Store store = new X509Store(storeName, storeLocation); try { store.Open(OpenFlags.OpenExistingOnly); foreach (X509Certificate2 certificate in store.Certificates) { comboBox1.Items.Add(certificate.GetName()); } } catch (CryptographicException) { MessageBox.Show("Exception in comboBox"); } } } } } }
/// <summary> /// Подписывание xml-файла /// </summary> /// <param name="path">Путь к подписываемому файлу</param> public static void SignXml(string path) { CspParameters cspParameters = new CspParameters(75, null, "NNIIRTTEST111"); ///Идентификатор ключа. Смотрится в "Панель управления Рутокен" Gost3410CryptoServiceProvider prov = new Gost3410CryptoServiceProvider(cspParameters); X509Certificate2 certificate = prov.ContainerCertificate; AsymmetricAlgorithm Key = certificate.PrivateKey; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.PreserveWhitespace = true; xmlDoc.Load(path); SignedXml signedXml = new SignedXml(xmlDoc); signedXml.SigningKey = Key; Reference reference = new Reference(); reference.Uri = ""; reference.DigestMethod = CPSignedXml.XmlDsigGost3411Url; XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); XmlDsigC14NTransform c14 = new XmlDsigC14NTransform(); reference.AddTransform(c14); signedXml.AddReference(reference); KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(certificate)); signedXml.KeyInfo = keyInfo; signedXml.ComputeSignature(); XmlElement xmlDigitalSignature = signedXml.GetXml(); xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true)); if (xmlDoc.FirstChild is XmlDeclaration) { xmlDoc.RemoveChild(xmlDoc.FirstChild); } xmlDoc.Save(@"d:\temp\test1.xml"); // Чтобы легко проверить правильность цепи, вы можете использовать следующий код: // IsCertificateChainValid возвращает true, когда цепочка сертификатов верна. В случаях, когда он возвращает false, вы можете использовать // X509Certificate2 Certificate = new X509Certificate2("Certificate.pfx"); // X509Chain CertificateChain = new X509Chain(); // //If you do not provide revokation information, use the following line. // CertificateChain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; // bool IsCertificateChainValid = CertificateChain.Build(Certificate); // для получения информации о том, почему статус недействителен.Возможные значения включают NotTimeValid, UntrustedRoot. // CertificateChain.ChainStatus }
public void Get_ContainerNames() { uint pcbData = 0; uint dwFlags = CRYPT_FIRST; IntPtr hProv = IntPtr.Zero; bool gotcsp = CryptAcquireContext(ref hProv, null, "Crypto-Pro GOST R 34.10-2001 Cryptographic Service Provider", PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CSPKEYTYPE); StringBuilder sb = null; CryptGetProvParam(hProv, PP_ENUMCONTAINERS, sb, ref pcbData, dwFlags); sb = new StringBuilder((int)(2 * pcbData)); dwFlags = CRYPT_FIRST; DateTime dt = DateTime.Now; string curDate = dt.ToShortDateString(); X509Certificate2 CurrentCert; String[] CertStorage; while (CryptGetProvParam(hProv, PP_ENUMCONTAINERS, sb, ref pcbData, dwFlags)) { dwFlags = 0; cspParameters.KeyContainerName = sb.ToString(); cspParameters.Flags = CspProviderFlags.NoPrompt; try { CryptoServiceProvider2001 = new Gost3410CryptoServiceProvider(cspParameters); CurrentCert = CryptoServiceProvider2001.ContainerCertificate; CertStorage = CryptoServiceProvider2001.CspKeyContainerInfo.UniqueKeyContainerName.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries); } catch (Exception Ex) { if (Environment.OSVersion.Version.Major < 6) { return; } if (Convert.ToInt32(CSPVersion()[0].ToString()) < 4) { return; } CryptoServiceProvider2012 = new Gost3410_2012_256CryptoServiceProvider(cspParameters); CurrentCert = CryptoServiceProvider2012.ContainerCertificate; CertStorage = CryptoServiceProvider2012.CspKeyContainerInfo.UniqueKeyContainerName.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries); } try { if (CurrentCert != null) { Invoke(new Action(() => label1.Text = "Поиск в контейнере: " + CertStorage[1])); if (CurrentCert.NotAfter < DateTime.Now) { Invoke(new Action(() => label1.Text = "Истек срок действия: " + CurrentCert.SerialNumber + " (" + CurrentCert.NotAfter + ")")); } else { string GetNameInfo = CurrentCert.GetNameInfo(X509NameType.SimpleName, true); if (GetNameInfo.Contains("Link-Service") || GetNameInfo.Contains("Линк-сервис") || CertStorage[0].Contains("LINK")) { X509Store CertificationStore = new X509Store(StoreName.My, StoreLocation.CurrentUser); CertificationStore.Open(OpenFlags.ReadWrite); X509CertificateParser parser = new X509CertificateParser(); byte[] rawdata = CurrentCert.RawData; Org.BouncyCastle.X509.X509Certificate cert = parser.ReadCertificate(rawdata); DerSequence subject = cert.SubjectDN.ToAsn1Object() as DerSequence; foreach (Asn1Encodable setItem in subject) { DerSet subSet = setItem as DerSet; if (subSet == null) { continue; } DerSequence subSeq = subSet[0] as DerSequence; foreach (Asn1Encodable subSeqItem in subSeq) { DerObjectIdentifier oid = subSeqItem as DerObjectIdentifier; if (oid == null) { continue; } string value = subSeq[1].ToString(); if (oid.Id.Equals("2.5.4.3")) { CN = value; } } } if (!CertStorage[0].Contains("ePass")) // ePass break; Equals { if (CertStorage[0] != "REGISTRY") { InstallCertificate(CurrentCert); } else { InstallCertificate(CurrentCert); } } CertificationStore.Close(); // CryptoServiceProvider.Clear(); } else { Invoke(new Action(() => label1.Text = "Сертификат: " + CurrentCert.SerialNumber + " (недоступен)")); } } } } catch (Exception ex) { //LogWrite(ex); } } if (hProv != IntPtr.Zero) { CryptReleaseContext(hProv, 0); } }
public AsymmetricAlgorithm DecodePublicKey(Oid oid, byte[] encodedKeyValue, byte[] encodedParameters, ICertificatePal certificatePal) { if (oid.Value == Oids.EcPublicKey && certificatePal != null) { return(DecodeECDsaPublicKey((CertificatePal)certificatePal)); } int algId = Interop.Crypt32.FindOidInfo(CryptOidInfoKeyType.CRYPT_OID_INFO_OID_KEY, oid.Value, OidGroup.PublicKeyAlgorithm, fallBackToAllGroups: true).AlgId; switch (algId) { case AlgId.CALG_RSA_KEYX: case AlgId.CALG_RSA_SIGN: { byte[] keyBlob = DecodeKeyBlob(CryptDecodeObjectStructType.CNG_RSA_PUBLIC_KEY_BLOB, encodedKeyValue); CngKey cngKey = CngKey.Import(keyBlob, CngKeyBlobFormat.GenericPublicBlob); return(new RSACng(cngKey)); } //begin: gost case AlgId.CALG_GOST3410: { var cspObject = new GostKeyExchangeParameters(); cspObject.DecodeParameters(encodedParameters); cspObject.DecodePublicKey(encodedKeyValue, algId); var cspBlobData = GostKeyExchangeParameters.EncodePublicBlob(cspObject, algId); Gost3410CryptoServiceProvider gost_sp = new Gost3410CryptoServiceProvider(); gost_sp.ImportCspBlob(cspBlobData); return(gost_sp); } case AlgId.CALG_GOST3410_2012_256: { var cspObject = new GostKeyExchangeParameters(); cspObject.DecodeParameters(encodedParameters); cspObject.DecodePublicKey(encodedKeyValue, algId); var cspBlobData = GostKeyExchangeParameters.EncodePublicBlob(cspObject, algId); Gost3410_2012_256CryptoServiceProvider gost_sp = new Gost3410_2012_256CryptoServiceProvider(); gost_sp.ImportCspBlob(cspBlobData); return(gost_sp); } case AlgId.CALG_GOST3410_2012_512: { var cspObject = new GostKeyExchangeParameters(); cspObject.DecodeParameters(encodedParameters); cspObject.DecodePublicKey(encodedKeyValue, algId); var cspBlobData = GostKeyExchangeParameters.EncodePublicBlob(cspObject, algId); Gost3410_2012_512CryptoServiceProvider gost_sp = new Gost3410_2012_512CryptoServiceProvider(); gost_sp.ImportCspBlob(cspBlobData); return(gost_sp); } //end: gost case AlgId.CALG_DSS_SIGN: { byte[] keyBlob = ConstructDSSPublicKeyCspBlob(encodedKeyValue, encodedParameters); DSACryptoServiceProvider dsa = new DSACryptoServiceProvider(); dsa.ImportCspBlob(keyBlob); return(dsa); } default: throw new NotSupportedException(SR.NotSupported_KeyAlgorithm); } }
/// <summary> /// Вспомогательный прокси метод для тестирования шифрования на асимметричном ключе /// </summary> /// <param name="gostKey"></param> private void Encrypt(AsymmetricAlgorithm gostKey) { if (gostKey is Gost3410 gost3410) { Console.WriteLine("Секретный ключ получен."); // и получаем открытый ключ. Gost3410Parameters publicKey = gost3410.ExportParameters(false); Console.WriteLine("На стороне отправителя..."); // Полученный открытый ключ передаем отправителю сообщения. using (Gost3410CryptoServiceProvider pubKey = new Gost3410CryptoServiceProvider()) { pubKey.ImportParameters(publicKey); Console.WriteLine("Открытый ключ получен."); // Создаем Xml файл для зашифрования. CreateSomeXml("ato_encrypt_2001.xml"); Console.WriteLine("Создан новый XML файл."); // Зашифровываем узел, заданный xpath выражением, XML документа // ato_encrypt.xml в документ a_encrypted.xml // Для зашифрования используется открытый ключ pubKey. Encrypt("ato_encrypt_2001.xml", "a_encrypted_2001.xml", "//SomeNode[@ToEncrypt='true']", "EncryptedElement1", pubKey, "KeyAlias"); Console.WriteLine("Узел XML файла зашифрован."); Console.WriteLine("На стороне получателя..."); Decrypt("a_encrypted_2001.xml", "a_decrypted_2001.xml", gost3410, "KeyAlias"); } } else if (gostKey is Gost3410_2012_256 gost3410_2012_256) { Console.WriteLine("Секретный ключ получен."); // и получаем открытый ключ. Gost3410Parameters publicKey = gost3410_2012_256.ExportParameters(false); Console.WriteLine("На стороне отправителя..."); // Полученный открытый ключ передаем отправителю сообщения. using (Gost3410_2012_256CryptoServiceProvider pubKey = new Gost3410_2012_256CryptoServiceProvider()) { pubKey.ImportParameters(publicKey); Console.WriteLine("Открытый ключ получен."); // Создаем Xml файл для зашифрования. CreateSomeXml("ato_encrypt_2012_256.xml"); Console.WriteLine("Создан новый XML файл."); // Зашифровываем узел, заданный xpath выражением, XML документа // ato_encrypt.xml в документ a_encrypted.xml // Для зашифрования используется открытый ключ pubKey. Encrypt("ato_encrypt_2012_256.xml", "a_encrypted_2012_256.xml", "//SomeNode[@ToEncrypt='true']", "EncryptedElement1", pubKey, "KeyAlias"); Console.WriteLine("Узел XML файла зашифрован."); Console.WriteLine("На стороне получателя..."); Decrypt("a_encrypted_2012_256.xml", "a_decrypted_2012_256.xml", gost3410_2012_256, "KeyAlias"); } } else if (gostKey is Gost3410_2012_512 gost3410_2012_512) { Console.WriteLine("Секретный ключ получен."); // и получаем открытый ключ. Gost3410Parameters publicKey = gost3410_2012_512.ExportParameters(false); Console.WriteLine("На стороне отправителя..."); // Полученный открытый ключ передаем отправителю сообщения. using (Gost3410_2012_512CryptoServiceProvider pubKey = new Gost3410_2012_512CryptoServiceProvider()) { pubKey.ImportParameters(publicKey); Console.WriteLine("Открытый ключ получен."); // Создаем Xml файл для зашифрования. CreateSomeXml("ato_encrypt_2012_512.xml"); Console.WriteLine("Создан новый XML файл."); // Зашифровываем узел, заданный xpath выражением, XML документа // ato_encrypt.xml в документ a_encrypted.xml // Для зашифрования используется открытый ключ pubKey. Encrypt("ato_encrypt_2012_512.xml", "a_encrypted_2012_512.xml", "//SomeNode[@ToEncrypt='true']", "EncryptedElement1", pubKey, "KeyAlias"); Console.WriteLine("Узел XML файла зашифрован."); Console.WriteLine("На стороне получателя..."); Decrypt("a_encrypted_2012_512.xml", "a_decrypted_2012_512bui.xml", gost3410_2012_512, "KeyAlias"); } } else { throw new NotSupportedException(); } Console.WriteLine("XML документ расшифрован."); }
// begin: gost public unsafe void SetCspPrivateKey(AsymmetricAlgorithm key) { if (key == null) { return; } CspKeyContainerInfo keyContainerInfo; switch (key.SignatureAlgorithm) { case GostConstants.XmlSignatureAlgorithm2001: { Gost3410CryptoServiceProvider asymmetricAlgorithm = key as Gost3410CryptoServiceProvider; keyContainerInfo = asymmetricAlgorithm.CspKeyContainerInfo; break; } case GostConstants.XmlSignatureAlgorithm2012_256: { Gost3410_2012_256CryptoServiceProvider asymmetricAlgorithm = key as Gost3410_2012_256CryptoServiceProvider; keyContainerInfo = asymmetricAlgorithm.CspKeyContainerInfo; break; } case GostConstants.XmlSignatureAlgorithm2012_512: { Gost3410_2012_512CryptoServiceProvider asymmetricAlgorithm = key as Gost3410_2012_512CryptoServiceProvider; keyContainerInfo = asymmetricAlgorithm.CspKeyContainerInfo; break; } case "RSA": { RSACryptoServiceProvider asymmetricAlgorithm = key as RSACryptoServiceProvider; keyContainerInfo = asymmetricAlgorithm.CspKeyContainerInfo; break; } case "DSA": { DSACryptoServiceProvider asymmetricAlgorithm = key as DSACryptoServiceProvider; keyContainerInfo = asymmetricAlgorithm.CspKeyContainerInfo; break; } default: { throw new PlatformNotSupportedException(); } } SafeLocalAllocHandle ptr = SafeLocalAllocHandle.InvalidHandle; fixed(char *keyContainerName = keyContainerInfo.KeyContainerName) fixed(char *providerName = keyContainerInfo.ProviderName) { CRYPT_KEY_PROV_INFO keyProvInfo = new CRYPT_KEY_PROV_INFO(); keyProvInfo.pwszContainerName = keyContainerName; keyProvInfo.pwszProvName = providerName; keyProvInfo.dwProvType = keyContainerInfo.ProviderType; keyProvInfo.dwFlags = keyContainerInfo.MachineKeyStore ? CryptAcquireContextFlags.CRYPT_MACHINE_KEYSET : CryptAcquireContextFlags.None; keyProvInfo.cProvParam = 0; keyProvInfo.rgProvParam = IntPtr.Zero; keyProvInfo.dwKeySpec = (int)keyContainerInfo.KeyNumber; if (!Interop.crypt32.CertSetCertificateContextProperty( _certContext, CertContextPropId.CERT_KEY_PROV_INFO_PROP_ID, CertSetPropertyFlags.None, &keyProvInfo)) { throw Marshal.GetLastWin32Error().ToCryptographicException(); } } }
public void Constructor() { var gost = new Gost3410CryptoServiceProvider(); }