z85.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. """Python implementation of Z85 85-bit encoding
  2. Z85 encoding is a plaintext encoding for a bytestring interpreted as 32bit integers.
  3. Since the chunks are 32bit, a bytestring must be a multiple of 4 bytes.
  4. See ZMQ RFC 32 for details.
  5. """
  6. # Copyright (C) PyZMQ Developers
  7. # Distributed under the terms of the Modified BSD License.
  8. import sys
  9. import struct
  10. PY3 = sys.version_info[0] >= 3
  11. # Z85CHARS is the base 85 symbol table
  12. Z85CHARS = b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-:+=^!/*?&<>()[]{}@%$#"
  13. # Z85MAP maps integers in [0,84] to the appropriate character in Z85CHARS
  14. Z85MAP = dict([(c, idx) for idx, c in enumerate(Z85CHARS)])
  15. _85s = [ 85**i for i in range(5) ][::-1]
  16. def encode(rawbytes):
  17. """encode raw bytes into Z85"""
  18. # Accepts only byte arrays bounded to 4 bytes
  19. if len(rawbytes) % 4:
  20. raise ValueError("length must be multiple of 4, not %i" % len(rawbytes))
  21. nvalues = len(rawbytes) / 4
  22. values = struct.unpack('>%dI' % nvalues, rawbytes)
  23. encoded = []
  24. for v in values:
  25. for offset in _85s:
  26. encoded.append(Z85CHARS[(v // offset) % 85])
  27. # In Python 3, encoded is a list of integers (obviously?!)
  28. if PY3:
  29. return bytes(encoded)
  30. else:
  31. return b''.join(encoded)
  32. def decode(z85bytes):
  33. """decode Z85 bytes to raw bytes, accepts ASCII string"""
  34. if PY3 and isinstance(z85bytes, str):
  35. try:
  36. z85bytes = z85bytes.encode('ascii')
  37. except UnicodeEncodeError:
  38. raise ValueError('string argument should contain only ASCII characters')
  39. if len(z85bytes) % 5:
  40. raise ValueError("Z85 length must be multiple of 5, not %i" % len(z85bytes))
  41. nvalues = len(z85bytes) / 5
  42. values = []
  43. for i in range(0, len(z85bytes), 5):
  44. value = 0
  45. for j, offset in enumerate(_85s):
  46. value += Z85MAP[z85bytes[i+j]] * offset
  47. values.append(value)
  48. return struct.pack('>%dI' % nvalues, *values)