Last active
November 13, 2022 17:26
-
-
Save FerranAD/5f6d1ee63544e3540f78919ccdd8d4ec to your computer and use it in GitHub Desktop.
Atac de força bruta sense diccionari amb hashes precomputats
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from cryptography.hazmat.primitives import hashes | |
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC | |
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes | |
SALT = bytes.fromhex('10 f2 27 27 6c 4f c5 33') | |
DICT = 'diccionari.txt' | |
ENC_FILE = 'exercici.bin' | |
CIPHERTEXT_HEADER_LENGHT = 16 | |
def main(): | |
attacker = DictAttacker(DICT, ENC_FILE, SALT) | |
password: str = attacker.get_password() | |
if password: | |
print(f'Password found: {password}') | |
else: | |
print('Password not found') | |
class DictAttacker: | |
def __init__(self, dict_path: str, enc_file: str, salt: bytes): | |
self.dict_wordlist = self._get_dict_wordlist(dict_path) | |
self.ciphertext = self._get_bytes_from_file(enc_file) | |
self.salt = salt | |
@staticmethod | |
def _get_dict_wordlist(dict_path: str) -> list[str]: | |
with open(dict_path, 'r') as f: | |
return f.readlines() | |
@staticmethod | |
def _get_bytes_from_file(filename: str) -> bytes: | |
with open(filename, "rb") as f: | |
return f.read()[CIPHERTEXT_HEADER_LENGHT:] | |
def get_password(self) -> str: | |
for password in self.generate_passwords(): | |
key = self.get_pbkdf2_key(password) | |
plaintext = self._decrypt_file(key, self.ciphertext) | |
try: | |
plaintext.decode() | |
return password | |
except UnicodeDecodeError: | |
continue | |
def generate_passwords(self) -> list[str]: | |
for word in self.dict_wordlist: | |
word_without_newline = word.strip() | |
yield word_without_newline | |
for i in range(100): | |
yield word_without_newline + str(i) | |
def get_pbkdf2_key(self, password: str) -> bytes: | |
key_derivation_function = PBKDF2HMAC( | |
algorithm=hashes.SHA1(), | |
length=16, | |
salt=self.salt, | |
iterations=1, | |
) | |
key = key_derivation_function.derive(password.encode()) | |
return key | |
@staticmethod | |
def _decrypt_file(key: bytes, ciphertext: bytes): | |
cipher = Cipher(algorithms.AES128(key), modes.ECB()) | |
decryptor = cipher.decryptor() | |
return decryptor.update(ciphertext) + decryptor.finalize() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment