Skip to content

Instantly share code, notes, and snippets.

@azechi
Created September 26, 2020 05:16
Show Gist options
  • Save azechi/cce5c300773ef73309fe29c62895c8ba to your computer and use it in GitHub Desktop.
Save azechi/cce5c300773ef73309fe29c62895c8ba to your computer and use it in GitHub Desktop.
JavaScript RFC7636 PKCE code_verifier and SHA-256 code_challenge with Web Cryptography API
//https://tools.ietf.org/html/rfc7636#appendix-B
const code_verifier = btoa(
String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32)))
).replace(/\/|\+|=/g, (x) => ({ "/": "_", "+": "-", "=": "" }[x]));
const hash = await crypto.subtle.digest(
"SHA-256",
new Uint8Array([...code_verifier].map((e) => e.charCodeAt(0)))
);
const code_challenge = btoa(
String.fromCharCode(...new Uint8Array(hash))
).replace(/\/|\+|=/g, (x) => ({ "/": "_", "+": "-", "=": "" }[x]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment