Skip to content

Instantly share code, notes, and snippets.

@ph1ee
Last active September 19, 2018 03:25
Show Gist options
  • Select an option

  • Save ph1ee/b2de70f261ce7f4d99b7bd04f22b47bd to your computer and use it in GitHub Desktop.

Select an option

Save ph1ee/b2de70f261ce7f4d99b7bd04f22b47bd to your computer and use it in GitHub Desktop.
Simple utility to decode base16-encoded strings
#!/usr/bin/env python
from __future__ import print_function
import sys
import argparse
import fileinput
import base64
def main():
parser = argparse.ArgumentParser('Decode base16-encoded strings.')
parser.add_argument('-n', dest='newline', action='store_false', help='do not output the trailing newline')
parser.add_argument('-e', dest='decode', action='store_false', help='encode strings using base16')
parser.add_argument('files', metavar='FILE', nargs='*', help='files to read, if empty, stdin is used')
args = parser.parse_args()
for line in fileinput.input(files=args.files if len(args.files) > 0 else ('-', )):
try:
if args.decode:
hexstr = line.strip().upper()
print(base64.b16decode(hexstr), "\n" if args.newline else "", sep="", end="")
else:
print(base64.b16encode(line), "\n" if args.newline else "", sep="", end="")
except TypeError as e:
print >> sys.stderr, '%s%s' % (e, "\n" if args.newline else ""),
if __name__ == '__main__':
main()
#!/usr/bin/env python
from __future__ import print_function
import sys
import os
import base64
import string
import timeit
def info(type, value, tb):
if hasattr(sys, 'ps1') or not sys.stderr.isatty() or type != AssertionError:
# we are in interactive mode or we don't have a tty-like
# device, so we call the default hook
sys.__excepthook__(type, value, tb)
else:
import traceback
try:
import ipdb as pdb
except ImportError:
import pdb
# we are NOT in interactive mode, print the exception...
traceback.print_exception(type, value, tb)
print
# ...then start the debugger in post-mortem mode.
pdb.pm()
sys.excepthook = info
MAXSIZE = 1500
def b16(binary):
encoded = base64.b16encode(binary[:])
assert binary == base64.b16decode(encoded)
return encoded
def b32(binary):
encoded = base64.b32encode(binary[:])
assert binary == base64.b32decode(encoded)
return encoded
def bxx(binary):
allow = bytearray('ghijklmnopqrstuvwxyzGHIJKLMNOPQRSTUVWXYZ')
encoded = bytearray()
for b in binary:
if b in allow:
encoded.append(b)
else:
encoded.extend('{:02X}'.format(b))
decoded = bytearray()
i = 0
while i < len(encoded):
if encoded[i] in allow:
decoded.append(encoded[i])
i += 1
else:
decoded.extend(bytearray.fromhex(str(encoded[i:i + 2])))
i += 2
assert binary == decoded
return encoded
def run(codec):
for i in range(1, MAXSIZE + 1):
binary = bytearray(os.urandom(i))
encoded = codec(binary)
print("{:d},{:d},{:d},{:.2f}".format(i, len(binary), len(encoded), len(encoded) / float(len(binary))))
if __name__ == '__main__':
print(timeit.timeit(lambda: run(b16), number=2), file=sys.stderr)
print(timeit.timeit(lambda: run(b32), number=2), file=sys.stderr)
print(timeit.timeit(lambda: run(bxx), number=2), file=sys.stderr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment