Hacking Secret Ciphers with Python

(Ann) #1
Chapter 19 – The Vigenère Cipher 293


  1. translated = decryptMessage(myKey, myMessage)



  2. print('%sed message:' % (myMode.title()))

  3. print(translated)

  4. pyperclip.copy(translated)

  5. print()

  6. print('The message has been copied to the clipboard.')





  7. def encryptMessage(key, message):

  8. return translateMessage(key, message, 'encrypt')





  9. def decryptMessage(key, message):

  10. return translateMessage(key, message, 'decrypt')





  11. def translateMessage(key, message, mode):

  12. translated = [] # stores the encrypted/decrypted message string



  13. keyIndex = 0

  14. key = key.upper()



  15. for symbol in message: # loop through each character in message

  16. num = LETTERS.find(symbol.upper())

  17. if num != -1: # -1 means symbol.upper() was not found in LETTERS

  18. if mode == 'encrypt':

  19. num += LETTERS.find(key[keyIndex]) # add if encrypting

  20. elif mode == 'decrypt':

  21. num -= LETTERS.find(key[keyIndex]) # subtract if decrypting



  22. num %= len(LETTERS) # handle the potential wrap-around




  23. add the encrypted/decrypted symbol to the end of translated.



  24. if symbol.isupper():

  25. translated.append(LETTERS[num])

  26. elif symbol.islower():

  27. translated.append(LETTERS[num].lower())



  28. keyIndex += 1 # move to the next letter in the key

  29. if keyIndex == len(key):

  30. keyIndex = 0

  31. else:


  32. The symbol was not in LETTERS, so add it to translated as is.



  33. translated.append(symbol)



Free download pdf