class CryptBufferInputConverter

Public Instance Methods

convert(input) click to toggle source
# File lib/crypto-toolbox/crypt_buffer_input_converter.rb, line 6
def convert(input)
  bytes_from_any(input)
end
from_base64(input) click to toggle source
# File lib/crypto-toolbox/crypt_buffer_input_converter.rb, line 22
def from_base64(input)
  string = Base64.decode64(input)
  CryptBuffer.new(str2bytes(string))
end
from_hex(input) click to toggle source

Make sure input strings are always interpreted as hex strings This is especially useful for unknown or uncertain inputs like strings with or without leading 0x

# File lib/crypto-toolbox/crypt_buffer_input_converter.rb, line 13
def from_hex(input)
  raise InvalidHexstring, "input: #{input} is not a valid hexadicimal string" unless valid_hexstring?(input)
  hexstr =""
  unless input.nil?
    hexstr = normalize_hex(input)
  end
  CryptBuffer.new(hex2bytes(hexstr))
end

Private Instance Methods

bytes_from_any(input) click to toggle source
# File lib/crypto-toolbox/crypt_buffer_input_converter.rb, line 28
def bytes_from_any(input)
  case input
  when Array
    input
  when String
    str2bytes(input)
  when CryptBuffer
    input.b
  when Fixnum
    int2bytes(input)
  when NilClass
    []
  else
    raise "Unsupported input: #{input.inspect} of class #{input.class}"
  end
end
hex2bytes(hexstr) click to toggle source
# File lib/crypto-toolbox/crypt_buffer_input_converter.rb, line 49
def hex2bytes(hexstr)
  hexstr.scan(/../).map{|h| h.to_i(16) }
end
int2bytes(input) click to toggle source
# File lib/crypto-toolbox/crypt_buffer_input_converter.rb, line 45
def int2bytes(input)
  [input].pack('C*').bytes
end
normalize_hex(str) click to toggle source
# File lib/crypto-toolbox/crypt_buffer_input_converter.rb, line 65
def normalize_hex(str)
  tmp = pad_hex_char(str)
  tmp.gsub(/(^0x|\s)/,"").upcase
end
pad_hex_char(str) click to toggle source
# File lib/crypto-toolbox/crypt_buffer_input_converter.rb, line 61
def pad_hex_char(str)
  (str.length == 1) ? "0#{str}" : "#{str}"
end
str2bytes(str) click to toggle source
# File lib/crypto-toolbox/crypt_buffer_input_converter.rb, line 53
def str2bytes(str)
  if str.match(/^0x[0-9a-fA-F]+$/).nil?
    str.bytes.to_a
  else
    hex2bytes(normalize_hex(str))
  end
end
valid_hexstring?(input) click to toggle source
# File lib/crypto-toolbox/crypt_buffer_input_converter.rb, line 71
def valid_hexstring?(input)
  input =~ /^(0x)?[a-fA-F0-9]+$/
end