title: How to fix bad length error for DecodeRSAPrivateKey?
body: <p>I'm getting this error: </p>
  
  <blockquote>
    <ol>
    <li>Bad length</li>
    <li>Object reference not set to an instance of an object.</li>
    </ol>
  </blockquote>
  
  <p>I'm using this code: </p>
  
  <pre class="lang-cs prettyprint-override"><code>    public string RSASign(string data, string PhysicalApplicationPath)
      {
          RSACryptoServiceProvider rsaCsp = LoadCertificateFile(PhysicalApplicationPath);
          byte[] dataBytes = System.Text.Encoding.Default.GetBytes(data);
          byte[] signatureBytes = rsaCsp.SignData(dataBytes, "SHA256");    &lt;--------error here:Object reference not set to an instance of an object.
          return BitConverter.ToString(signatureBytes).Replace("-", null);
      }
  
      byte[] GetPem(string type, byte[] data)
      {
          string pem = Encoding.UTF8.GetString(data);
          string header = String.Format("-----BEGIN {0}-----\\n", type);
          string footer = String.Format("-----END {0}-----", type);
          int start = pem.IndexOf(header) + header.Length;
          int end = pem.IndexOf(footer, start);
          string base64 = pem.Substring(start, (end - start));
          return Convert.FromBase64String(base64);
      }
  
      public byte[] HexToBytes(string hex)
      {
          hex = hex.Trim();
  
          byte[] bytes = new byte[hex.Length / 2];
  
          for (int index = 0; index &lt; bytes.Length; index++)
          {
              bytes[index] = byte.Parse(hex.Substring(index * 2, 2), NumberStyles.HexNumber);
              //  Console.WriteLine("bytes: " + bytes);
          }
  
          return bytes;
      }
  
      RSACryptoServiceProvider LoadCertificateFile(string filename)
      {
          using (System.IO.FileStream fs = System.IO.File.OpenRead(filename))
          {
              byte[] data = new byte[fs.Length];
              byte[] res = null;
              fs.Read(data, 0, data.Length);
              if (data[0] != 0x30)
              {
                  res = GetPem("PRIVATE KEY", data);
              }
              try
              {
                  RSACryptoServiceProvider rsa = DecodeRSAPrivateKey(res);
  
                  return rsa;
  
  
              }
              catch (Exception ex)
              {
                  Console.WriteLine("ex :" + ex);
  
              }
  
              return null;
          }
      }
  
      bool verbose = false;
  
      public RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
      {
          byte[] MODULUS, E, D, P, Q, DP, DQ, IQ;
  
          // --------- Set up stream to decode the asn.1 encoded RSA private key ------
          MemoryStream mem = new MemoryStream(privkey);
          BinaryReader binr = new BinaryReader(mem);  //wrap Memory Stream with BinaryReader for easy reading
          byte bt = 0;
          ushort twobytes = 0;
          int elems = 0;
          try
          {
              twobytes = binr.ReadUInt16();
              if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                  binr.ReadByte();    //advance 1 byte
              else if (twobytes == 0x8230)
                  binr.ReadInt16();    //advance 2 bytes
              else
                  return null;
  
              twobytes = binr.ReadUInt16();
              if (twobytes != 0x0102) //version number
                  return null;
              bt = binr.ReadByte();
              if (bt != 0x00)
                  return null;
  
  
              //------ all private key components are Integer sequences ----
              elems = GetIntegerSize(binr);
              MODULUS = binr.ReadBytes(elems);
  
              elems = GetIntegerSize(binr);
              E = binr.ReadBytes(elems);
  
              elems = GetIntegerSize(binr);
              D = binr.ReadBytes(elems);
  
              elems = GetIntegerSize(binr);
              P = binr.ReadBytes(elems);
  
              elems = GetIntegerSize(binr);
              Q = binr.ReadBytes(elems);
  
              elems = GetIntegerSize(binr);
              DP = binr.ReadBytes(elems);
  
              elems = GetIntegerSize(binr);
              DQ = binr.ReadBytes(elems);
  
              elems = GetIntegerSize(binr);
              IQ = binr.ReadBytes(elems);
  
              Console.WriteLine("showing components ..");
              if (verbose)
              {
                  showBytes("\nModulus", MODULUS);
                  showBytes("\nExponent", E);
                  showBytes("\nD", D);
                  showBytes("\nP", P);
                  showBytes("\nQ", Q);
                  showBytes("\nDP", DP);
                  showBytes("\nDQ", DQ);
                  showBytes("\nIQ", IQ);
              }
  
              // ------- create RSACryptoServiceProvider instance and initialize with public key -----
              CspParameters CspParameters = new CspParameters();
              CspParameters.Flags = CspProviderFlags.UseMachineKeyStore;
              RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(1024, CspParameters);
              RSAParameters RSAparams = new RSAParameters();
  
              RSAparams.Modulus = MODULUS;
              RSAparams.Exponent = E;
              RSAparams.D = D;
              RSAparams.P = P;
              RSAparams.Q = Q;
              RSAparams.DP = DP;
              RSAparams.DQ = DQ;
              RSAparams.InverseQ = IQ;
              RSA.ImportParameters(RSAparams);
              return RSA;
          }
          catch (Exception ex)
          {
              Console.WriteLine("ex1 :" + ex);     &lt;-----error here : bad length
              return null;
          }
          finally
          {
              binr.Close();
          }
      }
  </code></pre>
  
  <p>I would appreciate any guidance, advice, or assistance in helping me get this resolved.</p>