title: NodeJS Crypto RS-SHA256 and JWT Bearer
body: <p>In implementing an oauth2 stack utilizing passport and oauth2orize, in this case the issue is specifically in utilizing the oauth2orize jwt bearer. The oauth2orize jwt bearer is great in getting everything going, however it has the RSA SHA pieces marked as to do.</p>
  
  <p>In attempting to put in the pieces for the RSA SHA encryption handling, I cannot get the signature to verify as verifier.verify always seems to return false. If anyone has cleared this hurdle, a little help would be super.</p>
  
  <p>What I've done:
  Created the private / public keys:</p>
  
  <pre><code>openssl genrsa -out private.pem 1024
  //extract public key
  openssl rsa -in private.pem -out public.pem -outform PEM -pubout
  </code></pre>
  
  <p>now the data to sign:</p>
  
  <pre><code>{"alg":"RS256","typ":"JWT"}{"iss": "myclient"}
  </code></pre>
  
  <p>I've tried multiple ways as to how to sign this, too many to list here, but my understanding of the correct signature is to sign the bas64 encoding of these items, so i ran base64 on  {"alg":"RS256","typ":"JWT"} and base64 on {"iss": "myclient"} then ran base64 on those encodings. So the result is:
  <code>eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9
  eyJpc3MiOiAibXljbGllbnQifQ</code>
  then encode:</p>
  
  <pre><code>{eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9}.{eyJpc3MiOiAibXljbGllbnQifQ}
  </code></pre>
  
  <p>which gives me:
  <code>e2V5SmhiR2NpT2lKU1V6STFOaUlzSW5SNWNDSTZJa3BYVkNKOX0ue2V5SnBjM01pT2lBaWJYbGpiR2xsYm5RaWZRfQ</code></p>
  
  <p>At this point I sign the above base64 by doing:</p>
  
  <pre><code>openssl sha -sha256 -sign priv.pem &lt; signThis &gt; signedData
  </code></pre>
  
  <p>Then I run base64 on that to get the data to pass into the signature part of the assertion.
  I then pass in the object:</p>
  
  <pre><code>{
  "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
  "assertion":  "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiAibXljbGllbnQifQ.signedData"
  }
  </code></pre>
  
  <p>now in the code base I have:</p>
  
  <pre><code>var crypto = require('crypto')
     , fs = require('fs')
     , pub = fs.readFileSync('/path/to/pub.pem')
     , verifier = crypto.createVerify("RSA-SHA256");
  
  verifier.update(JSON.stringify(data));
  
  var result = verifier.verify(pub, signature, 'base64');
  console.log('vf: ', result);
  </code></pre>
  
  <p>however, result is always false.</p>
  
  <p>I do properly receive the data, the signature variable in the code is a match for what I'm passing in, I just always receive false and have exhausted all options I can think of on how to tweak this to get verifier.verify to return true. Thank you for the time and help!</p>