title: Use PHP to generate a public/private key pair and export public key as a .der encoded string
body: <p>Currently I have some working php code to generate a private/public keypair and store them in two variables. These variables are strings, with one variable containing the private key, and the other containing the public key. I researched on stack overflow and I also found some code to convert a pem encoded key string to a der encoded key string. However, I don't know how to convert the public key string to pem format in order to convert it to der. Please not that I don't need to ultimately convert the sting to pem, I just need the der encoded string.</p>
  
  <p>My code is below:</p>
  
  <pre><code>$userKey = $_POST["key"];
  
  $config = array(
      "digest_alg" =&gt; "sha512",
      "private_key_bits" =&gt; 2048,
      "private_key_type" =&gt; OPENSSL_KEYTYPE_RSA,
  );
  
  function encryptData($value){
     $key = $userKey;
     $text = $value;
     $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
     $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
     $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv);
     return $crypttext;
  }
  
  // Create the keypair
  $res = openssl_pkey_new($config);
  
  // Get private key
  openssl_pkey_export($res, $privKey);
  
  // Get public key
  $pubKey = openssl_pkey_get_details($res);
  $pubKey = $pubKey["key"];
  
  function pem2der($pem_data) {
     $begin = "CERTIFICATE-----";
     $end   = "-----END";
     $pem_data = substr($pem_data, strpos($pem_data, $begin)+strlen($begin));    
     $pem_data = substr($pem_data, 0, strpos($pem_data, $end));
     $der = base64_decode($pem_data);
     return $der;
  }
  
  $der = pem2der($pubKey);
  
  //Send der data to client here
  </code></pre>
  
  <p>Thanks in advance!</p>