Skip to content

Instantly share code, notes, and snippets.

@codemaniac
Last active December 15, 2015 06:08
Show Gist options
  • Save codemaniac/5213709 to your computer and use it in GitHub Desktop.
Save codemaniac/5213709 to your computer and use it in GitHub Desktop.
substitution cypher with DSL
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import string
literals = string.printable
HOP_FORWARD = 1
HOP_BACKWARD = -1
def get_nth_replacement_literal(literal, n, hop_direction):
if hop_direction not in (HOP_FORWARD, HOP_BACKWARD): return None
start = literals.index(literal)
hops = n * hop_direction
return literals[(start + hops) % len(literals)]
def fibo_sub(text, hop_direction):
if hop_direction not in (HOP_FORWARD, HOP_BACKWARD): return None
x,y = 0,1
processed_text = []
for ch in text:
n = x+y
processed_text.append(get_nth_replacement_literal(ch, n, hop_direction))
x,y = y,n
return ''.join(processed_text)
def simple_sub(text, hops, hop_direction):
if hop_direction not in (HOP_FORWARD, HOP_BACKWARD): return None
processed_text = ''.join(get_nth_replacement_literal(ch, hops, hop_direction) for ch in text)
return processed_text
cypher = lambda s : fibo_sub(simple_sub(s, 5, HOP_FORWARD), HOP_FORWARD)
decypher = lambda s : simple_sub(fibo_sub(s, HOP_BACKWARD), 5, HOP_BACKWARD)
raw_text = '''Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'''
cyphered_text = cypher(raw_text)
decyphered_text = decypher(cyphered_text)
print decyphered_text == raw_text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment