Ключевое слово в защите информации
КЛЮЧЕВОЕ СЛОВО
в защите информации
Получить ГОСТ TLS-сертификат для домена (SSL-сертификат)
Добро пожаловать, Гость! Чтобы использовать все возможности Вход. Новые регистрации запрещены.

Уведомление

Icon
Error

Опции
К последнему сообщению К первому непрочитанному
Offline Leonra_NzOe075n  
#1 Оставлено : 30 мая 2025 г. 13:22:09(UTC)
Leonra_NzOe075n

Статус: Новичок

Группы: Участники
Зарегистрирован: 24.11.2023(UTC)
Сообщений: 9
Российская Федерация

Сказал(а) «Спасибо»: 1 раз
Здравствуйте, уважаемые форумчане!
Помогите, пожалуйста, разобраться с проблемой.

Требуется, чтобы приложение (служба) могли выполнять ComputeSignature сертификатом по заданному отпечатку.
И чтобы эта служба работала от системы (не от пользователя).

StoreLocation = LocalMachine, StoreName = My

Код:
public byte[] DoIt(string thumbprint, string msg)
{
    Encoding unicode = Encoding.UTF8;
    byte[] msgBytes = unicode.GetBytes(msg);
    X509Certificate2 signerCert = GetSignerCert(thumbprint);
    byte[] encodedSignature = SignMsg(msgBytes, signerCert);
    VerifyMsg(msgBytes, encodedSignature);
    return encodedSignature;
}

private X509Certificate2 GetSignerCert(string thumbprint)
{
    var storeMy = new X509Store(StoreName, StoreLocation);
    storeMy.Open(OpenFlags.ReadOnly);
    X509Certificate2Collection certColl = storeMy.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
    storeMy.Close();
    return certColl[0];
}

private static byte[] SignMsg(byte[] msg, X509Certificate2 signerCert)
{
    var contentInfo = new ContentInfo(msg);
    var signedCms = new SignedCms(contentInfo, true);
    var cmsSigner = new CmsSigner(signerCert);
    cmsSigner.SignedAttributes.Add(new Pkcs9SigningTime(DateTime.Now));
    signedCms.ComputeSignature(cmsSigner);
    return signedCms.Encode();
}

private static void VerifyMsg(byte[] msg, byte[] encodedSignature)
{
    var contentInfo = new ContentInfo(msg);
    var signedCms = new SignedCms(contentInfo, true);
    signedCms.Decode(encodedSignature);
    signedCms.CheckSignature(true);
}


Сертификат вместе с закрытым ключом экспортировали и установили в хранилище LocalMachine/My.
При этом если открыть "Управление закрытыми ключами", то там у Системы полный доступ к сертификату.

Но при создании подписи падает ошибка "Набор ключей не существует":

