Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate openssl password with Ruby

Tags:

ruby

openssl

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.

like image 903
Elliot Larson Avatar asked Aug 04 '26 15:08

Elliot Larson


2 Answers

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.

like image 182
onemouth Avatar answered Aug 06 '26 08:08

onemouth


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.

like image 39
whitehat101 Avatar answered Aug 06 '26 09:08

whitehat101



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!