Skip to content

Instantly share code, notes, and snippets.

@gowhari
Created May 23, 2018 10:24
Show Gist options
  • Save gowhari/fea9c559f08a310e5cfd62978bc86a1a to your computer and use it in GitHub Desktop.
Save gowhari/fea9c559f08a310e5cfd62978bc86a1a 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']
@alex-pancho
Copy link

alex-pancho commented May 27, 2018

def forcode(key, string, act='d'):
    encoded_chars = []
    for i in range(len(string)):
        key_c = key[i % len(key)]
        if act!='d':
            encoded_c = chr(ord(string[i]) + ord(key_c) % 256)
        else:
            encoded_c = chr((ord(string[i]) - ord(key_c) + 256) % 256)
        encoded_chars.append(encoded_c)
    encoded_string = ''.join(encoded_chars)
    return encoded_string

@alex-pancho
Copy link

e = forcode('a key', 'a message')
d = forcode('a key', e, '')

@SharronQinCOB
Copy link

Thank you, Iman and Alex! This is exactly what I needed.

@jchan0087
Copy link

Thanks alex!!! This helped greatly!!!

@liomoti
Copy link

liomoti commented Nov 21, 2019

thanks!

@ademidun
Copy link

Hey @alex-pancho , can you please explain what you did?

@alex-pancho
Copy link

alex-pancho commented Dec 31, 2019

@ademidun

Hey @alex-pancho , can you please explain what you did?

I wrote this answer a long time ago. There seems to be a question whether it is possible to cut everything into one function. Indeed, if you look closely at the code, you will notice that the difference is only one line.
But now, I would have done the code a little differently:

def forcode(key, string, act='e'):
    '''vigenere cipher function, use (key,text) for encoding and (key,text, 'd') for decoding'''
    
    encoded_chars = []
    for i in range(len(string)):
        key_c = key[i % len(key)]
        if act=='e':
            encoded_c = chr(ord(string[i]) + ord(key_c) % 256)
        else:
            encoded_c = chr((ord(string[i]) - ord(key_c) + 256) % 256)
        encoded_chars.append(encoded_c)
    encoded_string = ''.join(encoded_chars)
    return encoded_string

useex:
e = forcode('a key', 'a message')
d = forcode('a key', e,'d')
print(e)
print(d)

@Sunda001
Copy link

nice

@zackmark29
Copy link

zackmark29 commented Aug 13, 2021

For base64 version

import six
import base64


def enc_or_dec(key: str, string: str, dec: bool = False) -> str:
    encoded_chars = []
    if dec:
        string = base64.urlsafe_b64decode(string + b'===')
        string = string.decode('latin') if six.PY3 else string

    for i in range(len(string)):
        key_c = key[i % len(key)]
        if dec:
            encoded_c = chr((ord(string[i]) - ord(key_c) + 256) % 256)

        encoded_c = chr(ord(string[i]) + ord(key_c) % 256)
        encoded_chars.append(encoded_c)

    encoded_string = ''.join(encoded_chars)
    if dec:
        return encoded_string
    encoded_string = encoded_string.encode('latin') if six.PY3 else encoded_string
    return base64.urlsafe_b64encode(encoded_string).rstrip(b'=')

Usage:

key = 'zm'
msg  = 'test'

encoded = enc_or_dec(key, msg)
print(encoded)
decoded = enc_or_dec(key, encoded, True)
print(decoded)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment