Skip to content

Instantly share code, notes, and snippets.

@sansyrox
Forked from gowhari/vigenere-cipher.py
Created February 7, 2021 01:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sansyrox/712ebc7f7d5c114b2bf5593b24a6d53a to your computer and use it in GitHub Desktop.
Save sansyrox/712ebc7f7d5c114b2bf5593b24a6d53a to your computer and use it in GitHub Desktop.
vigenere cipher
# 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