Цитата:
Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: Набор ключей не существует
at Internal.NativeCrypto.CapiHelper.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)
at System.Security.Cryptography.Gost3410_2012_256CryptoServiceProvider.get_SafeProvHandle()
at System.Security.Cryptography.Gost3410_2012_256CryptoServiceProvider.get_SafeKeyHandle()
at System.Security.Cryptography.Gost3410_2012_256CryptoServiceProvider.GetKeyPair()
at System.Security.Cryptography.Gost3410_2012_256CryptoServiceProvider..ctor(CspParameters parameters)
at Internal.Cryptography.Pal.Windows.PkcsPalWindows.GetPrivateKey[T](X509Certificate2 certificate, Boolean silent, Boolean preferNCrypt) in C:\projects\corefx\src\System.Security.Cryptography.Pkcs\src\Internal\Cryptography\Pal\Windows\PkcsPalWindows.cs:line 285
at Internal.Cryptography.Pal.Windows.PkcsPalWindows.GetPrivateKeyForSigning[T](X509Certificate2 certificate, Boolean silent) in C:\projects\corefx\src\System.Security.Cryptography.Pkcs\src\Internal\Cryptography\Pal\Windows\PkcsPalWindows.cs:line 181
at System.Security.Cryptography.Pkcs.CmsSignature.Gost2012_256CmsSignature.Sign(ReadOnlySpan`1 dataHash, HashAlgorithmName hashAlgorithmName, X509Certificate2 certificate, AsymmetricAlgorithm key, Boolean silent, Oid& signatureAlgorithm, Byte[]& signatureValue) in C:\projects\corefx\src\System.Security.Cryptography.Pkcs\src\System\Security\Cryptography\Pkcs\CmsSignature.Gost2012_256.cs:line 71
at System.Security.Cryptography.Pkcs.CmsSignature.Sign(ReadOnlySpan`1 dataHash, HashAlgorithmName hashAlgorithmName, X509Certificate2 certificate, AsymmetricAlgorithm key, Boolean silent, Oid& oid, ReadOnlyMemory`1& signatureValue) in C:\projects\corefx\src\System.Security.Cryptography.Pkcs\src\System\Security\Cryptography\Pkcs\CmsSignature.cs:line 104
at System.Security.Cryptography.Pkcs.CmsSigner.Sign(ReadOnlyMemory`1 data, String contentTypeOid, Boolean silent, X509Certificate2Collection& chainCerts) in C:\projects\corefx\src\System.Security.Cryptography.Pkcs\src\System\Security\Cryptography\Pkcs\CmsSigner.cs:line 251
at System.Security.Cryptography.Pkcs.SignedCms.ComputeSignature(CmsSigner signer, Boolean silent) in C:\projects\corefx\src\System.Security.Cryptography.Pkcs\src\System\Security\Cryptography\Pkcs\SignedCms.cs:line 323
at System.Security.Cryptography.Pkcs.SignedCms.ComputeSignature(CmsSigner signer) in C:\projects\corefx\src\System.Security.Cryptography.Pkcs\src\System\Security\Cryptography\Pkcs\SignedCms.cs:line 274
at EpguSignatureService.Helpers.DetachedSignatureHelper.SignMsg(Byte[] msg, X509Certificate2 signerCert) in


В чем может быть проблема? Неправильный экспорт и/или установка сертификата?

Wanna join the discussion?! Login to your Форум КриптоПро forum account. Новые регистрации запрещены.

Offline Андрей *  
#2 Оставлено : 30 мая 2025 г. 13:44:15(UTC)
Андрей *

Статус: Сотрудник

Группы: Участники
Зарегистрирован: 26.07.2011(UTC)
Сообщений: 13,727
Мужчина
Российская Федерация

Сказал «Спасибо»: 574 раз
Поблагодарили: 2303 раз в 1804 постах
Здравствуйте.

Тестирование по сертификату сделали в панели управления?
Контейнер где находится?
Техническую поддержку оказываем тут
Наша база знаний
Offline Андрей *  
#3 Оставлено : 30 мая 2025 г. 13:45:46(UTC)
Андрей *

Статус: Сотрудник

Группы: Участники
Зарегистрирован: 26.07.2011(UTC)
Сообщений: 13,727
Мужчина
Российская Федерация

Сказал «Спасибо»: 574 раз
Поблагодарили: 2303 раз в 1804 постах
Протестировать по сертификату, контейнер - компьютера.
Snimok ehkrana ot 2025-05-30 14-44-19.png (21kb) загружен 3 раз(а).
Техническую поддержку оказываем тут
Наша база знаний
RSS Лента  Atom Лента
Пользователи, просматривающие эту тему
Guest
Быстрый переход  
Вы не можете создавать новые темы в этом форуме.
Вы не можете отвечать в этом форуме.
Вы не можете удалять Ваши сообщения в этом форуме.
Вы не можете редактировать Ваши сообщения в этом форуме.
Вы не можете создавать опросы в этом форуме.
Вы не можете голосовать в этом форуме.