DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Generate A Random Password
I recently had need to generate random passwords for users. Obviously they need to be alphanumerica. Here's what I came up with.
def newpass( len )
chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
newpass = ""
1.upto(len) { |i| newpass << chars[rand(chars.size-1)] }
return newpass
end
It generates a random password using the upper and lower case alphabet, and the numbers 0 to 9, to the size passed in.
No effort is made to make an easy to read password. For example, 0 (zero) _will_ show up next to O (capital o). Yay.






Comments
Carla Brian replied on Sun, 2012/07/15 - 6:34pm
Phil Thompson replied on Wed, 2010/05/05 - 6:22pm
Array.new(10)should beArray.new(len). Having a default value for len would be nice too.Snippets Manager replied on Sat, 2008/07/05 - 1:18am
Snippets Manager replied on Tue, 2009/01/06 - 8:48am
Snippets Manager replied on Sat, 2009/01/24 - 11:55pm
Jeff Smick replied on Thu, 2006/04/13 - 8:05pm
def rand_str(len) Array.new(len/2) { rand(256) }.pack('C*').unpack('H*').first endIt's very fastSnippets Manager replied on Sun, 2007/04/01 - 5:25pm
Snippets Manager replied on Mon, 2012/05/07 - 2:13pm
chars = ("a".."z").to_a + ("1".."9").to_a newpass = Array.new(8, '').collect{chars[rand(chars.size)]}.joinSnippets Manager replied on Sun, 2006/05/28 - 1:58am
Snippets Manager replied on Mon, 2012/05/07 - 2:13pm
Snippets Manager replied on Mon, 2012/05/07 - 2:13pm
Snippets Manager replied on Mon, 2012/05/07 - 2:13pm
Snippets Manager replied on Mon, 2012/05/07 - 2:13pm