Hacking Secret Ciphers with Python

(Ann) #1

224 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


Source code for affineKeyTest.py




  1. This program proves that the keyspace of the affine cipher is limited




  2. to len(SYMBOLS) ^ 2.





  3. import affineCipher, cryptomath



  4. message = 'Make things as simple as possible, but not simpler.'

  5. for keyA in range(2, 100 ):

  6. key = keyA * len(affineCipher.SYMBOLS) + 1



  7. if cryptomath.gcd(keyA, len(affineCipher.SYMBOLS)) == 1:

  8. print(keyA, affineCipher.encryptMessage(key, message))


This is a fairly simple program. It imports the affineCipher module for its
encryptMessage() function and the cryptomath module for its gcd() function. We will
always encrypt the string stored in the message variable. The for loop will range between 2
(since 0 and 1 are not allowed as valid Key A integers) and 100.


On each iteration of the loop, we calculate the key from the current keyA value and always use 1
for Key B (this is why 1 is added on line 8). Remember that it is not valid to use a Key A that is
not relatively prime with the symbol set size. So if the greatest common divisor of the key and the
symbol set size is not equal to 1 , the if statement on line 10 will skip the call to
encryptMessage() on line 11.


Basically, this program will print out the same message encrypted with several different integers
for Key A. The output of this program will look like this:


2 {DXL!jRT^Ph!Dh!hT\bZL!Dh!bhhTFZL9!Flj!^j!hT\bZLf=
3 I&D2!;>M8!&!>JSG2!&!SP\>)G2E!)b!MP_!>JSG2YK
4 vg0w!T$(< P!gP!P(8D4w!gP!D@PP(k4wQ!kXT!<@T!P(8D4wLY
6 q+gC!>U[yO8!+8!8[s&mC!+8!& 88[1mCi!1D>!y >!8[s&mC2u


...skipped for brevity...


92 X{]o!BfcTiE!{E!EcWNZo!{E!NQEEcxZo!x?B!TQB!EcWNZoHV
93 &]IU!7OMCQ9!]9!9ME?GU!]9!?A99M[GUh![57!CA7!9ME?GU;d
94 S?5;!,8729-!?-!-7304;!?-!01--7>4;t!>+,!21,!-7304;.r
96 Nblf!uijoht!bt!tjnqmf!bt!qpttjcmf-!cvu!opu!tjnqmfs/
97 {DXL!jRT^Ph!Dh!hT\bZL!Dh!bhhTFZL9!Flj!^j!hT\bZLf=
98 I&D2!;>M8!&!>JSG2!&!SP\>)G2E!)b!MP_!>JSG2YK
99 vg0w!T$(< P!gP!P(8D4w!gP!D@PP(k4wQ!kXT!<@T!P(8D4wLY

Free download pdf