Skip to content

Instantly share code, notes, and snippets.

@aniline
Created July 6, 2019 16:36
Show Gist options
  • Save aniline/bae34f5db982ab9e92ea2ce840c28c2a to your computer and use it in GitHub Desktop.
Save aniline/bae34f5db982ab9e92ea2ce840c28c2a to your computer and use it in GitHub Desktop.
Tripwire style base64 encoding.
#!/usr/bin/env python3
#
# Tripwire style base64 encoding.
# It makes sense only for 4 byte aligned sequences and is slow.
# See: https://github.com/Tripwire/tripwire-open-source/blob/master/src/fco/signature.cpp#L201
#
# Example usage for MD5 sum of files as appearing in tripwire reports:
#
# md5sum * | python twb64.py
#
from struct import unpack
from binascii import unhexlify
from functools import reduce
import sys
twb64chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
def to_twb64(data):
bitseq_orig = reduce(lambda x,y: x+format(y, '032b'), unpack(f'!{int(len(data) / 4)}I', data), '')
offs = len(bitseq_orig) % 6
head = [int(bitseq_orig[:offs], 2)] if offs > 0 else []
tail_bits = bitseq_orig[offs:]
tail_6bit_list = [int(tail_bits[x:x+6],2) for x in range(0,len(tail_bits),6)]
return reduce(lambda x,y: x+y, [twb64chars[x] for x in head + tail_6bit_list], '')
if __name__ == '__main__':
for l in sys.stdin.read().splitlines():
(h, f) = l.split()
print(to_twb64(unhexlify(h)), f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment