Hi,
Iam having issues with a part of my code in a windows service that prevents it from being installed with the error,nullrefrenceexception unhandled.here is the code
public string GetEncryptedText(string PlainStringToEncrypt)
{
string DigitalCertificateName = "URAioPmtCert1";

        X509Store store = new X509Store(StoreName.Root);
        X509Certificate2 x509_2 = null;
        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)
              throw new Exception("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;
            byte[] cipher = rsa.Encrypt(cipherbytes, false);
            return Convert.ToBase64String(cipher);
        }
        catch (Exception e)
        {
            //Hadle exception
            throw e;
        }

    }

I suppose it may be possible for cert.SubjectName to be null or cert.SubjectName.Name to be null.

Also this part is incorrect:

      catch (Exception e)
      {
        throw e;
      }

When you do that it re-throws the exception with new line numbers -- thus makes harder chasing down the actual problem. There is no point in catching an exception just to re-throw it without doing anything else. The proper way to handle and re-throw an exception is to:

      catch
      {
        //Do something
        throw;
      }

You can rewrite it and throw more descript error messages each step of the way to see where its failing:

    public string GetEncryptedText(string plainStringToEncrypt)
    {
      string plainStr = (plainStringToEncrypt ?? string.Empty).Trim();
      if (string.IsNullOrEmpty(plainStr))
        throw new ArgumentNullException("plainStringToEncrypt");

      //string DigitalCertificateName = "URAioPmtCert1";
      //X509Store store = new X509Store(StoreName.Root);

      string DigitalCertificateName = "sensource";
      X509Store store = new X509Store(StoreName.Root);
      store.Open(OpenFlags.ReadWrite);
      try
      {
        X509Certificate2 x509_2;
        if (DigitalCertificateName.Length > 0)
        {
          x509_2 = store.Certificates
            .OfType<X509Certificate2>()
            .Where(cert => cert != null && cert.SubjectName != null && !string.IsNullOrEmpty(cert.SubjectName.Name))
            .FirstOrDefault(cert => cert.SubjectName.Name.IndexOf(DigitalCertificateName, StringComparison.OrdinalIgnoreCase) >= 0);
          if (x509_2 == null)
            throw new InvalidOperationException(string.Format("Could not locate certificate '{0}'", DigitalCertificateName));
        }
        else
        {
          x509_2 = store.Certificates[0];
        }

        try
        {
          byte[] cipherbytes = Encoding.Default.GetBytes(plainStr);
          if (x509_2.PublicKey == null) throw new InvalidOperationException("Public key is null");
          if (x509_2.PublicKey.Key == null) throw new InvalidOperationException("Public key is null");
          RSACryptoServiceProvider rsa = x509_2.PublicKey.Key as RSACryptoServiceProvider;
          if (rsa == null) throw new InvalidOperationException(string.Format("Public key was of type '{0}' and not type 'RSACryptoServiceProvider'", x509_2.PublicKey.Key.GetType().Name));
          byte[] cipher = rsa.Encrypt(cipherbytes, false);
          return Convert.ToBase64String(cipher);
        }
        catch
        {
          throw;
        }
      }
      finally
      {
        store.Close();
      }
    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.