Home Ask Login Register

Developers Planet

Your answer is one click away!

user3357141 February 2016

Getting PrivateKey null X509Certificate2 c#

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);
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);
byte[] SignedHashValue = RSAFormatter.CreateSignature(hash);


DmitryZyr February 2016

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.


Post Status

Asked in February 2016
Viewed 1,700 times
Voted 13
Answered 1 times


Leave an answer

Quote of the day: live life