Never been to DZone Snippets before?

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 (See related posts)

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 on this post

peter posts on Jul 28, 2005 at 22:22
In that case why not just allow a-z and 1-9. That way 0 isn't involved, and it's easier to read as there are only little letters and numbers.
jmoses posts on Jul 29, 2005 at 13:59
Eh. There's no reason not to, I suppose, but I was _really_ lazy. You understand.

If I was really motivated I'd strip out all the look-alikes (1 and I) before generating the password. Wouldn't be hard.
rikkus posts on Jul 31, 2005 at 02:55
You could also use ruby-password to generate. It does 'memorable' passwords too:

http://www.caliban.org/ruby/ruby-password/classes/Password.html#M000005
jmoses posts on Aug 01, 2005 at 20:29
Heh. I should have figured somebody had written and released something like that. Oh well. I learnt something anyways.
itchybeard posts on May 28, 2006 at 02:38
This method doesn't need to be buried though, it can instead be used to generate random keys for databases, cookies and the like. I have a method that does exactly the same thing but written completely differently here:

http://www.bigbold.com/snippets/posts/show/2111

I have to say your one is prettier. I might just steal it ;)
peter posts on Oct 21, 2006 at 13:06
Here's what I'm using nowadays:

chars = ("a".."z").to_a + ("1".."9").to_a 
newpass = Array.new(8, '').collect{chars[rand(chars.size)]}.join
disgustingangel posts on Apr 01, 2007 at 17:28
Maybe

def newpass(len)
chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
return Array.new(10){||chars[rand(chars.size)]}.join
end

could be more readable?

You need to create an account or log in to post comments to this site.


Click here to browse all 5140 code snippets

Related Posts