Hacking Secret Ciphers with Python

(Ann) #1
Chapter 15 – The Affine Cipher 215


  1. if keyB == 0 and mode == 'encrypt':

  2. sys.exit('The affine cipher becomes incredibly weak when key B is
    set to 0. Choose a different key.')

  3. if keyA < 0 or keyB < 0 or keyB > len(SYMBOLS) - 1:

  4. sys.exit('Key A must be greater than 0 and Key B must be between 0
    and %s.' % (len(SYMBOLS) - 1))

  5. if cryptomath.gcd(keyA, len(SYMBOLS)) != 1:

  6. sys.exit('Key A (%s) and the symbol set size (%s) are not
    relatively prime. Choose a different key.' % (keyA, len(SYMBOLS)))





  7. def encryptMessage(key, message):

  8. keyA, keyB = getKeyParts(key)

  9. checkKeys(keyA, keyB, 'encrypt')

  10. ciphertext = ''

  11. for symbol in message:

  12. if symbol in SYMBOLS:


  13. encrypt this symbol



  14. symIndex = SYMBOLS.find(symbol)

  15. ciphertext += SYMBOLS[(symIndex * keyA + keyB) % len(SYMBOLS)]

  16. else:

  17. ciphertext += symbol # just append this symbol unencrypted

  18. return ciphertext





  19. def decryptMessage(key, message):

  20. keyA, keyB = getKeyParts(key)

  21. checkKeys(keyA, keyB, 'decrypt')

  22. plaintext = ''

  23. modInverseOfKeyA = cryptomath.findModInverse(keyA, len(SYMBOLS))



  24. for symbol in message:

  25. if symbol in SYMBOLS:


  26. decrypt this symbol



  27. symIndex = SYMBOLS.find(symbol)

  28. plaintext += SYMBOLS[(symIndex - keyB) * modInverseOfKeyA %
    len(SYMBOLS)]

  29. else:

  30. plaintext += symbol # just append this symbol undecrypted

  31. return plaintext





  32. def getRandomKey():

  33. while True:

  34. keyA = random.randint(2, len(SYMBOLS))

  35. keyB = random.randint(2, len(SYMBOLS))

Free download pdf