Skip to content

Commit

Permalink
fix: base64 charset for keygen
Browse files Browse the repository at this point in the history
  • Loading branch information
Dwynr committed Feb 12, 2025
1 parent 1fb150a commit 275e412
Showing 1 changed file with 6 additions and 8 deletions.
14 changes: 6 additions & 8 deletions src/crypto/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,14 @@ const textEncoder = new TextEncoder()
* @returns {string}
*/
export async function generateRandomString({ length }: { length: number }): Promise<string> {
const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"

if (environment === "node") {
const randomBytes = nodeCrypto.randomBytes(length + 2)
const randomBytes = nodeCrypto.randomBytes(length)
const result = new Array(length)
let cursor = 0

for (let i = 0; i < length; i++) {
cursor += randomBytes[i]!
result[i] = chars[cursor % chars.length]
result[i] = chars[randomBytes[i]! % chars.length]
}

return result.join("")
Expand All @@ -36,9 +34,9 @@ export async function generateRandomString({ length }: { length: number }): Prom

globalThis.crypto.getRandomValues(array)

const randomNumbers = Array.from(array).map(x => x % chars.length)

return randomNumbers.map(x => chars[x]).join("")
return Array.from(array)
.map(x => chars[x % chars.length])
.join("")
}

throw new Error(`crypto.utils.generateRandomString not implemented for ${environment} environment`)
Expand Down

0 comments on commit 275e412

Please sign in to comment.