Friday, July 4, 2008

MySQL ENCRYPT function in Ruby (for Rails)

Zhe backend system required that the password column used the MySQL ENCRYPT function. Since I didn't wanted to hack rails to much, I just aded the required code into the rails model directly - 5 minutes work, voila.

When the password get's assigned, it is automatically "MySQL encrypted". Here's ther code for reference:

def password=(pw)
self[:password] = mysql_encrypt(pw)
end

private
def mysql_encrypt(pw)
salt = [Array.new(6){rand(256).chr}.join].pack("m").chomp
return pw.crypt(salt)
end

2 comments:

nerbie69 said...

so has this way been successful for you? I just came across a db column that uses mysql's encrypt function, and wanted to know if this was the best way to do it? cheers. good work.

Tobias said...

Thanks for sharing this. I hereby tag this blog post as #useful! :-)