Created
January 1, 2021 19:55
-
-
Save dcaponi/7796fd4b99559dcda95f07bf6747c6ef to your computer and use it in GitHub Desktop.
Takes a code_verifier string and makes a legal code_challenge out of it
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
const createCodeChallenge = ( codeVerifier ) => { | |
if ( typeof window !== 'undefined' && !!( window.crypto ) && !!( window.crypto.subtle ) ) { | |
return new Promise( ( resolve, reject ) => { | |
let codeVerifierCharCodes = textEncodeLite( codeVerifier ); | |
crypto.subtle | |
.digest( 'SHA-256', codeVerifierCharCodes ) | |
.then( | |
hashedCharCodes => resolve( urlSafe( new Uint8Array(hashedCharCodes) ) ), | |
error => reject( error ) | |
); | |
}); | |
} | |
} | |
const textEncodeLite = ( str ) => { | |
const charCodeBuffer = new Uint8Array( str.length ); | |
for ( let i = 0; i < str.length; i++ ) { | |
charCodeBuffer[i] = str.charCodeAt( i ); | |
} | |
return charCodeBuffer; | |
} | |
const urlSafe = ( buffer ) => { | |
const encoded = base64.fromByteArray( new Uint8Array( buffer ) ); | |
return encoded.replace( /\+/g, '-' ).replace( /\//g, '_' ).replace( /=/g, '' ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment