我在Azure网站(不是托管服务)中有网站,我需要在那里处理带有私钥的.pfx证书.
var x509Certificate2 = new X509Certificate2(certificate, password);
Run Code Online (Sandbox Code Playgroud)
但我遇到了以下异常:
System.Security.Cryptography.CryptographicException: The system cannot find the file specified.
at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
at System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromBlob(Byte[] rawData, IntPtr password, UInt32 dwFlags, Boolean persistKeySet, SafeCertContextHandle& pCertCtx)
at System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromBlob(Byte[] rawData, Object password, X509KeyStorageFlags keyStorageFlags)
at System.Security.Cryptography.X509Certificates.X509Certificate..ctor(Byte[] rawData, String password, X509KeyStorageFlags keyStorageFlags)
at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(Byte[] rawData, String password, X509KeyStorageFlags keyStorageFlags)
Run Code Online (Sandbox Code Playgroud)
在文章http://blog.tylerdoerksen.com/2013/08/23/pfx-certificate-files-and-windows-azure-websites/我发现它发生是因为默认情况下系统使用用户的本地目录存储密钥.但Azure网站没有本地用户配置文件目录.在同一篇文章中,作者建议使用X509KeyStorageFlags.MachineKeySet
flag.
var x509Certificate2 = new X509Certificate2(certificate, password, X509KeyStorageFlags.MachineKeySet);
Run Code Online (Sandbox Code Playgroud)
但现在我还有其他例外:
System.Security.Cryptography.CryptographicException: Access denied.
at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
at System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromBlob(Byte[] rawData, IntPtr password, UInt32 dwFlags, Boolean persistKeySet, SafeCertContextHandle& …
Run Code Online (Sandbox Code Playgroud)