diff --git a/sha256.rb b/sha256.rb index cbe16f3..4d2ef50 100644 --- a/sha256.rb +++ b/sha256.rb @@ -11,11 +11,16 @@ if !defined? $input # Detect input type (binary, hex, or string) $type = input_type($input) + # Read file if file is given + if $type == "file" + $input = File.read($input) + end + # Convert input to bytes (if possible) $bytes = bytes($input, $type) # Set message (binary representation of data) - if $type == "string" || $type == "hex" + if $type == "string" || $type == "file" || $type == "hex" $message = $bytes.map { |x| x.to_s(2).rjust(8, "0") }.join # convert bytes to binary string end if $type == "binary" diff --git a/sha256lib.rb b/sha256lib.rb index baa59d2..94d988f 100644 --- a/sha256lib.rb +++ b/sha256lib.rb @@ -65,24 +65,29 @@ end # Detect input type base on prefix (i.e. binary, hex, or otherwise just a string) def input_type(input) - # Check for hex or binary prefix - case input[0..1] - when "0b" - # check it's a valid binary string - if input[2..-1] =~ /[^0-1]/ # only 1s and 0s - puts "Invalid binary string: #{input}" - exit - end - return "binary" - when "0x" - # check it's a valid hex string - if input[2..-1] !~ /^[0-9A-F]+$/i # only hex chars (case-insensitive) - puts "Invalid hex string: #{input}" - exit - end - return "hex" + # Check if input is referencing a file + if(File.file?(input)) + return "file" else - return "string" + # Check for hex or binary prefix + case input[0..1] + when "0b" + # check it's a valid binary string + if input[2..-1] =~ /[^0-1]/ # only 1s and 0s + puts "Invalid binary string: #{input}" + exit + end + return "binary" + when "0x" + # check it's a valid hex string + if input[2..-1] !~ /^[0-9A-F]+$/i # only hex chars (case-insensitive) + puts "Invalid hex string: #{input}" + exit + end + return "hex" + else + return "string" + end end end