Skip to content
Home » How to Generate PKCE Challenge from Verifier in JavaScript

How to Generate PKCE Challenge from Verifier in JavaScript

This blog post will guide you on how to generate a PKCE (Proof Key for Code Exchange) challenge from a verifier in JavaScript. PKCE is an authentication method used in OAuth 2.0 to protect against code interception attacks. We will be using the SHA-256 hash algorithm and base64url encoding to generate the PKCE challenge.

Code

// SHA

function sha256(plain: any) {
  // returns promise ArrayBuffer
  const encoder = new TextEncoder();
  const data = encoder.encode(plain);
  return window.crypto.subtle.digest('SHA-256', data);
}

function base64urlencode(a: any) {
  // Convert the ArrayBuffer to string using Uint8 array.
  // btoa takes chars from 0-255 and base64 encodes.
  // Then convert the base64 encoded to base64url encoded.
  // (replace + with -, replace / with _, trim trailing =)
  // @ts-ignore
  return btoa(String.fromCharCode.apply(null, new Uint8Array(a)))
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=+$/, '');
}

export async function pkceChallengeFromVerifier(v: any) {
  const hashed = await sha256(v);
  return base64urlencode(hashed);
}

Code Explanation

The provided code snippet includes the following functions:

1. sha256(plain: any): This function takes a plain text input and returns a Promise that resolves to an ArrayBuffer. It first encodes the plain text using the TextEncoder API, then uses the window.crypto.subtle.digest() method to compute the SHA-256 hash of the encoded data. Finally, it returns the hash as an ArrayBuffer.

2. base64urlencode(a: any): This function takes an ArrayBuffer as input and converts it to a string using a Uint8 array. It then base64 encodes the string using the btoa() function. After that, it converts the base64 encoded string to base64url encoded format by replacing “+” with “-“, “/” with “_”, and trimming any trailing “=” characters. The resulting string is then returned.

3. pkceChallengeFromVerifier(v: any): This async function takes a verifier as input and generates the PKCE challenge. It first calls the sha256() function to compute the hash of the verifier. Then, it passes the hashed value to the base64urlencode() function to get the base64url encoded challenge. Finally, the function returns the PKCE challenge.

Example usage:

To generate a PKCE challenge from a verifier, you can call the pkceChallengeFromVerifier() function with the verifier as the argument. Here’s an example:

javascript
const verifier = "SOME_VERIFIER_VALUE";
const challenge = await pkceChallengeFromVerifier(verifier);
console.log("PKCE challenge:", challenge);

In the above example, we define a variable verifier with a sample value. We then call the pkceChallengeFromVerifier() function with the verifier and await its result. Finally, we print the generated PKCE challenge to the console.

Conclusion

In this blog post, we have learned how to generate a PKCE challenge from a verifier in JavaScript. The provided code snippet showcases the implementation of the necessary functions using the SHA-256 hash algorithm and base64url encoding. By following the example usage, you can easily generate PKCE challenges for secure authentication in OAuth 2.0 flows.

Also checkout the following codes.


How to Install TypeScript and Required Dependencies for Node.js and React Projects
Program to Convert Month Index to Month Name in JavaScript