Skip to content

Instantly share code, notes, and snippets.

@dcaponi
Created January 1, 2021 19:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcaponi/7796fd4b99559dcda95f07bf6747c6ef to your computer and use it in GitHub Desktop.
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
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