|
| 1 | +import hashlib |
| 2 | + |
| 3 | + |
| 4 | +def sha256_short(s: str) -> str: |
| 5 | + """Returns first 8 characters in SHA256 hash of `s`.""" |
| 6 | + return hashlib.sha256(s.encode()).hexdigest()[:8] |
| 7 | + |
| 8 | + |
| 9 | +def find_emails_by_hashes(input_file, output_file, target_hashes): |
| 10 | + # 1. Create a dictionary to map hashes back to emails |
| 11 | + # Key: hash string, Value: original email |
| 12 | + hash_map = {} |
| 13 | + |
| 14 | + try: |
| 15 | + with open(input_file, "r") as f: |
| 16 | + for line in f: |
| 17 | + email = line.strip() |
| 18 | + if email: |
| 19 | + # Compute hash and store in map |
| 20 | + h = sha256_short(email) |
| 21 | + hash_map[h] = email |
| 22 | + |
| 23 | + # 2. Identify which original emails match our target hash list |
| 24 | + matched_emails = [] |
| 25 | + for h in target_hashes: |
| 26 | + if h in hash_map: |
| 27 | + matched_emails.append(hash_map[h]) |
| 28 | + else: |
| 29 | + print(f"Warning: No email found for hash {h}") |
| 30 | + |
| 31 | + # 3. Write the results to a new file |
| 32 | + with open(output_file, "w") as f: |
| 33 | + for email in matched_emails: |
| 34 | + f.write(f"{email}\n") |
| 35 | + |
| 36 | + print(f"Successfully recovered {len(matched_emails)} emails to {output_file}") |
| 37 | + |
| 38 | + except FileNotFoundError: |
| 39 | + print(f"Error: The file '{input_file}' or '{output_file}' was not found.") |
| 40 | + |
| 41 | + |
| 42 | +# TODO parameterize as CLI |
| 43 | +if __name__ == "__main__": |
| 44 | + target_list = [ |
| 45 | + "e3384165", |
| 46 | + "1faf1492", |
| 47 | + "0757b4af", |
| 48 | + "5e0b5dff", |
| 49 | + "55d9e0b2", |
| 50 | + "4349b29d", |
| 51 | + "27f16a00", |
| 52 | + "1bcf17a8", |
| 53 | + "bbb281e4", |
| 54 | + "18e36d10", |
| 55 | + "d0d1b4b0", |
| 56 | + "94d2cb91", |
| 57 | + "09e6bcbc", |
| 58 | + "08a08a79", |
| 59 | + "1a3aee97", |
| 60 | + "3ff28b43", |
| 61 | + "4972bef4", |
| 62 | + "a8faf137", |
| 63 | + "d6797b5b", |
| 64 | + "fc1888f1", |
| 65 | + "c2b307c8", |
| 66 | + "395b6a1a", |
| 67 | + "f0cd1289", |
| 68 | + "90cfed97", |
| 69 | + "41a86dbb", |
| 70 | + ] |
| 71 | + |
| 72 | + find_emails_by_hashes( |
| 73 | + input_file="../../data/private/out/cs61a/fa25/emails.txt", |
| 74 | + output_file="../../data/private/out/dev3/emails.txt", |
| 75 | + target_hashes=target_list, |
| 76 | + ) |
0 commit comments