module Ronin::Support::Encoding::SQL

Contains methods for encoding/decoding escaping/unescaping SQL data.

## Core-Ext Methods

@api public

Constants

QUOTE_STYLES

The quote styles and their quote characters.

Public Class Methods

decode(data) click to toggle source

Returns the SQL decoded form of the String.

@param [String] data

The SQL string to decode.

@return [String]

The decoded String.
# File lib/ronin/support/encoding/sql.rb, line 118
def self.decode(data)
  if (data =~ /^[0-9a-fA-F]{2,}$/ && data.length.even?)
    raw = String.new

    data.scan(/../) do |hex_char|
      raw << hex_char.to_i(16)
    end

    return raw
  else
    unescape(data)
  end
end
encode(data) click to toggle source

Returns the SQL hex-string encoded form of the String.

@param [String] data

@return [String]

# File lib/ronin/support/encoding/sql.rb, line 97
def self.encode(data)
  return '' if data.empty?

  hex_string = String.new('0x')

  data.each_byte do |b|
    hex_string << ('%.2x' % b)
  end

  return hex_string
end
escape(data, quotes: :single) click to toggle source

Escapes a String for SQL.

@param [String] data

The String to SQL escape.

@param [:single, :double, :tick] quotes

Specifies whether to create a single or double quoted string.

@return [String]

The SQL escaped string.

@raise [ArgumentError]

The quotes argument was neither `:single`, `:double` nor `:tick`.
# File lib/ronin/support/encoding/sql.rb, line 57
def self.escape(data, quotes: :single)
  char = QUOTE_STYLES.fetch(quotes) do
           raise(ArgumentError,"invalid quoting style #{quotes.inspect}")
         end

  escaped = data.gsub(char,char * 2)

  return "#{char}#{escaped}#{char}"
end
unescape(data) click to toggle source

Unescapes a SQL String.

@param [String] data

The SQL string to unescape.

@return [String]

The unescaped SQL string value.

@raise [ArgumentError]

The String was not quoted with single, double or tick-mark quotes.
# File lib/ronin/support/encoding/sql.rb, line 79
def self.unescape(data)
  char = if    (data[0] == "'" && data[-1] == "'") then "'"
         elsif (data[0] == '"' && data[-1] == '"') then '"'
         elsif (data[0] == '`' && data[-1] == '`') then '`'
         else
           raise(ArgumentError,"#{data.inspect} is not properly quoted")
         end

  return data[1..-2].gsub(char * 2,char)
end