Last active
March 7, 2024 08:49
-
-
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.
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
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