获取私钥为空的X509Certificate2(c#)

4
这是一个控制台应用程序,我正在使用.NET Framework 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);

3
".cer"文件通常只包含公钥证书,不包含私钥。私钥通常存储在.PFX/P12文件中。 - Yacoub Massad
2个回答

4
通常一个扩展名为".cer"的文件只是证书,其中包含公钥和一些关联的元数据。而PFX/PKCS#12文件还可以包含私钥。
您可以检查myCert2.HasPrivateKey以确定是否加载了证书的任何私钥。由于当HasPrivateKey为false时,myCert2.PrivateKey应该返回null,我相信您会发现系统根本不知道您的证书的私钥。

我发现 HasPrivateKey 属性被设置为 true,而 PrivateKey 属性为空。我目前正在使用 EphemeralKeySet 尝试解决缺少用户配置文件的问题,同时又不将证书导入到服务器本身。你有什么建议吗?谢谢。 - masterwok
1
@masterwok 使用 cert.GetRSAPrivateKey() - bartonjs
谢谢您的回复!我已经尝试使用了该方法并且获得了一个私钥。但是,当我试图重新将私钥分配回X509Certificate2 PrivateKey属性时,我会收到“仅支持实现ICspAsymmetricAlgorithm的非对称密钥”.. 我正在使用Exportable和EphemeralKeySet标志。我尝试通过将RSA私钥分配回X509Certificate2 PrivateKey属性来获取带有私钥填充的X509Certificate2实例,这样做是否正确? - masterwok
1
@masterwok 不,您不应该在.NET Framework 4.6.2+或.NET Core(任何版本)上使用PrivateKey属性(获取或设置),只需使用GetRSAPrivateKey(或其他算法)并使用该结果进行操作。 - bartonjs
1
@masterwok,SslStream不支持EphemeralKeySet。(https://github.com/dotnet/corefx/issues/24454)。如果您仍有疑问,请创建一个新问题,而不是在此处发表评论。 - bartonjs
显示剩余2条评论

3

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