Luke
Luke

Reputation: 2168

Buffer toString include all letters of alphabet

I'm using Node.js to create secure, random tokens. Take this example:

crypto.randomBytes(32).toString("hex");
// dd89d6ab1a7196e8797c2da0da0208a5d171465a9d8e918d3b138f08af3e1852

That's great, but it's a lot longer than it needs to be. I want to include all letters of the alphabet, not just a-f. Even better if it also includes capital letters. Remember, it needs to be secure, so it can't use Math.random.

Upvotes: 1

Views: 996

Answers (2)

rossum
rossum

Reputation: 15693

Generate a suitably sized random number. Convert it to base 36 (for 0..9, a..z) or base 62 (for 0..9, a..z, A..Z).

Upvotes: 1

Bhagyashree Sarkar
Bhagyashree Sarkar

Reputation: 519

Use this:

crypto.randomBytes(32).toString('base64');

Upvotes: 2

Related Questions