Security and Cryptography in Python - HMAC

Security and Cryptography in Python - HMAC

image-20210307102233320

Implement in Python

import hashlib

# Alice and Bob share a secret key
secret_key = "secret key".encode()

# Alice wants to compute a MAC
m = "Hey Bob. You are still awesome.".encode()
sha256 = hashlib.sha256()
sha256.update(secret_key)
sha256.update(m)
hmac = sha256.digest()

print(m, hmac)

# Bob receives and validates the HMAC
sha256 = hashlib.sha256()
sha256.update(secret_key)
sha256.update(m)
hmac = sha256.digest()
print(m, hmac)

Running Result:

image-20210307103809072

What happens if Eve modifies a message.

import hashlib


def modify(m):
    l = list(m)
    l[0] = l[0] ^ 1
    return bytes(l)


# Alice and Bob share a secret key
secret_key = "secret key".encode()

# Alice wants to compute a MAC
m = "Hey Bob. You are still awesome.".encode()
sha256 = hashlib.sha256()
sha256.update(secret_key)
sha256.update(m)
hmac = sha256.digest()
print(m, hmac)

# Eve comes along
m = modify(m)
print(m)

# Bob receives and validates the HMAC
sha256 = hashlib.sha256()
sha256.update(secret_key)
sha256.update(m)
hmac = sha256.digest()
print(m, hmac)

Running Result:

image-20210307104305678

posted @ 2021-03-07 10:44  晨风_Eric  阅读(67)  评论(0编辑  收藏  举报