Last active
September 22, 2023 11:59
-
-
Save maxgaurav/798c23eecef318a3587a02d214231fe5 to your computer and use it in GitHub Desktop.
PKCE Code Challenge and Code Verifier Generation along with verification process
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
// browser part | |
const codeVerifier = crypto.getRandomValues(new Uint8Array(128)); | |
function toBase64(buffer: Uint8Array): string { | |
return btoa(String.fromCharCode(...buffer)) | |
.replace(/=/g, '') | |
.replace(/\+/g, '-') | |
.replace(/\//g, '_') | |
} | |
async function generateCodeChallenge(codeVerifier: Uint8Array): Promise<string> { | |
const digest = await crypto.subtle.digest('SHA-256', codeVerifier); | |
return toBase64(new Uint8Array(digest)); | |
} |
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
// node part | |
import { createHash } from 'node:crypto'; | |
async function verify(codeVerifier: string, codeChallenge: string) { | |
const codeHash = createHash('sha256').update(codeVerifier).digest(); | |
return codeChallenge === codeHash; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment