Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """JD cipher module"""
- #-- -----------
- def getAlphabet( shift = 0 ):
- """Return: eg. (shift == 1) -> 'BCDEFGHIJKLMNOPQRSTUVWXYZA' """
- ordA = ord('A') # ord() gets codepoint for Unicode char
- if ( isinstance( shift, int )) : # int, so shift ..
- if ( shift < 0 ): shift = 0 # .. guard
- # build letter sequence as a String ..
- return "".join([ chr( ordA + ( i + shift ) % 26 ) for i in range( 26 )])
- #
- return ""
- #
- #-- -----------------
- def getVigenereSquare():
- """ build a Vigenere Square. Return a "list of strings" mapped to a tuple of Strings """
- #
- return tuple( [ getAlphabet(s) for s in range( 26 ) ]) # read-only: seq of 26 Strings
- #----------------
- #==========================
- vSquare = getVigenereSquare() # use as a GLOBAL. read-only
- #==========================
- #DEBUG: show SQUARE ..
- print('\n"Vigenère square" follows ...\n')
- for row in range( 26 ): print( vSquare[row] )
- print('>')
- #-- ---------
- def encCaesar( key = 0, plainText = "" ):
- """ Caesar cipher is sometimes called a shift cipher. Encipher given plaintext."""
- #
- thisAlphabet = vSquare[key] # OR getAlphabet( key )
- return encMonoSub( thisAlphabet, plainText ) # use the monoalphabetic substitution cipher
- #
- #-- ---------
- def decCaesar( key = 0, cipherText = "" ):
- """ Caesar cipher is sometimes called a shift cipher. Decipher given ciphertext."""
- #
- standardAlphabet = vSquare[0] # OR getAlphabet(0)
- # I discovered that DECRYPTING the "standard alphabet" with ..
- # .. a 'mono alphabet' yields the "reciprocal (inverse decrypt) alphabet"
- thisAlphabet = decMonoSub( vSquare[key], standardAlphabet ) # OR getAlphabet( key )
- return encMonoSub( thisAlphabet, cipherText ) # use the monoalphabetic substitution cipher
- #
- #-- -----------------
- def caesarEncipherALLkeys( plainText = "" ): # NOT USED .. demos shift alg.
- """ 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()
- # 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 )
- #
- #
- #----------------------------------------------------------------------------------------------------------
- def encMonoSub( alphabet="", txt=""):
- """A monoalphabetic substitution cipher uses a fixed system of substitution
- in that a letter in the plaintext is always replaced by the same letter or symbol to create the ciphertext.
- Handles non-linear substitution."""
- lenTxt = len(txt)
- if ( lenTxt == 0 or len(alphabet) != 26 ) : return "ERROR: "+ str( len( alphabet ))
- # ----------- ------------------- ----------------
- ordA = ord('A') # ord() gets codepoint for Unicode char
- plainText = txt.upper()
- cipherChars = []
- for token in plainText :
- if token.isupper(): # map char using alphabet
- cypherChar = alphabet[ ord( token ) - ordA ] # LOOK-UP
- #
- else: # other chars pass thru ..
- cypherChar = token
- #
- cipherChars.append( cypherChar )
- #
- return "".join( cipherChars ) # a String
- #
- #-- ----------
- def decMonoSub( alphabet="", txt=""):
- """A monoalphabetic substitution cipher uses a fixed system of substitution
- in that a letter in the plaintext is always replaced by the same letter or symbol to create the ciphertext.
- Handles non-linear substitution."""
- # I discovered that DECRYPTING the "standard alphabet" with ..
- # .. a 'mono alphabet' yields the "reciprocal (inverse decrypt) alphabet"
- lenTxt = len(txt)
- if ( lenTxt == 0 or len(alphabet) != 26 ) : return "ERROR "+ str( len( alphabet ))
- # ----------- ------------------- ----------------
- ordA = ord('A') # ord() gets codepoint for Unicode char
- cipherText = txt.upper()
- plainChars = []
- for token in cipherText :
- if token.isupper(): # map char using alphabet
- plainChar = chr( ordA + alphabet.index( token )) #SEARCH using .. index( token )
- else: # other chars pass thru ..
- plainChar = token
- #
- plainChars.append( plainChar )
- #
- return "".join( plainChars ) # a String
- #
- #-- -------------
- def showALLshifts( cipherText = "" ):
- #
- print( '\n>> ' + cipherText ) # DEBUG output
- ordA = ord('A') # ord() gets codepoint for Unicode char
- cipherText = cipherText.upper() # force UPPERCASE ascii
- #
- for k in range( 1, 26 ) : # in 1..25
- #
- plainTxt = decCaesar( k, cipherText )
- # =========
- # 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)
- #
- print( key, plainTxt )
- #
- #
- #----------------------------------------------------------------------------------------------------------
- # TEST calls ..
- #--------------------
- print( '\n*** ENCIPHER MonoSub on "ABCDEFGHIJKLMNOPQRSTUVWXYZ" returns the KEY alphabet ! ***' )
- result = encMonoSub("DLRFOAPJVIBSGHUQKTMNZCEWYX", 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
- print( result ) # -> scramble alphabet
- print( '\n*** DECIPHER MonoSub on "ABCDEFGHIJKLMNOPQRSTUVWXYZ" returns the related reciprocal (inverse) alphabet !!! ***' )
- result = decMonoSub("DLRFOAPJVIBSGHUQKTMNZCEWYX", 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
- print( result ) # -> related unscramble (inverse) alphabet !!!
- print( '\n*** Show the alphabet and its inverse for Caesar (2) ***' )
- print( encMonoSub( getAlphabet( 2 ), getAlphabet() ))
- print( decMonoSub( getAlphabet( 2 ), getAlphabet() ))
- print( '\n*** ENCIPHER MonoSub ***' )
- result = encMonoSub("DLRFOAPJVIBSGHUQKTMNZCEWYX", 'AL-KINDI WAS BORN IN YEMEN TO A RICH FAMILY AS WELL AS PHILOSOPHY, HE WORKED IN ASTRONOMY, ALCHEMY, MATHEMATICS, MEDICINE, GEOGRAPHY, AND MANY OTHER TOPICS. HE BECAME A MEMBER OF A SCIENTIFIC PLACE OF STUDY CALLED THE HOUSE OF WISDOM. HIS TREATISES ON MUSIC WERE THOUGHT TO BE THE BEST WORKS ON THE SUBJECT OF MUSIC IN ARABIC.')
- print( result )
- print( '\n*** DECIPHER using ENCIPHER MonoSub with "inverse alphabet" ***' )
- result = encMonoSub("FKVAWDMNJHQBSTEGPCLROIXZYU", 'DS-BVHFV EDM LUTH VH YOGOH NU D TVRJ ADGVSY DM EOSS DM QJVSUMUQJY, JO EUTBOF VH DMNTUHUGY, DSRJOGY, GDNJOGDNVRM, GOFVRVHO, POUPTDQJY, DHF GDHY UNJOT NUQVRM. JO LORDGO D GOGLOT UA D MRVOHNVAVR QSDRO UA MNZFY RDSSOF NJO JUZMO UA EVMFUG. JVM NTODNVMOM UH GZMVR EOTO NJUZPJN NU LO NJO LOMN EUTBM UH NJO MZLIORN UA GZMVR VH DTDLVR.')
- print( result )
- print( '\n*** DECIPHER ... ***' )
- result = decMonoSub("DLRFOAPJVIBSGHUQKTMNZCEWYX", 'JV. GY HDGO VM GDNNJOE.')
- print( result )
- print( '\n*** ENCIPHER MonoSub: HI MY NAME IS MILLIE ***' )
- result = encMonoSub("DLRFOAPJVIBSGHUQKTMNZCEWYX", 'HI MY NAME IS MILLIE')
- print( result )
- print( '\n*** DECIPHER "jv gy hdgo vm gvssvd" using ENCIPHER MonoSub with "inverse alphabet" ***' )
- result = encMonoSub("FKVAWDMNJHQBSTEGPCLROIXZYU", 'jv gy hdgo vm gvssvd')
- print( result )
- print( '\n*** DECIPHER using ENCIPHER MonoSub with "inverse alphabet" ***' )
- result = encMonoSub("FKVAWDMNJHQBSTEGPCLROIXZYU", 'qsodmzto goonvhp yuz')
- print( result )
- print( '\n*** DECIPHER MonoSub using DECRYPT ALGORITHM ***' )
- result = decMonoSub("DLRFOAPJVIBSGHUQKTMNZCEWYX", 'qsodmzto goonvhp yuz')
- print( result )
- print( '\n*** ENCIPHER MonoSub ***' )
- result = encMonoSub("DLRFOAPJVIBSGHUQKTMNZCEWYX", 'John Davis')
- print( result )
- #--- Caesar ... -----------------------
- print( '\n*** Caesar examples .. ***' )
- print( decCaesar( 5, 'WJYZWS YT WTRJ') ) # .. RETURN TO ROME
- print( encCaesar( 7, 'IF YOU CAN GUESS THE KEY IT IS EASY TO DECRYPT THE MESSAGE.'))
- print( decCaesar( 7, 'PM FVB JHU NBLZZ AOL RLF PA PZ LHZF AV KLJYFWA AOL TLZZHNL.'))
- showALLshifts('PM FVB JHU NBLZZ AOL RLF PA PZ LHZF AV KLJYFWA AOL TLZZHNL.')
- showALLshifts('IF YOU CAN GUESS THE KEY IT IS EASY TO DECRYPT THE MESSAGE.')
- #
- print( "----")
- print( decCaesar( 17, 'z rd vetipgkzex r dvjjrxv'))
- print( decCaesar( 15, 'htatri iwt utaxct'))
- print( decCaesar( 1, 'xfmdpnfcbdl'))
- print( decCaesar( 25, 'khjdvhrd'))
Add Comment
Please, Sign In to add comment