VIGENERE CIPHER
Vigenere Cipher
A Vigenere Cipher is a method of Encryption using polyalphabetic substitution. A series of interwoven Ceasar Ciphers. This can be accomplished using a Vigenere square or table.
*Featured Code Submitted and Created by
*Featured Code Submitted and Created by
VENOM666
# 365 DAYS OF CODE: DAY 1: VIGENERE CIPHER # by: VENOM666
Python
vigenereRank = lambda x: ord(x) - 97 #letters have value depending on their rank in the alphabet, e.g a = 0
vigenereAlpha = lambda x: chr(x + 97) #return the letter based on rank, e.g 1 = b def vigenere_encode(plainText, key): cipherText = '' if len(plainText) != len(key):
# length of key must be equal to the length of the plaintext
for i in range(len(plainText) - len(key)): key += key[i] for i in range(len(plainText)): pChar = plainText[i].lower() kChar = key[i].lower() cipherText += vigenereAlpha(((vigenereRank(pChar) + vigenereRank(kChar)) % 26))
# add the ranks from both plaintext and cipher text, addition must be done with modulo 26
print(cipherText.upper()) def vigenere_decode(cipher, key): decodedText = '' if len(cipher) != len(key):
# length of key must be equal to the length of the plaintext
for i in range(len(cipher) - len(key)): key += key[i] for i in range(len(cipher)): cChar = cipher[i].lower() kChar = key[i].lower() if vigenereRank(cChar) - vigenereRank(kChar) < 0:
#if negative, add 26 to return proper rank decodedText += vigenereAlpha((vigenereRank(cChar) - vigenereRank(kChar)) + 26) else: decodedText += vigenereAlpha(vigenereRank(cChar) - vigenereRank(kChar)) print(decodedText.upper()) vigenere_encode('DECODE', 'KEY') vigenere_decode('NIAYHC', 'KEY') vigenere_encode('SOLOLEARN', 'WEB') vigenere_decode('OSMKPFWVO', 'WEB')
Comments
Post a Comment