ASP.NET - The specified network password is not correct
Asked Answered
S

5

42

I have in my dev machine a WCF Client which requires certificate and it is working fine.
After the deployment to production server I get the following Error:

[CryptographicException: The specified network password is not correct.]

DEV - Win7 32BIT IIS 7.5
PRODUCTION - Win SERVER 64BIT 2008 IIS 7.5

Even though there is no password between the networks and there is not certificate password. (I know because the dev works with no password). The only password that I have is the WCF one that is the same as the DEV.

CrmServiceClient crm = new CrmServiceClient("CrmServiceEndpoint");
crm.ClientCredentials.UserName.UserName = CrmConfigRepository.CrmUserName;//fine
crm.ClientCredentials.UserName.Password = CrmConfigRepository.CrmPassword;//fine
crm.ClientCredentials.ClientCertificate.Certificate = new X509Certificate2(Path);
///THIS WONT WORK AS WELL
crm.ClientCredentials.ClientCertificate.Certificate = new X509Certificate2(Path, "", X509KeyStorageFlags.Exportable); 

this is the full stack

[CryptographicException: The specified network password is not correct. ]
   System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr) +41
   System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromFile(String fileName, IntPtr password, UInt32 dwFlags, Boolean persistKeySet, SafeCertContextHandle& pCertCtx) +0
   System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromFile(String fileName, Object password, X509KeyStorageFlags keyStorageFlags) +372
   System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(String fileName) +101
   Externals.CrmConnection.Get() in C:\Users\avi\Documents\Visual Studio 2010\Projects\ExpressBroker\Externals\CrmConnection.cs:31
   ExpressBroker.Models.ActionsMetadata.Handlers.LeadAccountHandler.Handle(BrokerAction brokerAction, ActionStep step, Dictionary`2 httpPostDataCollection) in C:\Users\avi\Documents\Visual Studio 2010\Projects\ExpressBroker\ExpressBroker\Models\ActionsMetadata\Handlers\LeadAccountHandler.cs:45
   ExpressBroker.Models.ActionsMetadata.Handlers.BaseStepHandler.SecuredHandle(BrokerAction brokerAction, ActionStep step, Dictionary`2 httpPostDataCollection) in C:\Users\avi\Documents\Visual Studio 2010\Projects\ExpressBroker\ExpressBroker\Models\ActionsMetadata\Handlers\BaseStepHandler.cs:49
   ExpressBroker.Models.ActionsMetadata.Handlers.HandlerInvoker.Invoke(BrokerAction brokerAction, ActionStep actionStep, Dictionary`2 stepValues) in C:\Users\avi\Documents\Visual Studio 2010\Projects\ExpressBroker\ExpressBroker\Models\ActionsMetadata\Handlers\StepServerInoker.cs:29
   ExpressBroker.Controllers.LeadAccountController.Register(String step) in C:\Users\avi\Documents\Visual Studio 2010\Projects\ExpressBroker\ExpressBroker\Controllers\LeadAccountController.cs:28
   lambda_method(Closure , ControllerBase , Object[] ) +127
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +264
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +39
   System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +129
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +784922
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +314
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +784976
   System.Web.Mvc.Controller.ExecuteCore() +159
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +335
   System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +62
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +20
   System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +54
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +453
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +371

Thanks

Salutary answered 27/11, 2011 at 14:4 Comment(2)
What is the path passed in the X509Certificates constructor? I think it is the network password accessing the certificate file.Aerie
Possible duplicate? https://mcmap.net/q/391451/-x509certificate-createfromcertfile-the-specified-network-password-is-not-correct/130352Tuscarora
O
75

Try this:

new X509Certificate2(Path, "", X509KeyStorageFlags.MachineKeySet); 

It appears that the X509Certificate2 constructor tries to access the private key store of the local user (even when loading a PFX and the private key is in the PFX). With asp.net, the user profile typically isn't loaded, so the user key store doesn't exist. Specifying MachineKeySet tells the constructor to look at the Local Computer key store which always exists.

Octahedral answered 28/11, 2011 at 5:46 Comment(5)
If you set X509KeyStorageFlags parameter it will create a key file in the C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys folder every time you instantiate an X509Certificate2 object, if you do this often you could end up filling up the disk, so use this carefully.Thumbstall
The best solution for me is to make asp load the user profile. Check https://mcmap.net/q/82214/-x509certificate-constructor-exceptionThumbstall
This works perfectly. If you have a password and wants to apply you'd have to run it this way X509Certificate2 certificate = new X509Certificate2(Path, "yourpassword", X509KeyStorageFlags.MachineKeySet);Skewer
Just want to mention new X509Certificate2(Path, "your-password", X509KeyStorageFlags.MachineKeySet);Revolute
Maybe X509KeyStorageFLags.EphemeralKeySet?Hospitalize
P
16

I also had an issue with a pfx file, problem was, it was exported using AES256-SHA256 encryption, which threw the same exception as in the question. According to this, AES256-SHA256 is only supported on Windows 10 1703, Windows Server 2016 and above. Changing to TripleDES-SHA1 'solved' the issue.

Perforate answered 17/3, 2021 at 13:51 Comment(3)
See also: linkPerforate
Should someone else bump on this problem trying to load such an AES256-encrypted certificate on the azure portal or loading by code from a file/byte array... I got the same (misleading) error, which I only solved re-exporting the certificate in 3DES-SHA1. Which is strange, because locally it worked, but stopped working once published on the webapp... PS: Before of that, I also tried shortening the password, but it didn't solve anything.Oria
This helped me deploying to an old Windows 2008 server after developing in Windows 10 fine.Leipzig
S
9

I also had an issue with a PFX file, problem was this :
Exported using AES256-SHA256 encryption (using a Windows 11 PC), which threw the same exception as in the question when the PFX was used on my server. This happened in my C# .Net 4.7 application, running on Windows server 2016. Changing export to TripleDES-SHA1 'solved' the issue. Apparently Windows Server 2016 does not support AES256-SHA256, but newer versions do.

Sand answered 28/3, 2022 at 14:56 Comment(1)
This answer is a freedom, thanks. And I found more info to complement: learn.microsoft.com/en-us/answers/questions/1054881/… Actually, someone said "Windows Server 2012 R2 and Windows Server 2016 operating system will never receive AES256-SHA256 algorithm support for PFX certificates."Bump
S
1

I had this issue in with a PFX certificate file that had a 40 character password set, Windows allowed me to export it and also import it, but it couldn't be used in C# code, so I changed to a 30 character password and it works.

Stereotype answered 7/7, 2020 at 10:24 Comment(0)
R
0

There are two things to do to resolve this.

  1. Change the AppPool Identity from the local settings to Local System from Identity.

  2. Then you need to convert the certificate .p12/.pfx to TripleDES-SHA1 from AES256-SHA256 because IIS 2016 doesn't support AES256-SHA256. Here is the method to convert that.

    ` public static void ExportWithTripleDESSHA1(string inputCertPath, string inputPassword, string outputCertPath, string outputPassword){

            // Validate the output path to make sure you have permissions
            string directory = Path.GetDirectoryName(outputCertPath);
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
    
            X509Certificate2 cert = new X509Certificate2(inputCertPath, inputPassword, X509KeyStorageFlags.Exportable);
            if (cert.HasPrivateKey)
            {
                AsymmetricKeyParameter privateKey = DotNetUtilities.GetKeyPair(cert.PrivateKey).Private;
                X509CertificateEntry[] chain = new X509CertificateEntry[1];
                chain[0] = new X509CertificateEntry(DotNetUtilities.FromX509Certificate(cert));
    
                Pkcs12Store store = new Pkcs12Store();
                store.SetKeyEntry("scbprivateKey.pem", new AsymmetricKeyEntry(privateKey), chain);
    
                using (MemoryStream pfxStream = new MemoryStream())
                {
                    store.Save(pfxStream, outputPassword.ToCharArray(), new SecureRandom());
                    File.WriteAllBytes(outputCertPath, pfxStream.ToArray());
                }
            }
            else
            {
                Console.WriteLine("The certificate does not have a private key.");
            }`
    
Rotatory answered 15/10, 2023 at 19:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.