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.

206 Chapter 7 ■ Message Integrity

choosing the length of the truncated message digest and information about its

security implications for the cryptographic application that uses it, see SP 800-107.

import hashlib

hasher = hashlib.md5()

# from http://csrc.nist.gov/groups/STM/cavp/documents/mac/

hmactestvectors.zip

with open('hmactestvectors.zip', 'rb') as afile:

buf = afile.read()

hasher.update(buf)

print(hasher.hexdigest())

The preceding Python should produce the following HMAC:

054d8addf01353605068508266eb2f19

To examine a NIST-supported SHA256 hash, review the following. It has

many similarities, but this example incorporates a BLOCKSIZE:

import hashlib

BLOCKSIZE = 65536

hasher = hashlib.sha256()

with open('hmactestvectors.zip', 'rb') as afile:

buf = afile.read(65536)

while len(buf) > 0:

hasher.update(buf)

buf = afile.read(BLOCKSIZE)

print(hasher.hexdigest())

The second example will produce the following HMAC:

418c3837d38f249d6668146bd0090db24dd3c02d2e6797e3de33860a387ae4bd

CBC-MAC

The cipher block chaining message authentication code (CBC-MAC) is used in

cryptography to construct a MAC from a block cipher. The initial message gets

encrypted with a block cipher algorithm in CBC mode. The CBC mode creates

a chain of blocks such that each block depends on the proper encryption of the

previous block. CBC sets up an interdependence that ensures that a change to

any portion of the plaintext bit causes the last block to be encrypted in a way

that cannot be predicted or counteracted without knowing the key to the block

cipher. The CBC-MAC encryption process is shown in Figure 7.2.

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

Saved successfully!

Ooh no, something went wrong!