Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def caesarDecipher( cipherText = "" ):
- """ Caesar cipher is sometimes called a shift cipher. Decipher given ciphertext."""
- print( '>> ' + cipherText ) # DEBUG output
- ordA = ord('A') # ord() gets codepoint for Unicode char
- cipherText = cipherText.upper() # force UPPERCASE ascii
- # assume UPPERCASE or <space ' '>
- for k in range( 1, 26 ) :
- plainTxt = ''
- for token in cipherText :
- if token == ' ': # space chars pass thru ..
- plainChar = ' '
- else: # map char using shift ..
- plainOrd = ord( token ) - k
- if plainOrd < ordA : plainOrd += 26
- plainChar = chr( plainOrd )
- #
- plainTxt += plainChar # append each char to build 'plaintext'
- #
- # DEBUG: show result for each key in 1..25
- if k <= 9 :
- key = ' ' + str(k) # space pad for single digit .. pretty print !
- else:
- key = str(k)
- #
- outTxt = key +' '+ plainTxt
- print( outTxt )
- #
- #--------------------
- def caesarEncipher( plainText = "" ):
- """ Caesar cipher is sometimes called a shift cipher. Encipher given plaintext."""
- print( '>> ' + plainText ) # DEBUG output
- ordZ = ord('Z') # ord() gets codepoint for Unicode char
- plainText = plainText.upper() # force UPPERCASE ascii
- # assume UPPERCASE or <space ' '>
- for k in range( 1, 26 ) :
- cipherText = ''
- for token in plainText :
- if token == ' ': # space chars pass thru ..
- cypherChar = ' '
- else: # map char using shift ..
- cypherOrd = ord( token ) + k
- if cypherOrd > ordZ : cypherOrd -= 26
- cypherChar = chr( cypherOrd )
- #
- cipherText += cypherChar # append each char to build 'cyphertext'
- #
- # DEBUG: show result for each key in 1..25
- if k <= 9 :
- key = ' ' + str(k) # space pad for single digit .. pretty print !
- else:
- key = str(k)
- #
- outTxt = key +' '+ cipherText
- print( outTxt )
- #
- #-------------------------
- # TEST calls ..
- print( '\n*** DECIPHER ***\n' )
- caesarDecipher('PM FVB JHU NBLZZ AOL RLF PA PZ LHZF AV KLJYFWA AOL TLZZHNL')
- print( '\n*** ENCIPHER ***\n' )
- caesarEncipher('IF YOU CAN GUESS THE KEY IT IS EASY TO DECRYPT THE MESSAGE')
- print( '\n*** DECIPHER another ... ***\n' )
- caesarDecipher('WJYZWS YT WTRJ') # .. RETURN TO ROME
Add Comment
Please, Sign In to add comment