title: Using Google Cloud Key Management Service to sign JSON Web Tokens
body: <p><strong>Edit: I found the answer. Scroll to the bottom of this question.</strong></p>
  
  <p>I am working on a NodeJS authentication server and I would like to sign JSON Web Tokens (JWT) using google signatures.</p>
  
  <p>I am using Google Cloud Key Management Service (KMS) and I created a key ring and an asymmetric signing key. </p>
  
  <p>This is my code to get the signature:</p>
  
  <pre><code>signatureObject = await client.asymmetricSign({ name, digest })
  
  signature = signatureObject["0"].signature
  </code></pre>
  
  <p>My Google signature object looks like this:</p>
  
  <p><a href="https://i.stack.imgur.com/jCD4Z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jCD4Z.png" alt="enter image description here"></a></p>
  
  <p>My question: <strong>How do I sign a JWT using the Google signature?</strong></p>
  
  <p>Or in other words, how do I concatenate the Google signature to the (header.payload) of the JWT?</p>
  
  <p>The JWT should look something like this:</p>
  
  <pre><code>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ. (GoogleSignature)
  </code></pre>
  
  <p>The Code I am using:</p>
  
  <p>signing:</p>
  
  <pre><code>async function sign(message, name) {
    hashedMessage = crypto.createHash('sha256').update(message).digest('base64');
    digest = { 'sha256': hashedMessage }
  
    signatureObject = await client.asymmetricSign({ name, digest }).catch((err) =&gt; console.log(err))
    signature = signatureObject["0"].signature
    signJWT(signature)
  }
  </code></pre>
  
  <p>Creating the JWT:</p>
  
  <pre><code>function signJWT(signature) {
    header = {
      alg: "RS256",
      typ: "JWT"
    }
  
    payload = {
      sub: "1234567890",
      name: "John Doe",
      iat: 1516239022
    }
  
    JWT = base64url(JSON.stringify(header)) + "." +
          base64url(JSON.stringify(payload)) + "." + 
          ???signature??? ; // what goes here?
  }
  </code></pre>
  
  <p>Verifying:</p>
  
  <pre><code>async function validateSignature(message, signature) {
    // Get public key
    publicKeyObject = await client.getPublicKey({ name }).catch((err) =&gt; console.log(err))
    publicKey = publicKeyObject["0"].pem
  
    //Verify signature
    var verifier = crypto.createVerify('sha256');
    verifier.update(message)
    var ver = verifier.verify(publicKey, signature, 'base64')
  
    // Returns either true for a valid signature, or false for not valid.
    return ver
  }
  </code></pre>
  
  <hr>
  
  <p><strong>The Answer:</strong></p>
  
  <p>I can use the toString() method like so: </p>
  
  <pre><code>signatureString = signature.toString('base64');
  </code></pre>
  
  <p>AND then I can get the original signature octet stream by using </p>
  
  <pre><code>var buffer = Buffer.from(theString, 'base64');
  </code></pre>