Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # implement Vigenere cipher.
- # or : pip install pycipher .. from pycipher import Vigenere .. Vigenere('SECRETKEY').encipher('defend at all costs')
- ordA = ord('A') # 65 ( or x41 ) ASCII / Unicode codepoint
- #-- -----------------
- def getVigenereSquare():
- """ build a Vigenere Square. Return a "list of lists" mapped to a tuple of Strings """
- vSquare = []
- for row in range( 26 ):
- # add row of letters as a String ..
- thisRow = []
- for col in range( 26 ):
- #
- # (col + row) % 26
- charOffset = col + row # in 0..50
- if charOffset >= 26 : charOffset -= 26 # now in 0..25 ie. < 26
- #
- thisRow.append( chr( ordA + charOffset ) ) # set char value in 'cell'
- #
- # vSquare.append( tuple( thisRow ) ) # read-only .. or ..
- vSquare.append( "".join( thisRow ) ) # read-only String
- #
- return tuple( vSquare ) # read-only seq of Strings
- #------------------------
- #==========================
- vSquare = getVigenereSquare() # use as a GLOBAL. read-only
- #==========================
- #DEBUG: show SQUARE ..
- for row in range( 26 ): print( vSquare[row] )
- print('>')
- #-- ------------------
- def getIndexListForKey( key ):
- """ sanitise the key, then map to list of indexes """
- key = key.upper()
- keyIter = filter( filterUPPER, key ) # strip out all non-UPPER
- #
- #keyIndices = []
- #for c in keyIter: # pull each char from filter iterator ..
- # keyIndices.append( ord( c ) - ordA ) # map 'A'..'Z' --> 0..25
- #
- # demo .. instead use a list comprehension
- keyIndices = [ ord( c ) - ordA for c in keyIter ] # map 'A'..'Z' --> 0..25
- return tuple( keyIndices ) # read-only
- #---------------------------
- def filterUPPER( s="" ): # utility
- """ filter function UPPERCASE only """
- return s.isupper()
- #-------------------
- #-- ===============
- def encryptVigenere( key="", plainTxt="" ):
- """ encrypt Vigenere """
- # vSquare = getVigenereSquare() # now made Global
- keyIndices = getIndexListForKey( key )
- print('\nKey:', key, ':> produced indices:', keyIndices ) # DEBUG .. REMOVE !!!
- keyIndexLimit = len( keyIndices )
- keyIndex = 0
- if keyIndexLimit == 0 or len(plainTxt) == 0 : return "" # empty !?!
- # build list of chars using append
- cipherChars = []
- for thisToken in plainTxt :
- if thisToken.isalpha() :
- #
- tokenUPPER = thisToken.upper()
- #
- thisRow = vSquare[ ord( tokenUPPER ) - ordA ]
- thisChar = thisRow[ keyIndices[ keyIndex ] ]
- #
- keyIndex += 1
- if keyIndex >= keyIndexLimit : keyIndex = 0 # wrap
- #
- else:
- thisChar = thisToken # pass through
- #
- cipherChars.append( thisChar )
- #
- cipherTxt = "".join( cipherChars )
- print( plainTxt ) # DEBUG .. REMOVE !!!
- return cipherTxt
- # ------ ---------
- def decryptVigenere( key="", cipherTxt="" ):
- """ decrypt Vigenere """
- # vSquare = getVigenereSquare() # now made Global
- keyIndices = getIndexListForKey( key )
- print('\nKey:', key, ':> produced indices:', keyIndices ) # DEBUG .. REMOVE !!!
- keyIndexLimit = len( keyIndices )
- if keyIndexLimit == 0 or len(cipherTxt) == 0 : return "" # empty !?!
- # build list of chars using append
- keyIndex = 0
- plainChars = []
- for thisToken in cipherTxt :
- if thisToken.isalpha():
- #
- thisRow = vSquare[ keyIndices[ keyIndex ] ]
- keyIndex += 1
- if keyIndex >= keyIndexLimit : keyIndex = 0 # wrap
- #
- searchChar = thisToken.upper()
- #
- colIndex = thisRow.index( searchChar )
- thisChar = chr( ordA + colIndex )
- else:
- thisChar = thisToken # pass through
- #
- plainChars.append( thisChar )
- #
- plainTxt = "".join( plainChars )
- print( cipherTxt ) # DEBUG .. REMOVE !!!
- return plainTxt
- # ------ --------
- #----------- **************************************************************************************************
- # TEST calls ..
- print("\n... DECRYPTING ...")
- result = decryptVigenere('polyalphabetic','Lvlr yppy wbw mpg Kwrcnpgl cjtamt uwyylwn jrbgdmf, tbognr xa’s sibop pg efe fcirfedidas ngpsty?')
- print( result )
- #
- result = decryptVigenere('RPI','z pu vckinxkxvx p uvharvm')
- print( result )
- #
- result = decryptVigenere('R','z rd vetipgkzex r dvjjrxv')
- print( result )
- # RPI hello
- result = decryptVigenere('RPI','yttcd')
- print( result )
- #
- result = decryptVigenere('polyalphabetic','xh hys nghcliw qp twrftptu fjjmg hdic')
- print( result )
- print("\n... ENCRYPTING ...")
- # RPI hello yttcd
- result = encryptVigenere('RPI','hello')
- print( result )
- #
- result = encryptVigenere('RPI','I am encrypting a message')
- print( result )
- #
- result = encryptVigenere('polyalphabetic','I am encrypting a message')
- print( result )
- #
- result = encryptVigenere('a key with spaces and digits 123', 'Non alpha chars are filtered out from key phrase')
- print( result )
- #
- print("\n... DECRYPTING AGAIN...")
- result = decryptVigenere('a key with spaces and digits 123','NYR YHXAH UWATW SRR ILTZMKWD YYR BZHT CTY RLJAFH')
- print( result )
- #
- result = decryptVigenere('polyalphabetic','xb pggsileo jbnvn tzsr ti dat gkiezso')
- print( result )
- #
Add Comment
Please, Sign In to add comment