Skip to content

Instantly share code, notes, and snippets.

@ondrek
Last active December 25, 2015 12:59
Show Gist options
  • Save ondrek/6980466 to your computer and use it in GitHub Desktop.
Save ondrek/6980466 to your computer and use it in GitHub Desktop.
Random Uniq Number (only 8-chars)
getRandom = function(){
var date = new Date().getTime();
var random = Math.floor((Math.random()*800)+100);
return(date+random).toString(36);
};
@ondrek
Copy link
Author

ondrek commented Oct 14, 2013

Random Uniq Number (only 8-chars)

by Samuel Ondrek


  • I use this method in my project Markdown mDown Project
  • Returns strings simular to hms2udc2, hms2ucwc, hms2ubtt, ..

Why you should use this method?

  • Because result is (and always will be) short string
  • Because result is always uniq
  • Because result is short
  • Because to guess next iteration is difficult (without knowledge of method)

How it works?

// miliseconds from 01.01.1970
// you can use different method of time-uniq number
1381778973111

// random (100~999) gets always same lenght of string
// so last string has always same lenght
889

// addition of both numbers for more uniq combination
// also more difficult randomly find correct one
1381778973111889

// convert this to base 36 (no base10, no base16, base36)
// so it's shorter and readable
hms3r897

How to improve code to more secure?

  • Change random number lenght Math.floor((Math.random()*8000000)+100)
  • Add random string random+'secretHash'.toString(36)
  • You can also change string to different base instead of 36

When I cannot use this?

  • If your users request code more like 10000x in one second
  • .. and if you still want, you should check ifExists

Copyright

  • Samuel Ondrek
  • Use it where you need, if it's public project, you can add link :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment