Azure-X509Certificate2构造函数错误(.Net Core):网络密码不正确

时间:2018-06-22 15:41:37

标签: azure x509certificate2

我正在从项目中的嵌入式资源文件中加载.pfx证书。嵌入式资源文件已正确加载,并且我正在正确获取原始数据-代码:

 using (Stream stream = assembly.GetManifestResourceStream(resourceName))
 {
       try
       {
                Byte[] raw = new Byte[stream.Length];

                for (Int32 i = 0; i < stream.Length; i++)
                {
                    raw[i] = (Byte)stream.ReadByte();
                }
                //X509Certificate2 cert = new X509Certificate2(raw, password);
                X509Certificate2 cert = new X509Certificate2(raw, password, X509KeyStorageFlags.MachineKeySet);
                //Both of the above attempts give me invalid network password
                //errors on Azure.
                builder.AddSigningCredential(cert);
                builder.AddValidationKey(cert);
       }
       catch (Exception e)
       {
            //Notify me of exception
       }
} //end using

但是,当尝试初始化一个新的X509Certificate2对象时,我认为它正在尝试访问商店中不存在的证书或其他东西

(根据这个问题:

ASP.NET - The specified network password is not correct

完整错误: Internal.Cryptography.CryptoThrowHelper + WindowsCryptographicException:指定的网络密码不正确    在Internal.Cryptography.Pal.CertificatePal.FilterPFXStore处(字节[] rawData,SafePasswordHandle密码,PfxCertStoreFlags pfxCertStoreFlags)    在Internal.Cryptography.Pal.CertificatePal.FromBlobOrFile(Byte [] rawData,String fileName,SafePasswordHandle password,X509KeyStorageFlags keyStorageFlags)中    在System.Security.Cryptography.X509Certificates.X509Certificate..ctor(Byte [] rawData,String password,X509KeyStorageFlags keyStorageFlags)

1 个答案:

答案 0 :(得分:0)

我最终下载了x64 OpenSSL二进制文件(您可以在此链接https://wiki.openssl.org/index.php/Binaries上看到可用二进制文件的列表)。

使用OpenSSL,您可以创建.pfx文件,这些文件可用于创建X509Certificate2对象,而无需使用Microsoft的工具。

基本上,您将获得一个zip文件,将其解压缩,然后使用Windows命令行在bin文件夹中运行openssl.ex。这是您成为自己的根CA,生成私钥,从中创建根证书,然后最终使用私钥和根证书创建.pfx证书文件的方式(在以这种方式正确生成.pfx之后,您可以可以解决Microsoft的想法,并且能够将您的证书从.pfx文件加载到X509Certificate2):

这些命令来自Windows的命令行,与openssl.exe在同一文件夹中:

  1. 使用openssl生成rsa私钥:

openssl genrsa -out myPrivateKey.rsa 2048

  1. 成为您自己的根CA,获取证书:

openssl req -new -x509 -days 3652 -key myPrivateKey.rsa -out rootCertificate.crt

  1. 创建您的pfx文件(pkcs12格式的.pfx文件):

openssl pkcs12 -export -out MyCertificate.pfx -inkey myPrivateKey.rsa -in rootCertificate.crt

  1. 在Visual Studio 2017解决方案资源管理器中右键单击您的项目,选择“添加现有项”,选择MyCertificate.pfx文件,然后单击“确定”。右键单击该文件,选择属性,对于构建操作,选择“嵌入式资源”。

  2. 在我的问题中使用代码。您可以取消注释该行:

    X509Certificate2 cert =新的X509Certificate2(原始密码);

,摆脱另一行尝试。现在它将可以正常工作。 (在这种情况下,资源名称变量将为“ Your.Project.Namespace.MyCertificate.pfx”)

相关问题