214 http://inventwithpython.com/hacking
Email questions to the author: [email protected]
Source Code of the Affine Cipher Program
How the affine cipher works was covered in the last chapter. Here is the source code for a Python
program that implements the affine cipher. Open a new file editor window by clicking on File ►
New Window. Type in the following code into the file editor, and then save it as affineCipher.py.
Press F5 to run the program. Note that first you will need to download the pyperclip.py module
and place this file in the same directory as the affineCipher.py file. You can download this file
from http://invpy.com/pyperclip.py.
Source code for affineCipher.py
Affine Cipher
http://inventwithpython.com/hacking (BSD Licensed)
- import sys, pyperclip, cryptomath, random
- SYMBOLS = """ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]
^_`abcdefghijklmnopqrstuvwxyz{|}~""" # note the space at the front
- def main():
- myMessage = """"A computer would deserve to be called intelligent if it
could deceive a human into believing that it was human." -Alan Turing""" - myKey = 2023
- myMode = 'encrypt' # set to 'encrypt' or 'decrypt'
- if myMode == 'encrypt':
- translated = encryptMessage(myKey, myMessage)
- elif myMode == 'decrypt':
- translated = decryptMessage(myKey, myMessage)
- print('Key: %s' % (myKey))
- print('%sed text:' % (myMode.title()))
- print(translated)
- pyperclip.copy(translated)
- print('Full %sed text copied to clipboard.' % (myMode))
- def getKeyParts(key):
- keyA = key // len(SYMBOLS)
- keyB = key % len(SYMBOLS)
- return (keyA, keyB)
- def checkKeys(keyA, keyB, mode):
- if keyA == 1 and mode == 'encrypt':
- sys.exit('The affine cipher becomes incredibly weak when key A is
set to 1. Choose a different key.')