def raw_decrypt(self, ciphertext):
     prng = MT19937(self.seed)
     num_chunks = len(ciphertext) // SIZE_OF_CHUNK
     plaintext_chunks = []
     for i in range(num_chunks):
         random = prng.get_random().to_bytes(SIZE_OF_CHUNK, byteorder="big")
         plaintext_chunks.append(fixed_xor(random, ciphertext[i * SIZE_OF_CHUNK:(i + 1) * SIZE_OF_CHUNK]))
     random = prng.get_random().to_bytes(SIZE_OF_CHUNK, byteorder="big")
     remainder = len(ciphertext) % SIZE_OF_CHUNK
     if remainder != 0:
         plaintext_chunks.append(fixed_xor(random[:remainder], ciphertext[-remainder:]))
     plaintext = bytearray()
     for chunk in plaintext_chunks:
         plaintext.extend(chunk)
     return plaintext
def main():
    string = bytes(
        "Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a cymbal",
        encoding="utf-8")
    key = b"ICE"
    new_key_bytes = extend_key_for_xor(key, len(string))
    print(binascii.hexlify(fixed_xor(string, new_key_bytes)).decode("utf-8"))
def main():

    oneline = ""
    with open("data/6.txt", "r") as file:
        for line in file.readlines():
            oneline += line.strip("\n")
    ciphertext = base64.b64decode(oneline)

    key = crack_repeating_xor(ciphertext)
    print("\nKey is: \"" + key.decode("utf-8") + "\n")
    plaintext = fixed_xor(ciphertext, extend_key_for_xor(key, len(ciphertext)))
    print(plaintext.decode("utf-8") + "\n")
Beispiel #4
0
def main():
    result_list = []
    with open("data/4.txt", "r") as file:
        for index, line in enumerate(file.readlines()):
            line = line.strip("\n")
            bytes_str = binascii.unhexlify(line)
            # single byte xor
            for i in range(256):
                try:
                    plaintext = fixed_xor(bytes_str, (struct.pack("B", i) * len(bytes_str))).decode("utf-8")
                except UnicodeDecodeError:
                    continue
                if text_check_only_allowed_chars(plaintext, allowed_chars_string) and text_contains_char(plaintext, " "):
                    vector_a = build_frequency_vector_from_text(plaintext, list(char_frequency_reference.keys()), uppercase=True)
                    result_list.append((cosine_similarity(vector_a, vector_frequency_reference), chr(i), index, plaintext))

    best_match = sorted(result_list, reverse=True)[0]
    key = best_match[1]
    line = best_match[2]
    plaintext = best_match[3]
    print("line: " + str(line) + " - key: " + key + " - plaintext: " + plaintext)
def find_key(blocks):

    key = bytearray()
    for i in range(len(blocks)):
        single_block_result_list = []
        for j in range(256):
            plaintext = fixed_xor(blocks[i],
                                  struct.pack("B", j) * len(blocks[i]))
            try:
                plaintext = plaintext.decode("utf-8")
            except UnicodeDecodeError:
                continue
            if text_check_only_allowed_chars(plaintext, allowed_chars_string):
                vector_a = build_frequency_vector_from_text(
                    plaintext,
                    list(char_frequency_reference.keys()),
                    uppercase=True)
                if is_null_vector(vector_a) is True:
                    continue
                single_block_result_list.append(
                    (cosine_similarity(vector_a, vector_frequency_reference),
                     j, plaintext))

        print(sorted(single_block_result_list, reverse=True))
        try:
            best_block_key = sorted(single_block_result_list,
                                    reverse=True)[0][1]
            print("The best key for this block is char \"" +
                  chr(best_block_key) +
                  "\", press Enter or specify another int")
            key_char = int(input() or best_block_key)
            key.extend(struct.pack("B", key_char))
        except IndexError:
            return None

    return bytes(key)
def brute_second_block(first_block, second_block):
    prexored = []
    for j in range(MyAES.block_size - 1, -1, -1):
        fb_bytearray = bytearray(first_block)
        for i in range(MyAES.block_size):
            fb_bytearray[i] = 0
        for i in range(len(prexored)):
            fb_bytearray[j + i + 1] = prexored[i] ^ (MyAES.block_size - j)
        found = False
        for byte in range(256):
            fb_bytearray[j] = byte
            #print(str(byte) + " - " + binascii.hexlify(fb_bytearray).decode("utf-8"))
            try:
                if decrypt(bytes(fb_bytearray), second_block) is True:
                    prexored.insert(0, byte ^ (MyAES.block_size - j))
                    found = True
                    #print("found " + str(j) + " - " + str(byte ^ (aes_block_size - j)))
                    break
            except InvalidPKCS7PaddingException:
                pass
        if found is False:
            raise Exception("Ouch")
        #print(prexored)
    return fixed_xor(first_block, prexored)

if __name__ == '__main__':
    '''
    cipher = MT19937StreamCipher(14391)
    ciph = cipher.raw_encrypt(b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")
    print(ciph)
    deciph = cipher.raw_decrypt(ciph)
    print(deciph)
    value_bytes = fixed_xor_bytes(ciph[:SIZE_OF_CHUNK], b"A" * SIZE_OF_CHUNK)
    value = int.from_bytes(value_bytes, byteorder="big")
    crack_seed(value)
    '''

    plaintext = b"BBBBBBBB"
    ciph = fixed_xor(salted_encrypt(plaintext), plaintext)
    values = []
    print(binascii.hexlify(ciph))
    for i in range(SIZE_OF_CHUNK):
        values.append(int.from_bytes(ciph[i:SIZE_OF_CHUNK + i], byteorder="big"))
    print(values)
    crack_seed(values)








def fixed_xor_hex(f_hex_str, s_hex_str):
    f_str = binascii.unhexlify(f_hex_str)
    s_str = binascii.unhexlify(s_hex_str)
    raw_res = fixed_xor(f_str, s_str)
    return binascii.hexlify(raw_res).decode("utf-8")