File: hex.py

package info (click to toggle)
pwntools 4.15.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 18,508 kB
  • sloc: python: 59,870; ansic: 48,351; asm: 45,047; sh: 396; makefile: 256
file content (53 lines) | stat: -rw-r--r-- 1,389 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
from __future__ import absolute_import
from __future__ import division

import argparse
import sys

from pwnlib.commandline import common
from pwnlib.util.fiddling import enhex
from pwnlib.util.lists import group

parser = common.parser_commands.add_parser(
    'hex',
    help = 'Hex-encodes data provided on the command line or stdin',
    description = 'Hex-encodes data provided on the command line or stdin')

parser.add_argument('data', nargs='*',
    help='Data to convert into hex')

parser.add_argument(
    '-p', '--prefix',
    metavar = 'prefix',
    type = str,
    default = '',
    help = 'Insert a prefix before each byte',
)

parser.add_argument(
    '-s', '--separator',
    metavar = 'separator',
    type = str,
    default = '',
    help = 'Add a separator between each byte',
)

def format_hex(hex_string, prefix, separator):
    return separator.join([prefix + x for x in group(2, hex_string)])

def main(args):
    if not args.data:
        encoded = enhex(getattr(sys.stdin, 'buffer', sys.stdin).read())
    else:
        data = ' '.join(args.data)
        if not hasattr(data, 'decode'):
            data = data.encode('utf-8', 'surrogateescape')
        encoded = enhex(data)

    if args.prefix or args.separator:
        encoded = format_hex(encoded, args.prefix, args.separator)

    print(encoded)

if __name__ == '__main__':
    common.main(__file__, main)