just slight update

This commit is contained in:
2024-12-01 17:29:14 +09:00
parent cd26dd8c88
commit 0d6eaf273d
2 changed files with 87 additions and 8 deletions

79
week05/easy/no_test.py Normal file
View File

@ -0,0 +1,79 @@
import random
import binascii
from Crypto.Cipher import AES
from Crypto.Hash import CMAC, HMAC, SHA256
import hashlib
KEY = b'1337133713371337'
def pkcs7(message: bytes, block_size: int = 16) -> bytes:
gap_size = block_size - (len(message) % block_size)
return message + bytes([gap_size] * gap_size)
def calc_cbc_mac(message: bytes, iv: bytes, key: bytes) -> bytes:
cipher = AES.new(key, AES.MODE_CBC, iv)
message = pkcs7(message)
last_block = cipher.encrypt(message)[-16:]
return last_block
def calc_hmac(message: bytes, key: bytes) -> bytes:
# Create HMAC object with the key and message using SHA-256
hmac = HMAC.new(KEY, msg=message, digestmod=SHA256)
# Calculate the HMAC
mac = hmac.hexdigest()
return mac
def calc_cmac(message: bytes, key: bytes) -> bytes:
c = CMAC.new(key, ciphermod=AES)
c.update(message)
return c.digest()
def calc_pure_cmac(message: bytes, key: bytes) -> bytes:
def left_shift(k):
"""Perform left shift on a byte string with overflow handling"""
result = bytearray(k)
overflow = result[0] & 0x80
for i in range(len(result)):
result[i] <<= 1
if i > 0:
result[i] |= (1 if result[i-1] & 0x80 else 0)
if overflow:
result[-1] ^= 0x87
return bytes(result)
def xor_bytes(a, b):
"""XOR two byte strings"""
return bytes(x ^ y for x, y in zip(a, b))
def check_challenge(challenge: bytes):
return (
calc_cbc_mac(challenge, b'\x00' * 16, KEY),
calc_cmac(challenge, KEY),
calc_hmac(challenge, KEY)
)
def decode_message(msg):
return binascii.unhexlify(msg)
def main():
challenge = "f681e8625406c40419ae7771eac8f8a2eb6a6fcb1fc0396ab8fdca793a27c93a6dafbb"
challenge = decode_message(challenge)
print(check_challenge(challenge))
if __name__ == "__main__":
main()

View File

@ -1,8 +1,9 @@
import random
import binascii
import base64
from Crypto.Cipher import AES
from Crypto.Hash import CMAC, HMAC, SHA256
# Crypto.Hash and hmac modules are forbidden so needs to replace them
KEY = b'1337133713371337'
@ -16,22 +17,21 @@ def calc_cbc_mac(message: bytes, iv: bytes, key: bytes) -> bytes:
cipher = AES.new(key, AES.MODE_CBC, iv)
message = pkcs7(message)
last_block = cipher.encrypt(message)[-16:]
last_block = base64.b64encode(last_block)
return last_block
def calc_hmac(message: bytes, key: bytes) -> bytes:
# Create HMAC object with the key and message using SHA-256
hmac = HMAC.new(KEY, msg=message, digestmod=SHA256)
# Calculate the HMAC
mac = hmac.hexdigest()
return mac
hmac = base64.b64encode(hmac.digest())
return hmac
def calc_cmac(message: bytes, key: bytes) -> bytes:
c = CMAC.new(key, ciphermod=AES)
c.update(message)
return c.digest()
cmac = base64.b64encode(c.digest())
return cmac
def check_challenge(challenge: bytes):