Skip to content

Instantly share code, notes, and snippets.

@johnwargo
Last active October 22, 2019 12:17
Show Gist options
  • Save johnwargo/7ee5fc5965a7e29554572d5ca059934f to your computer and use it in GitHub Desktop.
Save johnwargo/7ee5fc5965a7e29554572d5ca059934f to your computer and use it in GitHub Desktop.
Python Simple Substitution Cypher
#!/usr/bin/env python
in_str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ '
out_str = 'jklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghi'
def encrypt1(the_string):
the_result = ''
for x in the_string:
pos = in_str.find(x)
the_result += out_str[pos]
return the_result
def decrypt1(the_string):
the_result = ''
for x in the_string:
pos = out_str.find(x)
the_result += in_str[pos]
return the_result
def encrypt2(the_string):
the_result = ''
for x in the_string:
pos = in_str.find(x)
# have to deal with what happens if x isn't in in_str
if pos > -1:
the_result += out_str[pos]
return the_result
def decrypt2(the_string):
the_result = ''
for x in the_string:
pos = out_str.find(x)
# have to deal with what happens if x isn't in out_str
if pos > -1:
the_result += in_str[pos]
return the_result
def encrypt3(the_string):
the_result = ''
for x in the_string:
the_result += out_str[in_str.find(x)]
return the_result
def decrypt3(the_string):
the_result = ''
for x in the_string:
the_result += in_str[out_str.find(x)]
return the_result
def encrypt_decrypt(the_string, do_encrypt = True):
# this function encrypts and decrypts all in one place
the_result = ''
# only do this check once, no need to check every time
# you go through the loop - instead use two loops
if do_encrypt:
for x in the_string:
the_result += out_str[in_str.find(x)]
else:
for x in the_string:
the_result += in_str[out_str.find(x)]
return the_result
if __name__ == '__main__':
# Enctype the string
encrypted = encrypt3('some random string')
# print it to the console
print(encrypted)
# print the decrypted string to the console
print(decrypt3(encrypted))
encrypted = encrypt_decrypt('some random string')
# print it to the console
print(encrypted)
# print the decrypted string to the console
print(encrypt_decrypt(encrypted, False))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment