title: How to create a valid JWT in PHP using RSA256
body: <p>I have been having similar difficulties to this <a href="https://stackoverflow.com/questions/35314629/how-to-sign-data-in-php-with-hmac-using-a-pem-private-key">question</a>. I need to create a JWT in php. I have the following code:</p>
  <pre><code>define('RSA_PRIVATE', 'MIICXAIB......EWxOf9o=');
  
  $payload = json_encode([
      'sub' =&gt; 'username',
      'email' =&gt; 'john@example.com',
      'given_name' =&gt; 'John',
      'family_name' =&gt; 'Example',
      'iat' =&gt; time(),
      'nonce' =&gt; '12345'
  ]);
  
  
  $header = json_encode([
      'typ' =&gt; 'JWT',
      'alg' =&gt; 'RS256'
  ]);
  
  $base64UrlHeader = base64UrlEncode($header);
  $base64UrlPayload = base64UrlEncode($payload);
  $signature = hash_hmac('sha256', &quot;$base64UrlHeader.$base64UrlPayload&quot;, RSA_PRIVATE, true);                                
  
  $base64UrlSignature = base64UrlEncode($signature);
  $jwt = &quot;$base64UrlHeader.$base64UrlPayload.$base64UrlSignature&quot;;
  
  echo($jwt);
  
  
  function base64UrlEncode($text)
  {
      return str_replace(
          ['+', '/', '='],
          ['-', '_', ''],
          base64_encode($text)
      );
  }
  </code></pre>
  <p>Whenever I attempt to validate with the third party that needs my JWT it comes back with a message telling me</p>
  <p>Signature validation failed: rsa signature did not match</p>
  <p>When I attempt to validate using the <a href="https://jwt.io/" rel="nofollow noreferrer">JWT debugger</a>, it too says it is invalid.</p>
  <p>Am I missing something here? Like the previous question I have only ever seen examples where people are using small secrets and not private RSA keys.</p>