-
Notifications
You must be signed in to change notification settings - Fork 4
/
hexlify
executable file
·167 lines (131 loc) · 4.61 KB
/
hexlify
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
#! /usr/bin/env python
#
# Hexlify stdin and write to stdout
#
# Author: Sudhi Herle <sw-at-herle-dot-net>
#
# License: GPLv2
#
import os, sys, base64, argparse
from os.path import basename, dirname, abspath, normpath, join
from binascii import hexlify
from functools import partial
Z = basename(sys.argv[0])
def main():
usage = """%(Z)s - Flexible hex|base64 data dumper """ % { 'Z': Z }
pp = argparse.ArgumentParser(description=usage)
pp.add_argument('-L', '--line-length', dest="linelen", default=0,
type=int, metavar="N",
help="Break output line into 'N' character chunks [%(default)s]")
pp.add_argument('-n', '--Nbytes', dest="N", default=0,
type=int, metavar="N",
help="Only read N bytes of input data (0 implies until EOF) [%(default)s]")
pp.add_argument("-o", "--outfile", dest="outfile", default=None,
metavar="F", type=str,
help="write output to file F [STDOUT]")
g = pp.add_mutually_exclusive_group()
g.add_argument('-b', '--base64', dest='b64', action="store_true", default=False,
help="Base64 decode the input first [%(default)s]")
g.add_argument('-d', '--dump', dest='dump', action="store_true", default=False,
help="Show a hexdump style output [%(default)s]")
g.add_argument('-c', '--c-type', dest="ctype", action="store_true", default=False,
help="Generate a C like array definition [%(default)s]")
pp.add_argument("infile", nargs="*", type=str, help="zero or more input files")
args = pp.parse_args()
out = sys.stdout
if args.outfile:
out = open(args.outfile, 'w')
barehex = partial(hexlate, N=args.N, L=args.linelen, hexer=hexlify, pref='', suff='\n', lf="\n")
chex = partial(hexlate, N=args.N, L=args.linelen, hexer=chexlify, pref="{\n", suff="}\n", lf=",\n")
dumper = partial(dumpify, N=args.N, L=args.linelen)
if args.ctype:
hexify = chex
elif args.dump:
hexify = dumper
else:
hexify = barehex
if len(args.infile) > 0:
for fd, fn in argv2fd(args.infile):
hexify(fd, out, args.b64)
else:
hexify(sys.stdin, out, args.b64)
def argv2fd(argv):
"""Generator that yields open fd's from names in argv"""
if len(argv) == 0:
return
for fn in argv:
fd = open(fn, 'rb')
yield fd, fn
fd.close()
def chexlify(b):
"""like binascii.hexlify() except writes C like bytes"""
return ', '.join(["%#2.2x" % ord(x) for x in b])
def dumpify(infd, outfd, ign, N, L):
"""Call hexdump.."""
if L == 0: L = 16
if N > 0:
b = infd.read(N)
if not b:
return
x = hexdump(b, stride=L)
outfd.write(x)
else:
while True:
b = infd.read(65536)
if not b: break
x = hexdump(b, stride=L)
outfd.write(x)
outfd.write('\n')
def hexlate(infd, outfd, b64, N, L, hexer, pref, suff, lf):
"""Transcribe bytes from 'infd' to 'outfd' in hex. Breakup lines
into 'L' bytes. If 'N' is specified, read exactly 'N' bytes from
'infd', else read until EOF.
"""
outfd.write(pref)
# We provide one of two definitions for the closure pp()
if L < 2:
def pp(b):
outfd.write(hexer(b))
else:
l = L / 2
def pp(b):
z = len(b)
while z > 0:
r = l if z > l else z
c = b[:r]
b = b[r:]
z -= r
outfd.write(hexer(c)+lf)
inxform = base64.b64decode if b64 else lambda x: x
if N > 0:
b = infd.read(N)
if b: pp(inxform(b))
else:
while True:
b = infd.read(65536)
if not b: break
pp(inxform(b))
outfd.write(suff)
def hexdump(src, stride=16, sep='.'):
chrtab = [(len(repr(chr(x))) == 3) and chr(x) or sep for x in range(256)]
lines = []
for c in xrange(0, len(src), stride):
chars = src[c:c+stride]
hexb = ' '.join(["%02x" % ord(x) for x in chars])
if len(hexb) > 24:
hexb = "%s %s" % (hexb[:24], hexb[24:])
pr = ''.join(["%s" % chrtab[ord(x)] for x in chars])
lines.append("%08x: %-*s |%s|" % (c, stride*3, hexb, pr))
return '\n'.join(lines)
def die(fmt, *args):
warn(fmt, args)
exit(1)
def warn(fmt, *args):
sfmt = "%s: %s" % (Z, fmt)
if args: sfmt = sfmt % args
if not sfmt.endswith('\n'): sfmt += '\n'
sys.stdout.flush()
sys.stderr.write(sfmt)
sys.stderr.flush()
main()
# EOF