import pcapy
from bitstring  import *
import random

def complete_8(my_int):
    answer = str(my_int)
    while len(answer) < 8:
        answer = "0" + answer
    return answer

def gen_token(bit_count):
    rand_map = {}
    answer = []
    while len(answer) < bit_count / 2:
        runner = random.getrandbits(bit_count)
        c = format(runner, "b")
        c2 = complete_8(c)
        if c2 in rand_map:
            continue
        else:
            rand_map[c2] = True
            answer.append(c2)
    return answer

def is_null(key_token):
    for i in key_token:
        if i == "1":
            return False
    return True

def is_inside(key_token, bcad, fragment_number):
    answer1 = "0"
    answer2 = []
    if is_null(key_token):
        return answer1, answer2
    is_ok = True
    for i in range(0, len(key_token)):
        if key_token[i] == "0" and bcad[fragment_number * 8 + i] == "1":
            is_ok = False
            break
        if key_token[i] == "1" and bcad[fragment_number * 8 + i] == "1":
            answer2.append(i)
    if is_ok == True:
        answer1 = "1"
    return answer1, answer2

def correct_key_token(key_token, positions):
    answer = key_token
    for i in range(0, len(positions)):
        answer = answer[0:i] + "0" + answer[i + 1: len(answer)]
    return answer

def check_empty(arr_key_token):
    for i in arr_key_token:
        for j in range(0, len(i)):
            if i[j] == "1":
                return False
    return True

def main():
    print("reading pcap file")
    reader = pcapy.open_offline("201910011400.pcap")
    print("end of reading")

    print("generating keys")
    keys_to_use = gen_token(8)
    print("Key token generated printing:")
    print(keys_to_use)

    while True:
        try:
            (header, payload) = reader.next()
            bcad = ""
            for term in payload:
                c = format(term, "b")
                bcad += complete_8(c)
            print("printing complete message")
            print(bcad)
            arr_key_token = keys_to_use
            fragment_number = 0
            Token_for_this_case = ""
            while fragment_number * 8 < len(bcad) and not check_empty(arr_key_token):
                a1, a2 = "", ""
                for i in range(0, len(arr_key_token)):
                    a1, a2 = is_inside(arr_key_token[i], bcad, fragment_number)
                    if a1 == "1":
                        correct_key_token(arr_key_token[i], a2)
                    Token_for_this_case += a1
                fragment_number += 1
            print("el Token para este caso es: ")
            print(Token_for_this_case)


            input("Continuar any/ cntrl c? ")
        except pcapy.PcapError:
            break


if __name__ == "__main__":
    main()
