title: how to convert raw modulus & exponent to RSA public key (.pem format)
body: <p>I have the modulus &amp; exponent of an RSA public key embedded into a binary file, and I am trying to extract the entire blob and create a usable .pem public key.</p>
  
  <p>Currently, I am extracting the full 260 bytes (4 bytes for the exponent, 256 bytes for the modulus) 
  and encoding as base64. I am doing that using the following shell command :</p>
  
  <pre><code>tail -c $((filesize - start_of_key_data)) filename | head -c $size_of_key_data | base64 &gt; outkey
  </code></pre>
  
  <p>This gives me the following string :</p>
  
  <pre><code>&lt;&lt;&lt;&lt;&lt;&lt; modulus &amp; exponent extracted from binary file, base64-encoded &gt;&gt;&gt;&gt;&gt;&gt;
  
  tZyrQA6cZFJfVm6FyXwtZaLQYg8EecuO+ObrHTwc8JO+XrgnpNAdmlhbAEPxSNnjwhNnbYGYGL4F
  vzmnZXzZU71Key42HQPh1k2Zx1UDbrH5ciODKx1ZbuEx8K24SHnL1nY/H75hwhT/ZRRVGQDvYDT+
  sgzw2vmV66+dflw1Zs8BLhqjLjczdHvjeVXsDRJ9Mvvd/dhFH8UlTf4JpLGya9nsNIfNBBIf1Lll
  RWwCTiEIbaOMgWcLjLV/2tk/j5Dra/oQnVf/2hVsEF/hXEx41YjeEW/warweoDVG7zaxrHEc/k/r
  ZCUCZKxf8nBKdqax/gRICvkG6e5xg2GQw0W/ZwABAAE=
  </code></pre>
  
  <p>Now, when I take the key.pem keypair that the modulus &amp; exponent were originally extracted from, and display the public portion like so</p>
  
  <pre><code>openssl rsa -in key.pem -pubout -out pubkey.pem
  </code></pre>
  
  <p>I get this string (I have omitted the header &amp; footer lines :</p>
  
  <pre><code>&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; valid public key data extracted from keypair &gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;
  
  MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtZyrQA6cZFJfVm6FyXwt
  ZaLQYg8EecuO+ObrHTwc8JO+XrgnpNAdmlhbAEPxSNnjwhNnbYGYGL4FvzmnZXzZ
  U71Key42HQPh1k2Zx1UDbrH5ciODKx1ZbuEx8K24SHnL1nY/H75hwhT/ZRRVGQDv
  YDT+sgzw2vmV66+dflw1Zs8BLhqjLjczdHvjeVXsDRJ9Mvvd/dhFH8UlTf4JpLGy
  a9nsNIfNBBIf1LllRWwCTiEIbaOMgWcLjLV/2tk/j5Dra/oQnVf/2hVsEF/hXEx4
  1YjeEW/warweoDVG7zaxrHEc/k/rZCUCZKxf8nBKdqax/gRICvkG6e5xg2GQw0W/
  ZwIDAQAB
  </code></pre>
  
  <p>You can see that the key data which I have extracted and base64-encoded myself is
  actually present in the data of the valid public key data extracted from the key.pem using openssl.
  However there are 45 characters at the beginning, that my own extracted data does not have -</p>
  
  <pre><code>MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA
  </code></pre>
  
  <p>and the last 8 characters also differ.</p>
  
  <pre><code>ZwIDAQAB
  </code></pre>
  
  <p>Can anybody offer some advice on how to convert a modulus and exponent into a usable public key?</p>
  
  <p>(the goal is to do this in a bash script, not python or C as I've seen many suggest.)    </p>