cryptopals/cryptlib.py

59 lines
1.9 KiB
Python
Raw Permalink Normal View History

2025-04-26 00:00:45 -04:00
import base64
2025-04-26 22:37:02 -04:00
CHARACTER_FREQ = {
'a': 0.0651738, 'b': 0.0124248, 'c': 0.0217339, 'd': 0.0349835, 'e': 0.1041442, 'f': 0.0197881, 'g': 0.0158610,
'h': 0.0492888, 'i': 0.0558094, 'j': 0.0009033, 'k': 0.0050529, 'l': 0.0331490, 'm': 0.0202124, 'n': 0.0564513,
'o': 0.0596302, 'p': 0.0137645, 'q': 0.0008606, 'r': 0.0497563, 's': 0.0515760, 't': 0.0729357, 'u': 0.0225134,
'v': 0.0082903, 'w': 0.0171272, 'x': 0.0013692, 'y': 0.0145984, 'z': 0.0007836, ' ': 0.1918182
}
2025-04-26 00:00:45 -04:00
# this function takes a string representing hex, converts to bytes, and re-encodes to base64
def hex_to_base64(hex_string):
byte_array = bytearray.fromhex(hex_string)
base64_value = base64.b64encode(byte_array)
return base64_value
# this function takes two hex strings, converts them to bytes, and xor's them
2025-04-26 22:37:02 -04:00
def byte_xor(hs1, hs2):
byte_array1 = int(hs1,16)
byte_array2 = int(hs2,16)
2025-04-26 00:00:45 -04:00
return byte_array1 ^ byte_array2
2025-04-26 22:37:02 -04:00
# this function will take a hex string and xor it against a single byte
def single_byte_xor(hexstring,key_candidate):
byte_array = bytes.fromhex(hexstring)
results = b''
for char in byte_array:
results += bytes([char ^ key_candidate])
return results
def score_english_lang(byte_string):
score = 0
for byte in byte_string:
letter = chr(byte).lower()
score += CHARACTER_FREQ.get(letter, 0)
return score
# this function takes a string and xor's it with a repeating key
def repeating_xor(string):
byte_array = string.encode()
cipher_bytes = b''
key_counter = 0
for char in byte_array:
match key_counter:
case 1:
key = ord("C")
case 2:
key = ord("E")
case _:
key = ord("I")
cipher_bytes += bytes([char ^ key])
key_counter += 1
if key_counter > 2:
key_counter = 0
return cipher_bytes.hex()