title: Correctly create RSACryptoServiceProvider from public key
body: <p>I'm currently trying to create an <code>RSACryptoServiceProvider</code> object solely from a decoded PEM file. After several days of searching, I did manage to wrangle a working solution but it's not one that would be production ready.</p>
  
  <p>In a nutshell, in order to create an <code>RSACryptoServiceProvider</code> object from the bytes that make up the public key in a PEM file, I must create the object specifying the keysize (currently 2048 using SHA256, specifically) and then importing a <code>RSAParameters</code> object with the <code>Exponent</code> and <code>Modulus</code> set. I'm doing this as so;</p>
  
  <pre><code>byte[] publicKeyBytes = Convert.FromBase64String(deserializedPublicKey.Replace("-----BEGIN PUBLIC KEY-----", "")
                                                                        .Replace("-----END PUBLIC KEY-----", ""));
  
  // extract the modulus and exponent based on the key data
  byte[] exponentData = new byte[3];
  byte[] modulusData = new byte[256];
  Array.Copy(publicKeyBytes, publicKeyBytes.Length - exponentData.Length, exponentData, 0, exponentData.Length);
  Array.Copy(publicKeyBytes, 9, modulusData, 0, modulusData.Length);
  
  
  // import the public key data (base RSA - works)
  RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(dwKeySize: 2048);
  RSAParameters rsaParam = rsa.ExportParameters(false);
  rsaParam.Modulus = modulusData;
  rsaParam.Exponent = exponentData;
  rsa.ImportParameters(rsaParam);
  </code></pre>
  
  <p>While this works, it's not viable to assume that the <code>deserializedPublicKey</code> will be exactly 270 bytes and that the modulus I need is found at position 9 and always be 256 bytes in length.</p>
  
  <p>How do I change this to correctly pick out the Modulus and Exponent byte given a set of public key bytes? I've tried to make sense of the ASN.1 standard but with little luck finding what I need from it - the standard(s) are somewhat byzantine.</p>
  
  <p>Any help is appreciated.</p>