6 ms·
Hashing a value from Math.random() with a cryptographic hash (i.e. SHA256) doesn't make it cryptographically random[1]. If you want a random string get one dir
by sehrope 8y ago
Hashing a value from Math.random() with a cryptographic hash (i.e. SHA256) doesn't make it cryptographically random[1].
If you want a random string get one directly via crypto.randomBytes(...)[2]:
const id = crypto.randomBytes(32).toString('hex');
[1]: https://github.com/bluzi/jsonstore/blob/87af0d3ef6bf11222b98c00bbfda3ea48c30be57/api/routes.js#L9-L10 https://github.com/bluzi/jsonstore/blob/87af0d3ef6bf11222b98...
[2]: https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback https://nodejs.org/api/crypto.html#crypto_crypto_randombytes...
- bluzi 8y agoThanks, feel free to create a pull request.
- cobookman 8y agoWhy not use uuids?
- majewsky 8y agoThese need not be cryptographically random either.
- sehrope 8y agoUUIDs are fine too. What matters is how they're generated. If you're generating v4 UUIDs server side using the "uuid" NPM module then you're fine as internally it's using crypto.randomBytes(...)[1] with an almost 16-byte random string (UUIDs are 16-bytes but a proper v4 UUID has to override some of the bits to conform to the spec[2]). If you're rolling your own UUID function or generating them client side then they may not be as random as you think. For example the same uuid NPM module silently uses Math.random()[3] on the client side if it can't find a better alternative. It's fine for something purely local to the one browser but I wouldn't rely on it being unique globally. [1]: https://github.com/kelektiv/node-uuid/blob/17d443f7d8cfb65a7d85803218df27a6b4ae8397/lib/rng.js#L7 https://github.com/kelektiv/node-uuid/blob/17d443f7d8cfb65a7... [2]: https://github.com/kelektiv/node-uuid/blob/17d443f7d8cfb65a7d85803218df27a6b4ae8397/v4.js#L15-L17 https://github.com/kelektiv/node-uuid/blob/17d443f7d8cfb65a7... [3]: https://github.com/kelektiv/node-uuid/blob/17d443f7d8cfb65a7d85803218df27a6b4ae8397/lib/rng-browser.js#L20-L28 https://github.com/kelektiv/node-uuid/blob/17d443f7d8cfb65a7...