cyprography exception

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Hi all,
Im getting this error when I try to install a windows service.
<span style="font-size:x-small <span lang="EN
Service cannot be started. System.Security.Cryptography.CryptographicException: m_safeCertContext is an invalid handle.
at UraService.Service1.GetEncryptedText(String PlainStringToEncrypt)
at UraService.Service1.OnStart(String[] args)
at System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(Object state)
<a> please help me.
<a> code
<pre class="prettyprint public string GetEncryptedText(string PlainStringToEncrypt)
{
string DigitalCertificateName = "URAioPmtCert1";
X509Store store = new X509Store(StoreName.My);
X509Certificate2 x509_2 = new X509Certificate2();
// Test(x509_2);
store.Open(OpenFlags.ReadWrite);
if (DigitalCertificateName.Length > 0)
{
foreach (X509Certificate2 cert in store.Certificates)
{
if (cert.SubjectName.Name.Contains(DigitalCertificateName))
{
x509_2 = cert;
break;
}
}
if (x509_2 == null)
// Test(x509_2);
Console.WriteLine("No Certificate could be found in name " + DigitalCertificateName);
}
else
{
x509_2 = store.Certificates[0];
}
try
{
string PlainString = PlainStringToEncrypt.Trim();
byte[] cipherbytes = ASCIIEncoding.ASCII.GetBytes(PlainString);
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)x509_2.PublicKey.Key;
// RSACryptoServiceProvider rsa;
////added
//if (x509_2.HasPrivateKey)
//{
// rsa = (RSACryptoServiceProvider)x509_2.PublicKey.Key;
//}
//else
//{
// throw new CryptographicException(" key not contained within certificate.");
//}
////added
byte[] cipher = rsa.Encrypt(cipherbytes, false);
return Convert.ToBase64String(cipher);
}
catch (Exception e)
{
//Hadle exception
throw e;
}
}[/code]
<br/>
<span lang="EN <span lang="EN




View the full article
 
Back
Top