Skip to content

Instantly share code, notes, and snippets.

@adam12
Forked from kennethkalmer/user.rb
Created June 8, 2009 18:01
Show Gist options
  • Save adam12/125961 to your computer and use it in GitHub Desktop.
Save adam12/125961 to your computer and use it in GitHub Desktop.
module Linux
class User
class << self
# Generate an MD5 salt string
def salt
seeds = ('a'..'z').to_a
seeds.concat( ('A'..'Z').to_a )
seeds.concat( (0..9).to_a )
seeds.concat ['/', '.']
seeds.compact!
salt_string = '$1$'
8.times { salt_string << seeds[ rand(seeds.size) ].to_s }
salt_string
end
# Crypt a password suitable for use in shadow files
def crypt( string )
string.crypt( self.salt )
end
end
end
end
require File.dirname(__FILE__) + '/../spec_helper'
describe Linux::User do
describe "generating shadow passwords" do
it "should generate a salt for crypt" do
salt = Linux::User.salt
salt.length.should be(11)
salt.should match(/^\$1\$[a-zA-Z0-9\.\/]{8}$/)
end
it "should generate a shadow password" do
pass = Linux::User.crypt( 'secret' )
pass.should match(/^\$1\$[a-zA-Z0-9\.\/]{8}\$[a-zA-Z0-9\.\/]{22}$/)
pass.length.should be(34)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment