Работает под Kestrel, не работает под IIS.
Набор, свойства сертификатов смотрел в отладчике, совпадают.
ТаксКом сертификат присутствует, одинаковый.
В чём ошибка, как исправить?
using API.HonorSignServices.Interfaces;
using BarcodesServices;
using Domain.HonorSignModels;
using Microsoft.Extensions.Options;
namespace API.Controllers;
[ApiController]
[Route("api/[controller]")]
public sealed class MarksInfosController : ControllerBase
{
private readonly TokenSettings _tokenSettings;
private readonly MarksForCheckingModifier _marksForCheckingModifier;
private readonly IMarksInfosService _marksInfosService;
public MarksInfosController(IOptionsMonitor<TokenSettings> tokenSettings, MarksForCheckingModifier marksForCheckingModifier, IMarksInfosService marksInfosService)
{
_tokenSettings = tokenSettings.CurrentValue;
_marksForCheckingModifier = marksForCheckingModifier;
_marksInfosService = marksInfosService;
}
[HttpPost("signData")]
public async Task<ActionResult<Token>> SignData()
{
Token token = await _marksInfosService.GetHonorSignTokenAsync(_tokenSettings.TokenReceiverInn, _tokenSettings.TokenProviderInn);
if (token is not null)
{
return Ok(token);
}
return NotFound("Token not found");
}
[HttpPost("cises/info")]
public async Task<ActionResult<IEnumerable<CisResponseItem>>> GetCisesInfo(MarksInfosGettingModel marksInfosGettingModel)
{
try
{
var roots = await _marksInfosService.GetCisesInfo(marksInfosGettingModel);
return Ok(roots);
}
catch (Exception ex)
{
return BadRequest(ex);
}
}
}
using API.HonorSignServices.Interfaces;
using BarcodesServices;
using CryptoPro.Security.Cryptography.Pkcs;
using CryptoPro.Security.Cryptography.X509Certificates;
using Domain.HonorSignModels;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Net.Http.Json;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.Json;
namespace API.HonorSignServices.Classes;
public sealed class MarksInfosService : IMarksInfosService
{
private readonly ILogger<MarksInfosService> _logger;
private readonly MarksForCheckingModifier _marksForCheckingModifier;
private readonly TokenSettings _tokenSettings;
public MarksInfosService(MarksForCheckingModifier marksForCheckingModifier, IOptionsMonitor<TokenSettings> tokenSettings, ILogger<MarksInfosService> logger)
{
_marksForCheckingModifier = marksForCheckingModifier;
_tokenSettings = tokenSettings.CurrentValue;
_logger = logger;
}
public async Task<IEnumerable<CisResponseItem>> GetCisesInfo(MarksInfosGettingModel marksInfosGettingModel)
{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_tokenSettings.TokenValue}");
IEnumerable<string> modifiedMarks = marksInfosGettingModel.MarksToGetInfos.Select(m => _marksForCheckingModifier.ModifyStringIfConditionMet(m));
HttpResponseMessage marksInfosHttpResponseMessage = await httpClient.PostAsJsonAsync<IEnumerable<string>>("https://markirovka.crpt.ru/api/v3/true-api/cises/info", marksInfosGettingModel.MarksToGetInfos.Select(m => _marksForCheckingModifier.ModifyStringIfConditionMet(m)));
if (marksInfosHttpResponseMessage.IsSuccessStatusCode)
{
try
{
var roots = await JsonSerializer.DeserializeAsync<IEnumerable<CisResponseItem>>(await marksInfosHttpResponseMessage.Content.ReadAsStreamAsync());
return roots;
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
return null;
}
}
_logger.LogError($"GetCisesInfo error: {await marksInfosHttpResponseMessage.Content.ReadAsStringAsync()}");
return null;
}
public async Task<Token> GetHonorSignTokenAsync(string tokenReceiverInn, string tokenProviderInn)
{
using (var store = new CpX509Store(StoreName.My, StoreLocation.LocalMachine))
{
store.Open(OpenFlags.ReadOnly);
var cert = store.Certificates.Find(X509FindType.FindBySubjectName, tokenReceiverInn, false)[0];
if (cert is not null)
{
var httpClient = new HttpClient();
var authKey = await httpClient.GetFromJsonAsync<AuthKey>("https://markirovka.crpt.ru/api/v3/true-api/auth/key");
byte[] msgBytes = Encoding.UTF8.GetBytes(authKey.Data);
var contentInfo = new ContentInfo(msgBytes);
var signedCms = new CpSignedCms(contentInfo, false);
var cmsSigner = new CpCmsSigner(cert)
{
IncludeOption = X509IncludeOption.EndCertOnly
};
signedCms.ComputeSignature(cmsSigner);
byte[] encodedSignature = signedCms.Encode();
var httpResponseMessage = await httpClient.PostAsJsonAsync<AuthKeyInn>("https://markirovka.crpt.ru/api/v3/true-api/auth/simpleSignIn", new AuthKeyInn(authKey.UUID, Convert.ToBase64String(encodedSignature), tokenProviderInn));
if (httpResponseMessage.IsSuccessStatusCode)
{
Token token = await JsonSerializer.DeserializeAsync<Token>(await httpResponseMessage.Content.ReadAsStreamAsync());
return token;
}
throw new Exception(await httpResponseMessage.Content.ReadAsStringAsync());
}
return null;
}
}
}
System.Security.Cryptography.CryptographicException: Неправильный зарегистрированный набор ключей.
at Internal.Cryptography.Pal.Windows.PkcsPalWindows.GetPrivateKey[T](CpX509Certificate2 certificate, Boolean silent, Boolean preferNCrypt)
at Internal.Cryptography.Pal.Windows.PkcsPalWindows.GetPrivateKeyForSigning[T](CpX509Certificate2 certificate, Boolean silent)
at CryptoPro.Security.Cryptography.CpCmsSignature.Gost2012_256CmsSignature.Sign(ReadOnlySpan`1 dataHash, HashAlgorithmName hashAlgorithmName, CpX509Certificate2 certificate, AsymmetricAlgorithm key, Boolean silent, String& signatureAlgorithm, Byte[]& signatureValue, Byte[]& signatureParameters)
at CryptoPro.Security.Cryptography.CpCmsSignature.Sign(ReadOnlySpan`1 dataHash, HashAlgorithmName hashAlgorithmName, CpX509Certificate2 certificate, AsymmetricAlgorithm key, Boolean silent, RSASignaturePadding rsaSignaturePadding, String& oid, ReadOnlyMemory`1& signatureValue, ReadOnlyMemory`1& signatureParameters)
at CryptoPro.Security.Cryptography.Pkcs.CpCmsSigner.Sign(ReadOnlyMemory`1 data, String contentTypeOid, Boolean silent, CpX509Certificate2Collection& chainCerts)
at CryptoPro.Security.Cryptography.Pkcs.CpSignedCms.ComputeSignature(CpCmsSigner signer, Boolean silent)
at CryptoPro.Security.Cryptography.Pkcs.CpSignedCms.ComputeSignature(CpCmsSigner signer)
at API.HonorSignServices.Classes.MarksInfosService.GetHonorSignTokenAsync(String tokenReceiverInn, String tokenProviderInn) in D:\WebSites\Scanning\API.HonorSignServices\Classes\MarksInfosService.cs:line 77
at API.Controllers.MarksInfosController.SignData() in D:\WebSites\Scanning\Api\Controllers\MarksInfosController.cs:line 26
at lambda_method6(Closure, Object)
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(ActionContext actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)
HEADERS
=======
Accept: text/plain
Accept-Encoding: gzip, deflate, br, zstd
Accept-Language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7
Connection: close
Content-Length: 0
Host: 172.16.1.62
Referer:
https://172.16.1.62/swagger/index.htmlUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36
sec-ch-ua-platform: "Windows"
sec-ch-ua: "Chromium";v="140", "Not=A?Brand";v="24", "Google Chrome";v="140"
sec-ch-ua-mobile: ?0
origin:
https://172.16.1.62sec-fetch-site: same-origin
sec-fetch-mode: cors
sec-fetch-dest: empty
priority: u=1, i