Score:0

Node.js generated JWT secret, nanoid() vs crypto.randomBytes() which is stronger

za flag

Which method will generate stronger secret?

64 character secret generated by nanoid (https://www.npmjs.com/package/nanoid) with characters: 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_- e.g.: hNr3COb9fSz5qfZBCQx3GkpLVW-tbVM0E-Nl8xgcf8Js8-l6fqOIfSd6Gk-T_nkE

or crypto.randomBytes(32).toString('hex') e.g.: d152189824ea6b25c34048960dfa57722d547eff9e4e98a67064d910010e6747

both create 64 character number but I'm not sure which is stronger as a secret for JWT signing (HS256)

Maarten Bodewes avatar
in flag
Nanoid doesn't seem to be made for this - it generates an ID not a key. Just generating 32 secure random bytes is fine for HMAC/SHA-256 - presuming you are OK with keeping it in software of course, but that's generally OK for tokens. Don't confuse hex / base 64 with the bytes that are encoded using them.
wefad12292 avatar
za flag
@MaartenBodewes do I understand correctly that decoded secret from .randomBytes() has higher entropy than secret generated from 64 alphabet characters? (e.g. decoded secret: �txK�:O�>�o/2�L�Q�B� has characters like ">" "/" and some that aren't represented in utf-8 e.g. �) so its harder to theoretically brute force it?
Maarten Bodewes avatar
in flag
That depends what is encoded by those characters. Nanoid seems to encode 126 bits of random bits from the same crypto module. For HMAC/SHA-256 you'd normally use a 256 bit / 32 byte key, and larger key sizes are unnecessary. `crypto.randomBytes` should normally use the RNG of the OS which is fine. Not sure about the exact entropy in there, but on a correctly configured system I'd expect 128 bits *minimum*. Entropy is always a bit of a laden term when it comes to PRNG's and - sorry - JavaScript / NodeJS documentations is terrible so you'd have to look into the source code to be sure.
wefad12292 avatar
za flag
@MaartenBodewes got it, thanks a lot.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.