Reputation: 11049
I'd like to use the ruby openssl library to generate the same thing as this openssl command:
$ openssl passwd -1 mypassword
Right now, in my code, I'm doing this:
mypass = `openssl passwd -1 mypassword`
... this works, but it seems silly. I feel like you should be able to use OpenSSL::Digest to achieve the same result. However, I can't seem to get it to work.
Upvotes: 3
Views: 919
Reputation: 2549
This is compatible with openssl passwd -1
require 'openssl'
module CryptMD5
refine String do
def crypt_md5 salt = OpenSSL::Random.random_bytes(6)
crypt ['$1$', salt].pack('a3m0').tr(?+, ?.).delete(?=)
end
end
end
using CryptMD5
pass = '$1$i7VbAY.b$uy5kgtLn8m2daMxOBEz6p.'
salt = pass[3..10].tr(?., ?+).unpack1 'm0'
puts pass == 'secret'.crypt_md5(salt) # => true
puts pass == 'secret'.crypt_md5(salt + 'ignored extra') # => true
puts 'secret'.crypt_md5 # => $1$bMylNdtr$/fxt7r7gzdossTabWD/xT/
puts 'secret'.crypt_md5 # => $1$y6O7OsY7$bDl3yEKJXM0lhg3DYye6Z1
pass = `openssl passwd -1 secret`.chomp
salt = pass[3..10].tr(?., ?+).unpack1 'm0'
puts pass == 'secret'.crypt_md5(salt) # => true
Calling String#crypt
with a string usually only uses the first two characters as salt, but if prefixed with $1$
it will use the next 6 bytes / 8 characters as a salt with a modified base64 alphabet (swapping +
and .
). Any more bytes / chars are just truncated.
Upvotes: 1
Reputation: 2277
openssl passwd -1
implements UNIX crypt(3) algorithm. The implementation (md5crypt) resides in apps/passwd.c
. As a result, the implementation code is not a OpenSSL library function. As the function comment says:
MD5-based password algorithm (should probably be available as a library function; then the static buffer would not be acceptable).
So you will not find it in OpenSSL::Digest.
However, you may find other libraries useful, such as unix-crypt.
Upvotes: 3