11class VigenereCipher :
22 def __init__ (self ) -> None :
3- pass
3+ """This is a python implementation of Vigenere Cipher"""
4+
5+ def modify_key (self , msg : str , key : str ) -> str :
6+ '''Generates the key in a cyclic manner until it's length equal to the
7+ length of text'''
48
5- @staticmethod
6- def encrypt (msg : str , key : str ) -> str :
7- msg , key = msg .upper (), key .upper ()
89 if len (msg ) > len (key ):
9- # Generates the key in a cyclic manner until it's length equal to the length of text
1010 for i in range (len (msg ) - len (key )):
1111 key += key [i % len (key )]
12+
13+ return key
14+
15+ def encrypt (self , msg : str , key : str ) -> str :
16+ msg , key = msg .upper (), key .upper ()
17+ key = self .modify_key (msg , key )
18+
1219 encrypted_words = []
1320 curr_key_index = 0
1421 for text in msg .split ():
1522 result = ''
1623 for i in range (len (text )):
1724 x = (ord (text [i ]) + ord (key [curr_key_index ])) % 26
1825 x += ord ('A' )
19- result += chr (x )
20- curr_key_index += 1
26+ result += chr (x )
27+ curr_key_index += 1
2128 encrypted_words .append (result )
29+
2230 return ' ' .join (encrypted_words ).lower ()
2331
24- @staticmethod
25- def decrypt (msg : str ,key : str ) -> str :
26- msg , key = msg .upper (), key .upper ()
27- if len (msg ) > len (key ):
28- # Generates the key in a cyclic manner until it's length equal to the length of msg
29- for i in range (len (msg ) - len (key )):
30- key += key [i % len (key )]
32+ def decrypt (self , msg : str , key : str ) -> str :
33+ msg , key = msg .upper (), key .upper ()
34+ key = self .modify_key (msg , key )
35+
3136 decrypted_words = []
3237 curr_key_index = 0
3338 for word in msg .split ():
34- result = ''
39+ result = ''
3540 for i in range (len (word )):
3641 x = (ord (word [i ]) - ord (key [curr_key_index ]) + 26 ) % 26
3742 x += ord ('A' )
3843 result += chr (x )
39- curr_key_index += 1
44+ curr_key_index += 1
4045 decrypted_words .append (result )
41- return ' ' .join (decrypted_words ).lower ()
46+
47+ return ' ' .join (decrypted_words ).lower ()
0 commit comments