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 55

Armed with this information, you can now encrypt plaintext to an encrypted

value and retrieve it only with a secret password, as shown here:

import binascii

def xorKey(secret):

secret = secret.encode()

hexstr = binascii.hexlify(secret)

key = int(hexstr, 16)

print ("key: ", key)

return key

def xorEnc(msg, key):

msg = msg.encode()

hexstr = binascii.hexlify(msg)

print ("hexstr: ", hexstr)

ciphertext = int(hexstr, 16) ^ key

print ("ciphertext: ", ciphertext)

return ciphertext

def xorDec(msg, key):

xorMsgKey = msg ^ key

back2hex = format(xorMsgKey, 'x')

print ("back2hex: ", back2hex)

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

plaintext = binascii.unhexlify(evenpad)

print ("plaintext: ", plaintext)

return plaintext

key = xorKey("mysecret")

key2 = xorKey("wrongpass")

cipher = xorEnc('Hello world',key)

plain = xorDec(cipher,key)

wrongplain = xorDec(cipher, key2)

As you can see, only using the right key will result in the correct message.

The preceding should return the following:

key: 7888463101613466996

key: 2203408475604721431411

hexstr: 48656c6c6f20776f726c64

ciphertext: 87521610353724475878410512

back2hex: 48656c6c6f20776f726c64

plaintext: Hello world

back2hex: 48651b73793d757c617a63

plaintext: Hey=u|azc

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

Saved successfully!

Ooh no, something went wrong!