Skip to content

Instantly share code, notes, and snippets.

@joshbode
Created October 4, 2013 07:15
Show Gist options
  • Select an option

  • Save joshbode/6822121 to your computer and use it in GitHub Desktop.

Select an option

Save joshbode/6822121 to your computer and use it in GitHub Desktop.
Mixo-Fixo: Typo and casual reverse-engineering tolerant inefficient string-token encoding method. Features: - changing a single character in the input changes many characters in the output - valid token-space is very sparse
"""
Mixo-Fixo: Typo and casual reverse-eingineering tolerant, inefficient string-token encoding method.
"""
def chunks(l, n):
""" Yield successive n-sized chunks from l."""
for i in xrange(0, len(l), n):
yield l[i:i+n]
def mixo(s):
if s == '':
return s
s = [ord(x) for x in s]
result = []
offset_x = offset_y = 0
for x, y in zip(s, reversed(s)):
offset_x += x
offset_y += y
result.append((offset_x % 256, offset_y % 256))
# offset everythng with the final offsets
result[:-1] = [((x + offset_x) % 256, (y + offset_y) % 256) for x, y in result[:-1]]
return ''.join(chr(x) + chr(y) for x, y in result)
def fixo(s):
if s == '':
return s
if len(s) % 2 != 0:
raise ValueError("Invalid input.")
s = [(ord(x), ord(y)) for x, y in chunks(s, 2)]
result = []
offset_x, offset_y = [-p for p in s[-1]]
s[-1] = tuple((2 * p) % 256 for p in s[-1])
for x, y in s:
x += offset_x
y += offset_y
result.append((x % 256, y % 256))
offset_x -= x
offset_y -= y
a, b = [''.join(chr(p) for p in t) for t in zip(*result)]
if a == b[::-1]:
return a
else:
raise ValueError("Invalid checksum.")
import base64
s = '023.45|034.50|254'
t = base64.encodestring(mixo(s)).strip()
u = fixo(base64.decodestring(t))
s == u
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment