Use Ruby to Generate your Shadow Password

I was initially stumbled on creating the shadow compatible SHA-512 hash.
After a little research, the answer was obvious:

require 'digest/sha2'

password = "pass@123"
salt = rand(36**8).to_s(36)
shadow_hash = password.crypt("$6$" + salt)

And you now have a password hash which you can directly use in /etc/shadow

21 Replies to “Use Ruby to Generate your Shadow Password”

  1. I tried creating a user in Ubuntu using the output of this but it won’t let me login…

    password = ‘foobar’.crypt(“$6$” + rand(36**8).to_s(36))
    `ssh root@#{fqdn} ‘useradd -m -g sudo -s /bin/bash -p #{password} admin’`

    1. There is a chance that your system is not configured to use this method of encryption. By default it uses some other, I think a single MD5 hash.

      You’ll have to Google on how to check and migrate if required. Additionally, I think that it’s trying to re – hash the hash itself. Can you check /etc/shadow and see what’s the final hash like?

      1. I’m creating the hash based on user input on OSX Mountain Lion and then adding the user by SSH’ing the resulting script to Ubuntu 13.04.

        It turns out that the crypt function returns different results on OSX and Ubunto… I don’t suppose you would know a way to create an Ubuntu compatible shadow password on OSX?

        1. That’s highly unlikely. What’s the exact line generating the hash?

          Can you post the result of running the same ruby code in irb on both Mac and Ubuntu?

          1. That’s what I thought but…

            On OSX Mountain Lion:

            require ‘digest/sha2’
            ‘foobar’.crypt(“$6$” + rand(36**8).to_s(36))
            => “$6GFbj3O6XCj2”

            On Ubunto 13.04

            require ‘digest/sha2’
            ‘foobar’.crypt(“$6$” + rand(36**8).to_s(36))
            => “$6$iz5ko3ah$SrX1fP1PEjRnXewy07ka.13NRPzNWpPIEAbcUlDG8YvRAByK1BmnZ0g.zmVzgjHv.xZgyY5BUFgKicnatHffl0”

            1. Jamie,
              The salt is changing. Keep the salt constant on both runs of the command in irb. The function rand is generating a random salt everything you execute the command.

              1. OSX:

                => “$6GFbj3O6XCj2”


                => “$6$iz53ah$6BYFyUYh1rvcsJvdda27l0wpHm.dlorvzEXJSex8aHbiR2E4GDrVDAhvHCThJfefl7kWn2SvEZFESzRfAKBNG.”

                1. I am absolutely sure that what OSX is generating for you is not SHA 512. The hash doesn’t follow the standard. There is some other algorithm that’s working instead.

                  I’m certain that some other library is messing up.

                  1. Did you see the Stack Overflow issue, it looks like the crypt method uses the system’s own implementation which is obviously different on OSX. Is there a way for force SHA512 that you know of?

            1. The code that I used for generating the hash should work across all platforms. Could you run the generating line in irb on both, Mac and Ubuntu?

Comments are closed.