繁体   English   中英

获取私钥 null X509Certificate2 c#

[英]Getting PrivateKey null X509Certificate2 c#

这是一个控制台应用程序,我正在使用 .net 框架 4。当我尝试从证书中获取私钥时,我将其设为 null 知道为什么会发生这种情况吗?

string text = "some text"
SHA1 sha1 = SHA1CryptoServiceProvider.Create();
Byte[] textToBytes =  //ASCIIEncoding.Default.GetBytes(texto);
UTF8Encoding.UTF8.GetBytes(text);
Byte[] hash = sha1.ComputeHash(textToBytes);
//Path to the certificate file.
string sFile = @"C:\myCer.cer";
//Get the bytes array.
byte[] byteCer = File.ReadAllBytes(sFile);
//Create the certificate with bytes and the password.    
X509Certificate2 myCert2 = new X509Certificate2(byteCer, "Password", X509KeyStorageFlags.MachineKeySet);

byte[] Encrypted = rsa1.Encrypt(hash, true);
string cypherText = Convert.ToBase64String(Encrypted);
RSACryptoServiceProvider RSA = (RSACryptoServiceProvider)myCert2.PrivateKey;//I get the privateKey as null.
RSAPKCS1SignatureFormatter RSAFormatter = new RSAPKCS1SignatureFormatter(RSA);
RSAFormatter.SetHashAlgorithm("SHA1");
byte[] SignedHashValue = RSAFormatter.CreateSignature(hash);

通常带有“.cer”扩展名的文件只是证书,它是公钥和一些相关的元数据。 PFX/PKCS#12 文件也可以包含私钥。

您可以检查myCert2.HasPrivateKey以确定是否为证书加载了任何私钥。 由于myCert2.PrivateKey应该只在 HasPrivateKey 为false时返回 null ,我很确定您会发现系统根本不知道您的证书的私钥。

当前,此属性仅支持 RSA 或 DSA 密钥,因此它返回 RSACryptoServiceProvider 或 DSACryptoServiceProvider 对象。 如果没有私钥与证书关联,则返回 null。

https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.x509certificate2.privatekey#System_Security_Cryptography_X509Certificates_X509Certificate2_PrivateKey

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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