class UnixCrypt::CommandLine::Opts

Constants

HASHERS

Public Class Methods

parse(args) click to toggle source
# File lib/unix_crypt/command_line.rb, line 43
def self.parse(args)
  options            = OpenStruct.new
  options.hashmethod = :SHA512
  options.hasher     = HASHERS[options.hashmethod]
  options.password   = nil
  options.salt       = nil
  options.rounds     = nil
  options.leftovers  = OptionParser.new do |opts|
    opts.banner = "Usage: #{File.basename $0} [options]"
    opts.separator "Encrypts password using the unix-crypt gem"
    opts.separator ""
    opts.separator "Options:"

    opts.on("-h", "--hash [HASH]", String, "Set hash algorithm [SHA512 (default), SHA256, MD5, DES]") do |hasher|
      options.hashmethod = hasher.to_s.upcase.to_sym
      options.hasher     = HASHERS[options.hashmethod]
      raise Abort, "Invalid hash algorithm for -h/--hash" if options.hasher.nil?
    end

    opts.on("-p", "--password [PASSWORD]", String, "Provide password on command line (insecure!)") do |password|
      raise Abort, "Invalid password for -p/--password" if password.nil?
      options.password = password
      $0 = $0 # this invocation will get rid of the command line arguments from the process list
    end

    opts.on("-s", "--salt [SALT]", String, "Provide hash salt") do |salt|
      raise Abort, "Invalid salt for -s/--salt" if salt.nil?
      options.salt = salt
    end

    opts.on("-r", "--rounds [ROUNDS]", Integer, "Set number of hashing rounds (SHA256/SHA512 only)") do |rounds|
      raise Abort, "Invalid hashing rounds for -r/--rounds" if rounds.nil? || rounds.to_i <= 0
      options.rounds = rounds
    end

    opts.on_tail("-h", "--help", "Show this message") do
      puts opts
      exit
    end

    opts.on_tail("-v", "--version", "Show version") do
      puts UnixCrypt::VERSION
      exit
    end
  end.parse!(args)
  options
end