Skip to content

Commit

Permalink
feat: Random base64url
Browse files Browse the repository at this point in the history
  • Loading branch information
przpl committed Feb 26, 2024
1 parent 9d1460f commit 1ead7d9
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from "./random/randomBase64";
export * from "./random/randomBase64Url";
export * from "./random/randomHex";
export * from "./random/randomNumeric";
13 changes: 13 additions & 0 deletions src/random/randomBase64Url.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import assert from "node:assert";
import { randomBytes } from "node:crypto";

/**
* Generates a random base64url string with the specified number of characters.
* @param charactersCount The number of characters in the generated string.
*/
export function randomBase64Url(charactersCount: number) {
assert(charactersCount > 0, "charactersCount must be greater than 0");

const byteCount = Math.ceil((charactersCount * 3) / 4);
return randomBytes(byteCount).toString("base64url").substring(0, charactersCount);
}

0 comments on commit 1ead7d9

Please sign in to comment.