Created
May 23, 2018 10:24
-
-
Save gowhari/fea9c559f08a310e5cfd62978bc86a1a to your computer and use it in GitHub Desktop.
Revisions
-
gowhari created this gist
May 23, 2018 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,75 @@ # 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']