How to convert this code from version 2 to 3.4 of Python?

2

I am having difficulty converting the code below to Python's 3.4 version, the purpose of this code is to encode and decode hexes in order to create shellcodes .

import binascii, sys, time

RED = '3[31m'
WHITE = '3[37m'
RESET = '3[0;0m'

def main():
    print("shellcode hex encode decoder")
    print("programmer : gunslinger_ <yudha.gunslinger[at]gmail.com>")
    print "what do you want to do ? %sencode%s / %sdecode%s" % (RED, RESET, WHITE, RESET)  
    q = raw_input("=> ")

    if q == "encode":
        inputtype = raw_input("Please input data : ")
        print "shellcode => ",
        for encoded in inputtype:
            print "\b\x"+encoded.encode("hex"),
            sys.stdout.flush()
            time.sleep(0.5)
            print RESET

    elif q == "decode":
        inputtype = raw_input("Please input data : ")
        cleaninput = inputtype.replace("\x","")
        print "hex       => ",cleaninput
        print "plaintext => ",
        print "\b"+cleaninput.decode("hex")

    else:
        print "wrong answer ! your choice is %sencode%s or %sdecode%s" % (RED, RESET, WHITE, RESET)
        sys.exit(1)

if __name__ == '__main__':
    main()

This part did not understand:

print "what do you want to do ? %sencode%s / %sdecode%s" % (RED, RESET, WHITE, RESET)  

Surely he defined the colors above, and %sencode%s / %sdecode%s how does this work? From what I understand it made a %s , at the beginning and end of the words encode and decode and call with the colors.

q = raw_input("=> ")

Has the variable and this => defined something specific in Python 2?

In this part below I understand some parts but not all if someone explains me better I am grateful.

inputtype = raw_input("Please input data : ")
print "shellcode => ",
for encoded in inputtype:
    print "\b\x"+encoded.encode("hex"),
    sys.stdout.flush()
    time.sleep(0.5)

Thank you guys.

    
asked by anonymous 03.04.2015 / 07:18

1 answer

4

There should be some code changes to work as expected in Python 3.

  • In versions prior to Python 3 print was an instruction ( statement ), starting with Python 3, it is considered a function , and so some syntax details have changed , such as the mandatory use of parentheses, () .

  • AsofPython3,thebuilt-infunctionwith% < strong> has been renamed to raw_input() .

  • InPython3itisnotnecessarytousethecommaattheendtosuppressanewline.

  • From Python 3.4 , methods that deal with encoding and decoding have been replaced by the functions of module input() .

    Python 3.4, Wrong Mode:

    b"hello".decode("hex")
    Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
     LookupError: 'hex' is not a text encoding; use codecs.decode() to handle arbitrary codecs
    

    Python 3.4, correct mode:

    >>> from codecs import encode, decode
    >>> encode(b"hello", "hex")
    b'68656c6c6f'
    >>> decode(b"68656c6c6f", "hex")
    b'hello'
    
  •   

    This part did not understand:

    print "what do you want to do ? %sencode%s / %sdecode%s" % (RED, RESET, WHITE, RESET)
    

    The four occurrences of codecs format will be replaced by %s , RED , RESET and WHITE values. The RESET will print:

    print "what do you want to do ? 3[31mencode3[0;0m / 3[37mdecode3[0;0m"
    

    This will print on screen words with a different color, other color combinations can be viewed here .

  •   

    q = raw_input ("= >") - > he defined the variable and this = > serial something specific in python 2

    The print is the text that will be displayed and will receive the user input.

  •   

    In this part below I understand some parts but not all if someone explains me better I am grateful.

    inputtype = raw_input("Please input data : ") # Recebe a entrada do usuário
    print "shellcode => ",                        # Imprime "shellcode =>" e elimina a nova linha
    for encoded in inputtype:                     # Percorre cada letra da variável "inputtype"
        print "\b\x"+encoded.encode("hex"),
        sys.stdout.flush()                        # Imprime diretamente na saída padrão "stdout"
        time.sleep(0.5)                           # Espera 30s
    

The converted code for Python 3 should look like this:

import sys, time, binascii
# -*- coding: utf-8 -*-

RED = '3[31m'
WHITE = '3[37m'
RESET = '3[0;0m'

def main():
    print("shellcode hex encode decoder")
    print("programmer : gunslinger_ <yudha.gunslinger[at]gmail.com>")
    print("what do you want to do ? {0}encode{1} / {2}decode{3}".format(RED, RESET, WHITE, RESET))
    q = input("=> ")

    if q == "encode":
        inputtype = input("Please input data : ")
        print ("shellcode => ")
        for encoded in inputtype:
            print ("\x{0}".format(binascii.hexlify(bytes(encoded, 'utf-8')).decode()))
            sys.stdout.flush()
            time.sleep(0.5)
            print (RESET)

    elif q == "decode":
        inputtype = input("Please input data : ")
        cleaninput = inputtype.replace("\x","")
        print ("hex       => {0}".format(inputtype))
        print ("plaintext => {0}".format(binascii.unhexlify(cleaninput).decode('utf-8')))
    else:
        print ("wrong answer ! your choice is %sencode%s or %sdecode%s" % (RED, RESET, WHITE, RESET))
        sys.exit(1)

if __name__ == '__main__':
    main()

A cleaner version with some modifications:

# -*- coding: utf-8 -*-
import sys, binascii

cor = {'vermelho': '3[1;31m', 'branco': '3[1;34m', 'sem_cor': '3[0;0m'}

def shellcode(opcao, texto):
    resultado = ""
    if opcao == 'e':
        resultado += ''.join("\x{0}".format(binascii.hexlify(bytes(s, 'utf-8')).decode()) for s in texto)
    elif opcao == 'd':
        texto = texto.replace('\x', '')
        resultado = binascii.unhexlify(texto).decode()
    return resultado

def main():
    opcoes = "{0}encode{1} / {2}decode{3} ou sair".format(cor['vermelho'], cor['sem_cor'], cor['branco'], cor['sem_cor'])
    print("O que quer fazer? {0}".format(opcoes))
    while True:
        try:
            questao = input("Opcao: ").lower()
            dados = input("Dados: ")
            codigo = ""

            if questao in ['encode', 'enc', 'e']:
                codigo = shellcode('e', dados)
            elif questao in ['decode', 'dec', 'd']:
                codigo = shellcode('d', dados)
            elif questao in ['sair', 's']:
                sys.exit()
            else:
                sys.exit("Opcao inválida! Opcoes: {0}".format(opcoes))

            print("{0}: {1}".format(questao, codigo))
        except KeyboardInterrupt:
            sys.exit()

if __name__ == '__main__':
    main()
    
04.04.2015 / 06:05