簡體   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