-
-
Save ix4/d00da73577f2704c837924d2898e2e27 to your computer and use it in GitHub Desktop.
vigenere cipher
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
# encoding: utf8 | |
# vigenere cipher | |
# https://stackoverflow.com/a/2490718/1675586 | |
def encode(key, string): | |
encoded_chars = [] | |
for i in range(len(string)): | |
key_c = key[i % len(key)] | |
encoded_c = chr(ord(string[i]) + ord(key_c) % 256) | |
encoded_chars.append(encoded_c) | |
encoded_string = ''.join(encoded_chars) | |
return encoded_string | |
def decode(key, string): | |
encoded_chars = [] | |
for i in range(len(string)): | |
key_c = key[i % len(key)] | |
encoded_c = chr((ord(string[i]) - ord(key_c) + 256) % 256) | |
encoded_chars.append(encoded_c) | |
encoded_string = ''.join(encoded_chars) | |
return encoded_string | |
e = encode('a key', 'a message') | |
d = decode('a key', e) | |
print([e]) | |
print([d]) | |
# python 3 | |
# ['Â@ØÊìÔ\x81ÒÊ'] | |
# ['a message'] | |
# python 2 | |
# ['\xc2@\xd8\xca\xec\xd4\x81\xd2\xca'] | |
# ['a message'] | |
#-------------------------------------------------- | |
# this version makes it also base64: | |
import six, base64 | |
def encode(key, string): | |
encoded_chars = [] | |
for i in range(len(string)): | |
key_c = key[i % len(key)] | |
encoded_c = chr(ord(string[i]) + ord(key_c) % 256) | |
encoded_chars.append(encoded_c) | |
encoded_string = ''.join(encoded_chars) | |
encoded_string = encoded_string.encode('latin') if six.PY3 else encoded_string | |
return base64.urlsafe_b64encode(encoded_string).rstrip(b'=') | |
def decode(key, string): | |
string = base64.urlsafe_b64decode(string + b'===') | |
string = string.decode('latin') if six.PY3 else string | |
encoded_chars = [] | |
for i in range(len(string)): | |
key_c = key[i % len(key)] | |
encoded_c = chr((ord(string[i]) - ord(key_c) + 256) % 256) | |
encoded_chars.append(encoded_c) | |
encoded_string = ''.join(encoded_chars) | |
return encoded_string | |
e = encode('a key', 'a message') | |
d = decode('a key', e) | |
print([e]) | |
print([d]) | |
# python 3 | |
# [b'wkDYyuzUgdLK'] | |
# ['a message'] | |
# python 2 | |
# ['wkDYyuzUgdLK'] | |
# ['a message'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment