It is a console application and I'm using .net framework 4. When I try to get the private key from the certificate I get it as null any idea why is this happening?
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);
Usually a file with the extension ".cer" is just the certificate, which is the public key and some associated metadata. A PFX/PKCS#12 file can also contain private keys.
You can check myCert2.HasPrivateKey
to determine if any private key was loaded for the certificate. Since myCert2.PrivateKey
should only return null when HasPrivateKey is false
, I'm pretty sure you'll find that the system simply doesn't know about the private key to your certificate.
Currently this property supports only RSA or DSA keys, so it returns either an RSACryptoServiceProvider or a DSACryptoServiceProvider object. If no private key is associated with the certificate, it returns null.
https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.x509certificate2.privatekey#System_Security_Cryptography_X509Certificates_X509Certificate2_PrivateKey
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With