Thoughts are free, who can guess them?
They flee by like nocturnal shadows.
No man can know them, no hunter can shoot them,
with powder and lead: Thoughts are free!
About www.weisserth.net
Tobias Weisserth
Hamburg, Germany
photographer & independent gearhead

Using the MySQL encrypt function in Ruby

Posted by polarapfel on Sun, 14 Feb 2010 17:48

If you’re dealing with a legacy MySQL database schema where your users’ passwords are encrypted using MySQL’s encrypt function within your schema and you want to create new records like that using Ruby rather than calling the MySQL function, you can easily do that with Ruby. Ruby supplies a crypt function that does just what the MySQL encrypt function provides. Both implementations use the UNIX C function crypt(3) so you can replace the use of one with another.

The function expects a salt value of two characters. If none is provided, a random string will be used. Take a look at this simple example:

  #!/usr/bin/env ruby -wKU

  def mysql_encrypt(pw)
    
    # compute a random salt value
    # (will end up to be a Base64 encoded string 
    # of random characters)
    salt = [Array.new(2){rand(256).chr}.join].pack("m").chomp
    return pw.crypt(salt)
  end

  encrypted_password = mysql_encrypt("test")

  puts "Encrypted password could be " + encrypted_password

  # we take the first two characters of the already
  # encrypted password as salt value
  # for the re-encryption so we end up with the same value
  
  compared_password = "test".crypt(encrypted_password[0,2])

  puts "The re-encrypted 'test' string is now " + compared_password

Creating hashed passwords using crypt(3) cannot be regarded as secure though. Take a look at the Wikipedia entry on crypt. If you’re implementing any kind of user authentication from scratch, consider using other means of hashing passwords.

Trackbacks

Use the following link to trackback from your own site:
http://www.weisserth.net/trackbacks?article_id=11

Comments

Leave a comment

Comments