Method: Rex::Text.uri_encode

Defined in:
lib/rex/text.rb

.uri_encode(str, mode = 'hex-normal') ⇒ Object

Encode a string in a manor useful for HTTP URIs and URI Parameters.



775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
# File 'lib/rex/text.rb', line 775

def self.uri_encode(str, mode = 'hex-normal')
  return "" if str == nil

  return str if mode == 'none' # fast track no encoding

  all = /./
  noslashes = /[^\/\\]+/
  # http://tools.ietf.org/html/rfc3986#section-2.3
  normal = /[^a-zA-Z0-9\/\\\.\-_~]+/

  case mode
  when 'hex-all'
    return str.gsub(all) { |s| Rex::Text.to_hex(s, '%') }
  when 'hex-normal'
    return str.gsub(normal) { |s| Rex::Text.to_hex(s, '%') }
  when 'hex-noslashes'
    return str.gsub(noslashes) { |s| Rex::Text.to_hex(s, '%') }
  when 'hex-random'
    res = ''
    str.each_byte do |c|
      b = c.chr
      res << ((rand(2) == 0) ?
        b.gsub(all)   { |s| Rex::Text.to_hex(s, '%') } :
        b.gsub(normal){ |s| Rex::Text.to_hex(s, '%') } )
    end
    return res
  when 'u-all'
    return str.gsub(all) { |s| Rex::Text.to_hex(Rex::Text.to_unicode(s, 'uhwtfms'), '%u', 2) }
  when 'u-normal'
    return str.gsub(normal) { |s| Rex::Text.to_hex(Rex::Text.to_unicode(s, 'uhwtfms'), '%u', 2) }
  when 'u-noslashes'
    return str.gsub(noslashes) { |s| Rex::Text.to_hex(Rex::Text.to_unicode(s, 'uhwtfms'), '%u', 2) }
  when 'u-random'
    res = ''
    str.each_byte do |c|
      b = c.chr
      res << ((rand(2) == 0) ?
        b.gsub(all)   { |s| Rex::Text.to_hex(Rex::Text.to_unicode(s, 'uhwtfms'), '%u', 2) } :
        b.gsub(normal){ |s| Rex::Text.to_hex(Rex::Text.to_unicode(s, 'uhwtfms'), '%u', 2) } )
    end
    return res
  when 'u-half'
    return str.gsub(all) { |s| Rex::Text.to_hex(Rex::Text.to_unicode(s, 'uhwtfms-half'), '%u', 2) }
  else
    raise TypeError, "invalid mode #{mode.inspect}"
  end
end