crypt.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # Purpose: decode/encode DXF proprietary data
  2. # Created: 01.05.2014
  3. # Copyright (c) 2014-2018, Manfred Moitzi
  4. # License: MIT License
  5. from typing import Iterable
  6. _decode_table = {
  7. 0x20: ' ',
  8. 0x40: '_',
  9. 0x5F: '@',
  10. }
  11. for c in range(0x41, 0x5F):
  12. _decode_table[c] = chr(0x41 + (0x5E - c)) # 0x5E -> 'A', 0x5D->'B', ...
  13. def decode(text_lines: Iterable[str]) -> Iterable[str]:
  14. def _decode(text):
  15. dectab = _decode_table # fast local var
  16. s = []
  17. text = bytes(text, 'ascii')
  18. skip = False
  19. for c in text:
  20. if skip:
  21. skip = False
  22. continue
  23. if c in dectab:
  24. s += dectab[c]
  25. skip = (c == 0x5E) # skip space after 'A'
  26. else:
  27. s += chr(c ^ 0x5F)
  28. return ''.join(s)
  29. return (_decode(line) for line in text_lines)
  30. _encode_table = {
  31. ' ': ' ', # 0x20
  32. '_': '@', # 0x40
  33. '@': '_', # 0x5F
  34. }
  35. for c in range(0x41, 0x5F):
  36. _encode_table[chr(c)] = chr(0x5E - (c - 0x41)) # 0x5E->'A', 'B'->0x5D, ...
  37. def encode(text_lines: Iterable[str]) -> Iterable[str]:
  38. def _encode(text):
  39. s = []
  40. enctab = _encode_table # fast local var
  41. for c in text:
  42. if c in enctab:
  43. s += enctab[c]
  44. if c == 'A':
  45. s += ' ' # append a space for an 'A' -> cryptography
  46. else:
  47. s += chr(ord(c) ^ 0x5F)
  48. return ''.join(s)
  49. return (_encode(line) for line in text_lines)