Search code examples
rubyhashyamldigest

Digesting value in YAML file into MD5 hash


I have a YAML file containing usernames and passwords.

Overview of YAML:

users:
 test:
    password: test
  test2:
    password: test2

I want to encrypt the password value into an MD5 hash using Digest::MD5 for example:

user:
  Lost Bam:
    password: testtesttest #<=I want to overwrite this password with a MD5 hash

In Digest is there a way to encrypt a hash value? If so how do I implement this into a YAML file?

md5.rb Source:

require 'yaml'
require 'digest'

private

    def load_file
        File.exist?('info.yml') ? YAML.load_file('info.yml') : {users: {}}
    end

    def read_file
        File.read('info.yml')
    end

    def save_file( hash )
        File.open('info.yml', 'w') { |f| f.write(hash.to_yaml)}
    end

    def add_user
        hash = load_file
        hash["users"][prompt('Enter username:')] =
            { "password" =>  prompt('Enter password:') }
        puts "Encrypt information?"
        information = gets.chomp
        case input
        when /yes/i
#           hash = Digest::MD5.digest(["password"]'value')<-Doesn't work
#
#This is where I want to be able to encrypt the 
#value of the password key that was entered by the user
#
#           save_file( hash )
        else
            puts "Add another?"#Not completed yet
        end
        save_file( hash )
    end

main.rb Source:

require_relative 'md5.rb'

def main
     puts <<-END.gsub(/^\s*>/, '')
                >
                >To load information type "L" to quit system type "Q"
                >
            END
    input = gets.chomp.upcase
    case input
    when "L"
        add_user
    when "Q"
        exit_system
    else
        exit_lock
    end
end

def exit_system
    puts "Exiting..."
    exit
end

def exit_lock
    puts "Locked out, please contact system administrator"
    exit
end

def restart
    puts "Encrypt more?"
    input = gets.chomp
    if input =~ /yes/i
        return true
    else 
        exit_system
    end
end

def prompt( message )
    puts message
    gets.chomp
end
main

Solution

  • You can use Digest::MD5:

    require 'digest'
    Digest::MD5.digest('value')
    

    http://ruby-doc.org/stdlib-2.1.0/libdoc/digest/rdoc/Digest.html