Study Record

[암호 프로그래밍] HMAC , CMAC 프로그램 본문

암호/프로그래밍

[암호 프로그래밍] HMAC , CMAC 프로그램

초코초코초코 2021. 12. 13. 10:00
728x90

HMAC - SHA256 사용하기

from Crypto.Hash import HMAC, SHA256


message = b'hello'        # message
secretKey = b'secret'     # key

hMac = HMAC.new(secretKey, message, digestmod=SHA256)
print(hMac.hexdigest())

 

HMAC - SHA256 유효성 검사

from Crypto.Hash import HMAC, SHA256


recMsg = b'hello'
recvMac = '88aab3ede8d3adf94d26ab90d3bafd4a2083070c3bcce9c014ee04a443847c0b'
secretKey = b'secret'

hMac = HMAC.new(secretKey, recMsg, SHA256)

# 내가 만든 HMAC 값과 받은 MAC 값을 확인해본다.
try:
    hMac.hexverify(recvMac)
    print("[ OK ] Authentic")
except Exception as e:
    print("[ FAIL ] Not authentic")

 

CMAC 사용하기

from Crypto.Hash import CMAC
from Crypto.Cipher import AES


# sender
message = b'hello'
secretKey = b'sixteen byte Key'

# cmac create
cmac = CMAC.new(secretKey, ciphermod=AES)
cmac.update(message)

sendMsg = message
sendMac = cmac.digest()

# receiver
recvMsg = sendMsg
recvMac = sendMac

h = CMAC.new(secretKey, ciphermod=AES)
h.update(recvMsg)
# verify
try:
    h.verify(recvMac)
    print('[  OK  ] Authentic ')
except Exception as e:
    print('Error:', e)
    print('Not authentic')

 

728x90