Hacking Secret Ciphers with Python

(Ann) #1

402 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


So a cryptographic block is really just a very large integer. Since our block size is 128 bytes, it
can represent any integer between 0 and up to (but not including) 256 ^ 128, which is
179,769,313,486,231,590,772,930,519,078,902,473,361,797,697,894,230,657,273,430,081,157,7
32,675,805,500,963,132,708,477,322,407,536,021,120,113,879,871,393,357,658,789,768,814,41
6,622,492,847,430,639,474,124,377,767,893,424,865,485,276,302,219,601,246,094,119,453,082,
952,085,005,768,838,150,682,342,462,881,473,913,110,540,827,237,163,350,510,684,586,298,2
39,947,245,938,479,716,304,835,356,329,624,224,137,216.


(You might have noticed that the RSA cipher uses a lot of big numbers.)


The reason RSA needs to work on a block (which represents multiple characters) is because if we
used the RSA encryption algorithm on a single character, the same plaintext characters would
always encrypt to the same ciphertext characters. In that case, the RSA cipher just becomes a
simple substitution cipher with fancy mathematics, kind of like the affine and Caesar ciphers.


The RSA cipher works by encrypting an integer that is hundreds of digits long (that is, a block)
into a new integer that is hundreds of digits long (that is, a new block). The mathematics of
encrypting a large plaintext integer to a large ciphertext integer are simple enough. But first we
will need a way to convert between a string and a large integer (that is, a block).


We can use ASCII as a system to convert between a single character and a small integer (between
0 and 255 ). But we will also need a way to combine several small integers into a large integer that
we perform RSA encryption on.


Remember how the affine cipher in Chapter 15 had two keys, Key A and Key B, but they were
combined by multiplying Key A by the symbol set size (which was 95) and then adding Key B?
This was how we combined two small key integers into one larger key integer.


This worked because the ranges of both Key A and Key B were from 0 to 94. In the RSA
program, each character’s ASCII integer ranges from 0 to 255. To combine ASCII integers
together into one large number we use the following formula:


Take the ASCII integer of the character at index 0 of the string and multiply it by 256 ^ 0 (but
since 256 ^ 0 is 1, and multiplying by 1 leaves you with just the original number, this one is
easy). Take the ASCII integer of the character at index 1 and multiply it by 256 ^ 1. Take the
ASCII integer of the character at index 2 and multiply it by 256 ^ 2 , and so on and so on. To get
the final large integer, add all of these products together. This integer is the ciphertext’s block.


Table 24-2 has an example using the string, 'Hello world!':

Free download pdf