Skip to content

Instantly share code, notes, and snippets.

@stephenlb
Created May 28, 2021 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephenlb/406036042683ce64d9a0106db8c122ee to your computer and use it in GitHub Desktop.
Save stephenlb/406036042683ce64d9a0106db8c122ee to your computer and use it in GitHub Desktop.
Grant Signature PubNub Access Manager (PAM) HMAC SHA-256 - JavaScript
Open Dev Console
<script>(async ()=>{
'use strict';
let secret = "sec-demo";
let enc = new TextEncoder("utf-8");
let body = "GET\npub-demo\n/v2/auth/grant/sub-key/sub-demo\nauth=myAuthKey&g=1&target-uuid=user-1&timestamp=1595619509&ttl=300";
let algorithm = { name: "HMAC", hash: "SHA-256" };
let key = await crypto.subtle.importKey("raw", enc.encode(secret), algorithm, false, ["sign", "verify"]);
let signature = await crypto.subtle.sign(algorithm.name, key, enc.encode(body));
let digest = btoa(String.fromCharCode(...new Uint8Array(signature)));
console.log(digest);
})();</script>
@stephenlb
Copy link
Author

Async/Await Crypto Subtle HMAC SHA-256 with Base64 Digest

The following is a copy of the ✅ StackOverflow Crypto Subtle answer. This time we are using async/await for clean syntax. This approach also offers a base64 encoding digest.

  • body is the string-to-sign.
  • enc is a text encoder that converts the UTF-8 to JavaScript byte arrays.
  • algorithm is a JS object which is used to identify the signature methods.
  • key is a CryptoKey.
  • signature is the byte array hash.
  • digest is the base64 encoded signature.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment