Hacking Secret Ciphers with Python

(Ann) #1

238 http://inventwithpython.com/hacking


Email questions to the author: [email protected]




  1. if keyList != lettersList:




  2. sys.exit('There is an error in the key or symbol set.')








  3. def encryptMessage(key, message):




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








  5. def decryptMessage(key, message):




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








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




  8. translated = ''




  9. charsA = LETTERS




  10. charsB = key




  11. if mode == 'decrypt':




  12. For decrypting, we can use the same code as encrypting. We




  13. just need to swap where the key and LETTERS strings are used.




  14. charsA, charsB = charsB, charsA






  15. loop through each symbol in the message




  16. for symbol in message:




  17. if symbol.upper() in charsA:




  18. encrypt/decrypt the symbol




  19. symIndex = charsA.find(symbol.upper())




  20. if symbol.isupper():




  21. translated += charsB[symIndex].upper()




  22. else:




  23. translated += charsB[symIndex].lower()




  24. else:




  25. symbol is not in LETTERS, just add it




  26. translated += symbol






  27. return translated








  28. def getRandomKey():




  29. key = list(LETTERS)




  30. random.shuffle(key)




  31. return ''.join(key)








  32. if name == 'main':




  33. main()



Free download pdf