07.07.2023 Views

Implementing-cryptography-using-python

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

54 Chapter 2 ■ Cryptographic Protocols and Perfect Secrecy

Hello World

48656c6c6f20576f726c64

87521618088882533792115812

48656c6c6f20576f726c64

Hello World

While examining the following code, notice the use of binascii along with

the hexlify() and unhexlify() methods. The hexlify() method returns the

hexadecimal representation of binary data. Each byte of the data is converted

into a two-digit hex representation. The resulting output will be twice as long

as the length of the data. The unhexlify() method returns the binary representation

of the data. As you may have guessed, the unhexlify() method is the

inverse of the hexlify() method:

import binascii

def text2int(msg):

print (msg)

# convert string to hex

#hexstr = msg.encode('hex')

msg = msg.encode()

hexstr = binascii.hexlify(msg)

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')

plaintext = binascii.unhexlify(evenpad)

print (plaintext)

text2int("Hello World")

Hello World

b'48656c6c6f20576f726c64'

87521618088882533792115812

48656c6c6f20576f726c64

b'Hello World'

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

Saved successfully!

Ooh no, something went wrong!