简体   繁体   中英

Import method of windows security encryption algorithm is not working in hosting environment

I need to use RSA cryptography for encryption of data. I have used ImportPkcs8PrivateKey method of System.Security.Cryptography for importing private key. The code working fine in visual studio but only ImportPkcs8PrivateKey method is not working in hosting server. My Hosting server is windows 2019 and I have installed all hosting package.

var privateKeyBytes = Convert.FromBase64String(marchentPrivateKey);
int myarray;
var rsa = RSA.Create();
rsa.ImportPkcs8PrivateKey(privateKeyBytes, out myarray);
return rsa;

The following Error trace is generated in hosted server

 at lambda_method(Closure , Object )
   at Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResult()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(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()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextExceptionFilterAsync>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)

Actually its issue of IIS setting. Cryptographic Service Provider try to store a key for certificate in the user store and if a profile was not available, a cryptographic context was not available. By default IIS Load User Profile is false. See for more details What exactly happens when I set LoadUserProfile of IIS pool?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM