#!/usr/bin/env ruby # Author Eric Monti (emonti at matasano) # # hexify converts a string or raw data to hex characters. Input can be # supplied via stdin, a string argument, or a file (with -f). # # Usage: hexify [options] # -h, --help Show this message # -v, --version Show version and exit # -f, --file FILENAME Input from FILENAME # -l, --length LEN Hexify in lines of LEN bytes # -d, --delim=DELIMITER DELIMITER between each byte # -p, --prefix=PREFIX PREFIX before each byte # -s, --suffix=SUFFIX SUFFIX after each byte # require 'rbkb' require 'rbkb/command_line' include RBkB::CommandLine #------------------------------------------------------------------------------ # Init options and arg parsing OPTS = {} arg = bkb_stdargs(nil, OPTS) arg = bkb_inputargs(arg, OPTS) arg.banner += " " #------------------------------------------------------------------------------ # Add local options arg.on("-l", "--length LEN", Numeric, "Hexify in lines of LEN bytes") do |l| bail("Length must be greater than zero") unless (OPTS[:len] = l) > 0 end arg.on("-d", "--delim=DELIMITER", "DELIMITER between each byte") do |d| OPTS[:delim] = d end arg.on("-p", "--prefix=PREFIX", "PREFIX before each byte") do |p| OPTS[:prefix] = p end arg.on("-s", "--suffix=SUFFIX", "SUFFIX after each byte") do |s| OPTS[:suffix] = s end #------------------------------------------------------------------------------ # Parse arguments arg.parse!(ARGV) rescue bail "Error: #{$!}\nUse -h|--help for more info." # original-style spacing compatability if ARGV[0] == "+" and OPTS[:delim].nil? OPTS[:delim]=" " ARGV.shift end # default string arg if OPTS[:indat].nil? and a=ARGV.shift OPTS[:indat] = a.dup end # catchall if ARGV.length != 0 bail "Error: bad arguments - #{ARGV.join(' ')}\n-h|--help for more info." end # Default to standard input OPTS[:indat] ||= STDIN.read() #------------------------------------------------------------------------------ # Do stuff indat = OPTS.delete(:indat) len = OPTS.delete(:len) exit 1 unless((len ||= indat.length) > 0) until (m = indat.slice!(0..len-1)).empty? print m.hexify(OPTS) puts (OPTS[:delim] and not indat.empty?)? OPTS[:delim] : "\n" end