Make a Password with Ruby

…and zshhttp://en.wikipedia.org/wiki/Z_shell

I’ve done this with Haskell/articles/make-a-password-with-haskell and Perl/articles/make-a-password, but lately I’ve been using the venerable makeapass widgethttp://andrew.hedges.name/widgets/#makeapass whenever a website registration asks for a password. As my laptop gets slower by the day, waiting for the dashboard to appear gets frustrating… Why not use a shell command wrapped around Ruby! And why not put it straight on the clipboard!

Here it is:

# put this in ~/.zshrc
new_password() {
 ruby -rSecureRandom -e "n = '$1'.to_i; n = 16 if n.zero?; puts SecureRandom.urlsafe_base64(n)[0..(n - 1)]" | pbcopy

After running source ~/.zshrc the command is available - it even gets completion!

$ new_password
# put PACCl-tGs9HQC1X8 on the clipboard
$ new_password 52
# put UwNcBoprAIxuropuK7qaTzxyTSceX9ee8Gr5A88104E8-cZVAxfM on the clipboard

I rarely use a shell function as it’s easier for me to just drop down into Ruby, which is why it looks so ugly (especially as zsh docs aren’t usually up-to date or easy to read), but it works. It also makes use of the SecureRandom libraryhttp://www.ruby-doc.org/stdlib-1.9.3/libdoc/s…, so no need to worry about the randomness, it’ll be enough.

Added on:
Last updated:
Info:- Ruby 2.0 - OSX 10.6.8