07.07.2023 Views

Implementing-cryptography-using-python

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 2 ■ Cryptographic Protocols and Perfect Secrecy 53

>>> print (ord('A'))

65

>>> print (bin(ord('A')))

0b1000001

You will find that the use of XOR is critical to cryptography. The power of

XOR is that it is self-decrypting. If you encrypt a value using XOR, you can

easily reverse it with the same operation. We will show this with a simple

integer solution first by typing the following into the shell. The following code

takes two integers (240, 115) and gets their XOR value (131). You can then XOR

131 with either 240 or 115 and get the other value:

>>> x = 240

>>> y = 115

>>> z = (x ^ y) #131

>>> print (z ^ 115)

240

>>> print (z ^ 240)

115

To XOR a whole string with another string, we should convert plaintext into

an integer, then XOR the integer and reverse that. The print() function will

work in either scope. One of the biggest differences between the two code samples

is the way we encode and decode hexadecimal values.

The following example shows how the encode method is used on the string:

def text2int(msg):

print (msg)

# convert string to hex

hexstr = msg.encode('hex')

print (hexstr)

# convert hex to integer

integer_m = int(hexstr, 16)

print (integer_m)

# convert integer back to hex

back2hex = format(integer_m, 'x')

print (back2hex)

# convert back to string

evenpad = ('0' * (len(back2hex) % 2)) + back2hex

plaintext = evenpad.decode('hex')

print (plaintext)

text2int("Hello World")

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!