Monday, September 15, 2014

URL encoder / Percent-encoding Like '%75%72%6C %65%6E%63%6F%64%69%6E%67' with Python.

With some injection techniques, we need sometimes to encode some string to URL-Encoded string (Percent-encoding).

I've found a lot of resources that can encode/decode your text to URL encoding.
But.
All of them does not encoding ASCII characters, like 'A' or 'S' for example.

If you want to encode this: ['some text], you will get this: [%27some%20text].
And I want all that string to be encoded, including 'some' and 'text'.
Decided to make this in python.

What is %20? It is hexadecimal value of 'space'.
I will use method .encode('hex_codec').
>>> ' '.encode('hex_codec')
'20'

Append '%' to it's value, and woala, you've got URL encoded 'space' = %20

Here it is (just a function):
#recieve string >> return URL converted string
def encoder(strings):
   strings = strings.split(' ')
   lst = []
   for s in strings:
      b = ''
      for i in str(s):
         b = b+'%'+i.encode('hex_codec')
      lst.append(str(b))
   all_string = ' '.join(lst).upper()
   return all_string

It should get a string, and return encoded string. (by the way, it will not encode spaces, i don't need it)

If you want a full working and colored script with upper/lower character randomization: 
#!/usr/bin/env python
#__author: Korznikov Alexander, aka nopernik

import sys
from random import randint

#coloring
W = '\033[0m' # Text reset
G = '\033[32m' # green
R = '\033[31m' # red
B = '\033[34m' # blue

#recieve string >> return URL converted string
def encoder(strings):
   strings = strings.split(' ')
   lst = []
   for s in strings:
      b = ''
      for i in str(s):
         b = b+'%'+i.encode('hex_codec')
      lst.append(str(b))
   all_string = ' '.join(lst).upper()
   return all_string

def randomize(data):
   s = ''
   for i in data:
      if randint(1,10) % 2: 
         s += i.lower()
      else:
         s += i.upper()
   return s
   
def main(data):
   rnd_data = randomize(data)
   print '\n(Original Decoded): \'%s%s%s\'' % (B,data,W)
   print '(Original Encoded): \'%s%s%s\'' % (G,encoder(data),W)
   print '\nRandomized Decoded: \'%s%s%s\'' % (R,rnd_data,W)
   print 'Randomized Encoded: \'%s%s%s\'\n' % (G,encoder(rnd_data),W)
   
   
if __name__ == '__main__':
   print '\n'+'-'*37+'\n URL Encoder, by Korznikov Alexander\n'+'-'*37
   if len(sys.argv[1:]) >= 1:
      main(' '.join(sys.argv[1:]))
   else:
      main(raw_input('\nEnter text to encode: '))
   
Example output:
# url_encode.py got some text

-------------------------------------
 URL Encoder, by Korznikov Alexander
-------------------------------------

(Original Decoded): 'got some text'
(Original Encoded): '%67%6F%74 %73%6F%6D%65 %74%65%78%74'

Randomized Decoded: 'GOt SoMe text'
Randomized Encoded: '%47%4F%74 %53%6F%4D%65 %74%65%78%74'

That's all.

No comments:

Post a Comment