Last active
September 21, 2021 04:30
-
-
Save bilelz/4449430eb1070fc34b8ebfaf5fb9f9b5 to your computer and use it in GitHub Desktop.
PKCE Code Verifier and Code Challenge Generator without externals libs (vanilla js). Demo : https://codepen.io/bilelz/full/YzNozBe
This file contains hidden or 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
function generateCodeVerifier() { | |
return Array(128) | |
.fill('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-._~') | |
.map(x => x[Math.floor(crypto.getRandomValues(new Uint32Array(1))[0] / (0xffffffff + 1) * x.length)]) | |
.join(''); | |
} | |
async function generateCodeChallenge(code_verifier) { | |
const encoder = new TextEncoder(); | |
const data = encoder.encode(code_verifier); | |
const buffer = await window.crypto.subtle.digest('SHA-256', data); | |
//ArrayBuffer to base64 https://gist.github.com/jonleighton/958841#gistcomment-2915919 | |
return btoa(new Uint8Array(buffer).reduce((data, byte) => { | |
return data + String.fromCharCode(byte); | |
}, '')).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment