Last active
August 29, 2015 14:22
-
-
Save damzam/29506f10ead83d477570 to your computer and use it in GitHub Desktop.
Encrypt a lowercase string into another lowercase string with no spaces
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
#!/usr/bin/env python | |
""" | |
encrypt and descript lowercase strings without using | |
but lowercase strings | |
""" | |
from string import lowercase | |
from random import choice | |
MAX_GARBAGE_LENGTH = 5 | |
def encrypt(string): | |
offset = len(string) % 26 | |
chars = [] | |
# Get an offset based on the string length | |
for char in string: | |
modified = ord(char) - offset | |
if modified < 97: | |
modified += 26 | |
# Then get the inverse of the character set | |
modified = 97 * 2 - modified | |
if modified < 97: | |
modified += 26 | |
chars.append(chr(modified)) | |
# Reverse the string to make things worse | |
chars.reverse() | |
shifted_and_inverted = ''.join(chars) | |
# Throw in garbage so that no sane person could | |
# deduce what's going on | |
messy = [] | |
for char in shifted_and_inverted: | |
garbage_header = choice(lowercase) | |
messy.append(garbage_header) | |
for _ in range(ord(garbage_header) % MAX_GARBAGE_LENGTH): | |
messy.append(choice(lowercase)) | |
messy.append(char) | |
return ''.join(messy) | |
def decrypt(string): | |
# Remove the garbage | |
good_chars = [] | |
next_bad_char = 0 | |
next_good_char = 0 | |
for i, char in enumerate(string): | |
if next_bad_char == i: | |
bad_chars = ord(char) % MAX_GARBAGE_LENGTH | |
next_good_char = i + 1 + bad_chars | |
next_bad_char = i + 2 + bad_chars | |
if next_good_char == i: | |
good_chars.append(char) | |
# Reverse the chars | |
good_chars.reverse() | |
# Now invert | |
chars = [] | |
for char in good_chars: | |
inverted = 97 * 2 - ord(char) | |
if inverted < 97: | |
inverted += 26 | |
chars.append(chr(inverted)) | |
# Now correct for the offset | |
offset = len(chars) % 26 | |
for i, char in enumerate(chars): | |
modified = ord(char) + offset | |
if modified > 122: | |
modified -= 26 | |
chars[i] = chr(modified) | |
return ''.join(chars) | |
def main(): | |
# text = 'davidmortonisonecrazyprogrammingfiend' | |
text = lowercase | |
encrypted = encrypt(text) | |
print text | |
print encrypted | |
print decrypt(encrypted) | |
print len(text) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment