def _g_equal_p_minus_one() -> bool: g = _p - 1 a = DHClient(_p, g) b = DHClient(a.p, a.g) a.gen_session_key(b.public_key) b.gen_session_key(a.public_key) a_encrypted_msg = a.encrypt_msg(_msg) b_encrypted_msg = b.encrypt_msg(_msg) a_decrypted_msg = a.decrypt_msg(*b_encrypted_msg) b_decrypted_msg = b.decrypt_msg(*a_encrypted_msg) if a.public_key == g and b.public_key == g: key = g else: key = 1 key = sha1(key.to_bytes(floor(key.bit_length() / 8) + 1, "big"))[:16] iv = a_encrypted_msg[0] cbc = AESCipher(AESCipher.MODE_CBC, key, iv=iv) mitm_decrypted = pkcs7_unpad(cbc.decrypt(a_encrypted_msg[1])) return mitm_decrypted == a_decrypted_msg == b_decrypted_msg == _msg
def decrypt_msg(self, iv: bytes, msg: bytes) -> bytes: key = sha1( self._session_key.to_bytes( floor(self._session_key.bit_length() / 8) + 1, "big"))[:16] cbc = AESCipher(AESCipher.MODE_CBC, key, iv=iv) return pkcs7_unpad(cbc.decrypt(msg))
def encrypt_msg(self, msg: bytes) -> Tuple[bytes, bytes]: key = sha1( self._session_key.to_bytes( floor(self._session_key.bit_length() / 8) + 1, "big"))[:16] iv = gen_random_bytes(16) cbc = AESCipher(AESCipher.MODE_CBC, key, iv=iv) return (iv, cbc.encrypt(pkcs7_pad(msg)))
def _attacker(plain_text: bytes, token: bytes) -> Tuple[bytes, bytes]: msg = b";admin=true" h = struct.unpack(b">5I", token) for key_size in range(64): fake_msg = _sha1_padding(bytes([0]) * key_size + plain_text)[key_size:] + msg fake_token = sha1(msg, h, (key_size + len(fake_msg)) * 8) yield (fake_msg, fake_token)
def challenge34() -> bool: p = int.from_bytes( bytes.fromhex("ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024" "e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd" "3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec" "6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f" "24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361" "c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552" "bb9ed529077096966d670c354e4abc9804f1746c08ca237327fff" "fffffffffffff"), "big", ) g = 2 msg = b"test" a = DHClient(p, g) b = DHClient(a.p, a.g) a.gen_session_key(b.p) b.gen_session_key(a.p) a_encrypted_msg = a.encrypt_msg(msg) b_encrypted_msg = b.encrypt_msg(msg) a_decrypted_msg = a.decrypt_msg(*b_encrypted_msg) b_decrypted_msg = b.decrypt_msg(*a_encrypted_msg) key = 0 key = sha1(key.to_bytes(floor(key.bit_length() / 8) + 1, "big"))[:16] iv = a_encrypted_msg[0] cbc = AESCipher(AESCipher.MODE_CBC, key, iv=iv) mitm_decrypted = pkcs7_unpad(cbc.decrypt(a_encrypted_msg[1])) return mitm_decrypted == a_decrypted_msg == b_decrypted_msg == msg
def test_sha1_two_block(self): msg = b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" result = "84983e441c3bd26ebaae4aa1f95129e5e54670f1" assert sha1(msg).hex( ) == result, "The result does not match the expected value"
def test_sha1_one_block(self): msg = b"abc" result = "a9993e364706816aba3e25717850c26c9cd0d89d" assert sha1(msg).hex( ) == result, "The result does not match the expected value"