Created
January 12, 2016 13:19
-
-
Save drslump/9b07eafb176ae7fe231f to your computer and use it in GitHub Desktop.
Converts binary data to an arbitrary alphabet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| Converts binary data to an arbitrary alphabet | |
| """ | |
| class AlphabetCodec(object): | |
| def __init__(self, alphabet): | |
| self._alphabet = alphabet | |
| self._base = len(self._alphabet) | |
| def encode(self, data): | |
| # convert the bytes string into a bigint | |
| bigint = int(data.encode('hex'), 16) | |
| if bigint == 0: | |
| return self._alphabet[0] | |
| result = [] | |
| while bigint > 0: | |
| mod = bigint % self._base | |
| bigint = bigint // self._base | |
| result.append(self._alphabet[mod]) | |
| # Order and convert to a bytes string | |
| result.reverse() | |
| return ''.join(result) | |
| def decode(self, encoded): | |
| num = 0 | |
| l = len(encoded) - 1 | |
| for i, ch in enumerate(encoded): | |
| factor = self._base ** (l - i) | |
| num += self._alphabet.index(ch) * factor | |
| # convert the bigint into a bytes string | |
| h = '%x' % num | |
| return ('0'*(len(h) % 2) + h).decode('hex') | |
| if __name__ == "__main__": | |
| import sys | |
| import base64 | |
| original = 'aE1lTm9KMWw1eVZEd3hVU0tiNTRiSWVpV0Y0ZlZVUFdGeTFVdw==' | |
| if len(sys.argv) > 1: | |
| original = sys.argv[1] | |
| codec = AlphabetCodec('23456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ') | |
| data = base64.b64decode(original) | |
| print 'ORIGINAL: %s' % data | |
| encoded = codec.encode(data) | |
| print ' ENCODED: %s' % encoded | |
| decoded = codec.decode(encoded) | |
| print ' DECODED: %s' % decoded | |
| b64 = base64.b64encode(decoded) | |
| print ' B64: %s' % b64 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment