Secure Password Generation With Random Chars

user2977636 picture user2977636 · Sep 7, 2016 · Viewed 8.8k times · Source

I am trying to generate a random password that contains special chars using ruby. I would like to know if there is a standard for generating such passwords. I have considered using a weighted probability distribution and assigning weights such that there is a higher probability of picking special chars from , but I am not sure if this is a widely-accepted standard.

Answer

DiegoSalazar picture DiegoSalazar · Sep 7, 2016

Ruby comes with just such a module SecureRandom. You can generate random strings:

require "securerandom"

SecureRandom.hex 1 # => "e1"
SecureRandom.hex 2 # => "dcdd"
SecureRandom.hex 3 # => "93edc6"
SecureRandom.hex 5 # => "01bf5657ce"
SecureRandom.hex 8 # => "3cc72f70146ea286"

SecureRandom.base64 2  # => "d5M="
SecureRandom.base64 3  # => "EJ1K"
SecureRandom.base64 5  # => "pEeGO68="
SecureRandom.base64 8  # => "muRa+tO0RqU="
SecureRandom.base64 13 # => "1f8y7xsvaCEw0hwkjg=="

There is now a cryptographically secure version of the above called SysRandom which some people are recommending.

With the gem simple-password-gen You can also generate random and pronounceable passwords:

require "simple-password-gen"

Password.random 8 # => "#TFJ)Vtz3"
Password.pronounceable 13 # => "vingastusystaqu"

Finally, and just for fun (I recommend SysRandom), I wrote a small gem a while back to generate random strings based on template strings. Although it doesn't include special chars, it would be a trivial addition. Feel free to submit an issue for it if it interests you.