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


  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’`

    • 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?

      • 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?

        • 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?

          • 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”

            • Woah! This is something really weird. It shouldn’t do such a thing. Let me explore this further and get back to you.

            • 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.

              • OSX:

                => “$6GFbj3O6XCj2”


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

                • 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.

  2. Pingback: Läksy w49: Oman Puppet modulin julkaiseminen « eliimatt

  3. Pingback: Läksy w48: Oman Puppet modulin toteuttaminen « eliimatt

  4. Pingback: Läksy w45: Muotit, parametrisoidut luokat ja määritellyt tyypit « eliimatt

Comments are closed.