将YAML文件中的值摘要为MD5哈希值

时间:2015-11-18 18:25:27

标签: ruby hash yaml digest

我有一个包含用户名和密码的YAML文件。

YAML概述:

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

我想使用Digest::MD5将密码值加密为MD5哈希,例如:

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

在Digest中有没有办法加密哈希值?如果是这样,我如何将其实现为YAML文件?

md5.rb来源:

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来源:

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

1 个答案:

答案 0 :(得分:2)

您可以使用Digest :: MD5:

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

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