Skip to content

Instantly share code, notes, and snippets.

@t1mofe1
Last active March 7, 2024 08:49
Show Gist options
  • Save t1mofe1/2eaedc6587c2c20eabdda5057905e073 to your computer and use it in GitHub Desktop.
Save t1mofe1/2eaedc6587c2c20eabdda5057905e073 to your computer and use it in GitHub Desktop.
PKCE Generator in nodejs which generates `code_challenge` and `code_verifier` using sha256. Implemented custom length feature.
import * as crypto from 'crypto';
export type PkcePayload = {
code_verifier: string;
code_challenge: string;
code_challenge_method: 'S256';
};
export default function generatePKCE(length = 128): PkcePayload {
if (length < 43) length = 43;
if (length > 128) length = 128;
const bytesLength = Math.ceil((length * 3) / 4);
const code_verifier = crypto.randomBytes(bytesLength).toString('base64url');
const code_challenge = crypto
.createHash('sha256')
.update(code_verifier)
.digest()
.toString('base64url');
return {
code_verifier,
code_challenge,
code_challenge_method: 'S256', // TODO: support plain?
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment