RaR
RaR

Reputation: 3213

Generate custom-length unique random string in node

I want to generate unique 32-word length hash string for each user in my application, based on their id(each user has a unique id). When I was searching about this I found a similar question in SO. How to generate random SHA1 hash to use as ID in node.js? Gabi Purcaru's answer suggests using crypto module's createHash with the current time and a random string. Instead of that random string, I could use user's unique ID, so that I can make sure the generated string will always be unique. But this always gives me 40 string length hash. But I want it 32 string length. How to use the same approach to generate 32-word length random string?

crypto.createHash('sha1').update(current_date + uid).digest('hex'); //This always gives 40-word length string

I also referred naomik's great answer for the same question. He recommends using crypto.randomBytes(). But how can we ensure that it can never generate same string again?

Upvotes: 1

Views: 3306

Answers (2)

code_monk
code_monk

Reputation: 10130

Use md5

let hash = crypto.createHash('md5').update(current_date + uid).digest('hex');

Upvotes: 0

ponury-kostek
ponury-kostek

Reputation: 8060

crypto.createHash('sha1').update(current_date + uid).digest('hex').slice(0, 32);

will create what you need

Upvotes: 2

Related Questions