Created
May 28, 2021 18:57
-
-
Save stephenlb/406036042683ce64d9a0106db8c122ee to your computer and use it in GitHub Desktop.
Grant Signature PubNub Access Manager (PAM) HMAC SHA-256 - JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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×tamp=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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.