How can I use ruby to generate a MySQL password hash for its sha256 format?

Viewed 267

I am using puppet to manage my MySQL deployments. Service accounts are also managed via puppet because AWS doesn't provide the ability for me to leverage OpenLDAP as an authentication provider to RDS. I was given the requirement to use the sha256_password plugin for mysql. The puppet module I am using to manage everything, https://forge.puppet.com/puppetlabs/mysql, requires me to provide a hashed password to the user resource and the function included in the module only generates the mysql_native password. How can I use Ruby to generate the required hash? Below is the code I have so far.

require 'digest'

salt = Array.new(20){rand(256).chr}.join
hash = salt + 'Password'

rounds = 5000 # 5 iteration count * 1000 multipler per mysql code
x = 0
while x < rounds do
  hash = Digest::SHA2.new(256).hexdigest(hash)
  x += 1
end

h_salt = [salt].pack('H*')
b_hash = [hash[0..42]].pack('m')
h_hash = [hash].pack('H*')

value = '$A$005$' + h_salt + h_hash
print value

I can't determine if I'm encoding the salt and digest correctly. I believe I have the correct format other wise.

From https://crypto.stackexchange.com/questions/77427/whats-the-algorithm-behind-mysqls-sha256-password-hashing-scheme,

the expected format: DELIMITER[digest_type]DELIMITER[iterations]DELIMITER[salt][digest]

It seems after reviewing the source code and others implementation of it, the salt and digest are base64 encoded HEX values. Is that correct?

Some examples I leveraged were from: https://github.com/hashcat/hashcat/issues/2305

0 Answers
Related