ASP.NET - 指定的网络密码不正确。

40

我在我的开发机上有一个需要证书的 WCF 客户端,它正常运行。
部署到生产服务器后,我遇到以下错误:

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

开发环境 - Win7 32位 IIS 7.5
生产环境 - Win SERVER 64位 2008 IIS 7.5

虽然网络之间没有密码,也没有证书密码(我知道这一点,因为在开发环境中没有密码)。 我唯一拥有的密码是与开发环境相同的 WCF 密码。

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); 

这是完整的堆栈

[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

感谢


X509Certificates构造函数中传递的路径是什么?我认为它是访问证书文件的网络密码。 - Simon
可能是重复问题?https://dev59.com/FXNA5IYBdhLWcg3wmfEa - Chris J
5个回答

73

试试这个:

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

看起来 X509Certificate2 构造函数尝试访问本地用户的私钥存储区(即使加载了 PFX 文件且私钥已经在 PFX 文件中)。在 asp.net 中,用户配置文件通常没有被加载,因此用户密钥存储区不存在。指定 MachineKeySet 参数告诉构造函数查看始终存在的本地计算机密钥存储区。


10
如果您设置X509KeyStorageFlags参数,每次实例化X509Certificate2对象时都会在C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys文件夹中创建一个密钥文件,如果经常这样做,可能会填满磁盘,因此请谨慎使用。 - NahuelGQ
4
最好的解决方案是让asp加载用户配置文件。请查看https://dev59.com/nmkw5IYBdhLWcg3wXZT8#10048789。 - NahuelGQ
2
这个工作得非常好。如果您有密码并想要应用它,则必须以这种方式运行:X509Certificate2证书= new X509Certificate2(路径,“您的密码”,X509KeyStorageFlags.MachineKeySet); - Victor.Uduak
只想提一下新的X509Certificate2(Path, "your-password", X509KeyStorageFlags.MachineKeySet); - Mohammad Hassani
也许是 X509KeyStorageFlags.EphemeralKeySet - Zachary Scott

13

我也遇到了一个与pfx文件相关的问题,问题是它使用AES256-SHA256加密导出,在这个问题中产生了相同的异常。根据这里的说明,只有在Windows 10 1703、Windows Server 2016及以上版本才支持AES256-SHA256加密方式。将加密方式改为TripleDES-SHA1后,“解决”了这个问题。


1
参见:链接 - ferikeem
1
如果有人在尝试从文件/字节数组加载这样的AES256加密证书时,在Azure门户或通过代码加载时遇到问题...我遇到了相同(误导性)的错误,只有重新将证书导出为3DES-SHA1才解决了问题。这很奇怪,因为在本地它可以工作,但一旦发布到Web应用程序上就停止工作了...PS:在那之前,我还尝试缩短密码,但没有解决任何问题。 - Luke
这帮助我在 Windows 10 上开发后部署到旧的 Windows 2008 服务器上。 - Andy Cox

6
我曾遇到一个与PFX文件有关的问题,它的问题在于:使用Windows 11 PC导出时使用了AES256-SHA256加密,当我在我的运行在Windows Server 2016上的C# .Net 4.7应用程序中使用PFX文件时,会抛出与问题中相同的异常。将导出方式更改为TripleDES-SHA1“解决”了这个问题。显然,Windows Server 2016不支持AES256-SHA256,但更新版本支持。

这个答案是自由的,谢谢。我还找到了更多的信息来补充:https://learn.microsoft.com/en-us/answers/questions/1054881/windows-server-2016-2012r2-how-to-add-support-for 实际上,有人说"Windows Server 2012 R2和Windows Server 2016操作系统将永远不会为PFX证书提供AES256-SHA256算法支持。" - undefined

1
我曾经遇到一个PFX证书文件的问题,它的密码长度为40个字符。Windows允许我导入和导出,但在C#代码中无法使用。于是我将密码长度改为30个字符,问题得以解决。

0
有两件事情要做来解决这个问题。
  1. 将AppPool身份从本地设置更改为本地系统身份。

  2. 然后,您需要将证书.p12/.pfx从AES256-SHA256转换为TripleDES-SHA1,因为IIS 2016不支持AES256-SHA256。以下是转换的方法。

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

            // 验证输出路径以确保您有权限
            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("该证书没有私钥。");
            }`
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接