-1

I am trying to generate ascii to javascript unicode , and I could generate it , but after checking some aspects . I notice my program is eating the last part of the string. how can I fix this?

import binascii

content = 'string\n'

first_byte = ""
second_byte = ""
shellcode = ""
flag = 0
for b in content:
    if flag == 0:
        shellcode += "%u"
        first_byte = binascii.hexlify(b)
        flag += 1
    else:
        second_byte = binascii.hexlify(b)
        shellcode += second_byte
        shellcode += first_byte
        flag = 0

print shellcode

my output from the script

%u6c62%u6361%u6c6b%u6965%u7574%u

desired one, but in general whatever string

%u6c62%u6361%u6c6b%u6965%u7574%u0a73
wjandrea
  • 28,235
  • 9
  • 60
  • 81

2 Answers2

0

You are using the variable flag to split your input into two parts. The even characters are saved in first_byte, and when you get the odd character you save both into shellcode. At the end of the loop you have a character in first_byte that you haven't output yet, if the number of characters is even.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
0

See Mark's answer for the explanation of the problem. As for how to fix it, you could iterate over the string in two-byte chunks using one of the examples from here: How do you split a list into evenly sized chunks?

import binascii

content = 'string\n'

def chunks(sequence, n):
    """
    Yield successive n-sized chunks from the sequence.

    Modified from https://stackoverflow.com/a/312464/4518341
    """
    for i in xrange(0, len(sequence), n):
        yield sequence[i:i+n]

shellcode = ''
for t in chunks(content, 2):
    shellcode += "%u"
    if len(t) > 1:
        shellcode += binascii.hexlify(t[1])
    shellcode += binascii.hexlify(t[0])

print shellcode

Output:

%u7473%u6972%u676e%u0a
wjandrea
  • 28,235
  • 9
  • 60
  • 81