3

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.

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0
require 'openssl' OpenSSL::Digest::MD5.hexdigest(mypassword) 

1 Comment

If my password is 'secret', the openssl command produces: $1$i7VbAY.b$uy5kgtLn8m2daMxOBEz6p. Your Ruby openssl digest command produces: ebe2294ecd0e0f08eab7690d2a6ee69

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.