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 57

>>> msg = "helloworldthisistheonetimepad"

>>> key = ''

>>> for i in range(len(msg)):

>>> key += secrets.choice('ABCDEFGHIJKLMNOPQRSTUVWZYZ')

>>> print (key)

CDHHCYIINAQHKMVOVAAYDPELIRNRU

In some ciphers, you can use language detectors. When the OTP is constructed

properly, there may be a condition that the wrong key will produce English text,

so there is no guarantee that using a language detector will offer the original

message. The next example demonstrates that two possible messages may occur:

Attack at Midnight! or Retreat Do Not Attack.

If you use the correct key, you will see the real message, while using the decoy

key will present the other. If an attacker is trying to brute-force this scheme, it

is possible they will find the wrong message.

The following code recipe introduces using from ... import. To refer to

items from a module within your program’s namespace, you can use the

from ... import statement. When you import modules this way, you can

refer to the functions by name rather than through dot notation. Using the

from ... import construction allows us to reference the defined elements of

a module within our program’s namespace, letting us avoid dot notation. In

this case, we use hexlify and unhexlify:

from binascii import hexlify, unhexlify

def otpSuperMsg(msg1, msg2):

hex1 = hexlify(msg1)

hex2 = hexlify(msg2)

cipher1 = int(hex1, 16)

cipher2 = int(hex2, 16)

msg = cipher1 ^ cipher2

return msg

def otpEnc(msg, key):

superKey = int(msg, 16) ^ key

return superKey

def otpDec(msg, key):

xorMsgKey = msg ^ key

back2hex = format(xorMsgKey, 'x')

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

plaintext = unhexlify(evenpad)

return plaintext

realMessage = b"attackthematmidnight!"

decoyMessage= b"retreatanddonotattack"

msg = otpSuperMsg(realMessage, decoyMessage)

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

Saved successfully!

Ooh no, something went wrong!