Exemplo n.º 1
0
def getSerial():
    lib=getLib()
    pkcs11 = PyKCS11.PyKCS11Lib()
    pkcs11.load(lib)
    slots = pkcs11.getSlotList()
    for slot in slots:
        if 'CARTAO DE CIDADAO ' in pkcs11.getTokenInfo(slot).label:
            session = pkcs11.openSession(slot)
            objects = session.findObjects()

            for obj in objects:
                l = session.getAttributeValue(obj, [CKA_LABEL])[0]
                if l == 'CITIZEN SIGNATURE CERTIFICATE':
                    print("Serial: ")
                    try:
                        serial=session.getAttributeValue(obj, [CKA_SERIAL_NUMBER], True)[0]
                        session.closeSession

                        sym=SymCipher("cc")
                        res=sym.cipher(encodeBase64(serial))

                        print(res)
                        return res
                    except Exception as ex:
                        print(' Verification failed: ')
                        print(ex)
Exemplo n.º 2
0
 def decipherHand(self, keys):
     tmp = []
     for tile in self.hand:
         if tile in keys.keys():
             key = keys[tile]
             plaintext = decodeBase64(SymCipher.decipherKey(tile, key))
             print("Peca: ", plaintext)
             tmp.append(plaintext)
     if len(tmp) > 0:
         self.hand = tmp
Exemplo n.º 3
0
 def decipherPiece(self, key, peca, check_tuplo=False):
     pieces = [p for p in self.hand if not isinstance(p,Piece)]
     if len(pieces) == 0:
         return None
     piece = pieces[0]
     #print("ASDASD",piece)
     #if peca == piece:
     #print("TRUEEEEEEE", len(self.hand))
     
     #print("HAND",len(self.hand))
     newPiece = decodeBase64(SymCipher.decipherKey(piece, key))
     #print("PECA::::",newPiece)
     if check_tuplo:
         if not isinstance(newPiece,tuple):
             return peca
     self.hand.remove(piece)
     self.hand.append(newPiece)
     if newPiece:
         return newPiece
     else:
         return None
Exemplo n.º 4
0
    def encryptDeck(self, deck):
        new_deck = []
        for i in deck:
            c = SymCipher(''.join(random.choices(string.ascii_uppercase + string.digits, k=5)))

            key = c.getKey()
            #print("key: ", key)
            # encrypt tuple
            encrypt = c.cipher(encodeBase64(i))
            #print("str: ", encrypt)

            while encrypt in deck:
                print("AQUI")
                c = SymCipher(''.join(random.choices(string.ascii_uppercase + string.digits, k=5)))

                key = c.getKey()

                encrypt = c.cipher(encodeBase64(i))

            new_deck.append(encrypt)

            # guardar tuples e key
            self.keyMapDeck.update({encrypt: key})
        return new_deck
Exemplo n.º 5
0
import base64

deck = []
new_deck = []
store = dict()

with open('pieces', 'r') as file:
    pieces = file.read()
indexes = random.sample(range(100), 28)
for piece in pieces.split(","):
    piece = piece.replace(" ", "").split("-")
    peca = Piece(piece[0], piece[1])
    deck.append(peca)

for i in deck:
    c = SymCipher(''.join(
        random.choices(string.ascii_uppercase + string.digits, k=5)))

    key = c.getKey()
    #print("key: ", key)
    # encrypt tuple
    encrypt = c.cipher(encodeBase64(i))
    #print("str: ", encrypt)

    while encrypt in new_deck:
        print("AQUI")
        c = SymCipher(''.join(
            random.choices(string.ascii_uppercase + string.digits, k=5)))

        key = c.getKey()

        encrypt = c.cipher(str(i))
Exemplo n.º 6
0
 def decipherToTuple(self, key, peca):
     newPiece = decodeBase64(SymCipher.decipherKey(peca, key))
     #print("PECA::::", newPiece)
     return newPiece
Exemplo n.º 7
0
    def handle_action(self, data, sock):
        msg = None
        data = pickle.loads(data)
        # print("DATA: ", data)

        if sock in self.dh_keys.keys():
            if len(self.dh_keys[sock]) == 3:
                data = decodeBase64(self.dh_keys[sock][2].decipher(data))
        print("MSG-->", data)
        action = data["action"]
        print("\n" + action)
        if data:
            if action == "TalkToPlayer":
                playerTo = data["to"]
                print("Sending message to ", playerTo)
                print(self.players[playerTo])
                time.sleep(0.01)
                self.send_to_player(data, self.players[playerTo])
                return None

            if action == "hello":
                privateNumber = random.randint(1, 16)
                keyToSend = diffieHellman(self.sharedBase, privateNumber)
                self.dh_keys[sock] = [privateNumber]
                msg = {
                    "action": "login",
                    "msg": "Welcome to the server, what will be your name?",
                    "key": keyToSend
                }
                return pickle.dumps(msg)
            # TODO login mechanic is flawed, only nickname
            if action == "req_login":
                print("User {} requests login, with nickname {}".format(
                    sock.getpeername(), data["msg"]))
                keyRecev = int(data["key"])
                sharedKey = diffieHellman(keyRecev, self.dh_keys[sock][0])
                print("SharedKey: ", sharedKey)
                self.dh_keys[sock].append(sharedKey)
                self.dh_keys[sock].append(SymCipher(str(sharedKey)))

                if not self.game.hasHost(
                ):  # There is no game for this tabla manager
                    self.game.addPlayer(
                        data["msg"], sock,
                        self.game.deck.pieces_per_player)  # Adding host
                    self.players[data["msg"]] = sock
                    msg = {
                        "action":
                        "you_host",
                        "msg":
                        Colors.BRed + "You are the host of the game" +
                        Colors.Color_Off
                    }
                    print("msg: ", msg)
                    encrypt = self.dh_keys[sock][2].cipher(encodeBase64(msg))
                    print("User " + Colors.BBlue + "{}".format(data["msg"]) +
                          Colors.Color_Off +
                          " has created a game, he is the first to join")
                    return pickle.dumps(encrypt)
                else:
                    if not self.game.hasPlayer(data["msg"]):
                        if self.game.isFull():
                            msg = {
                                "action": "full",
                                "msg": "This table is full"
                            }
                            print("User {} tried to join a full game".format(
                                data["msg"]))
                            return pickle.dumps(msg)
                        else:
                            self.game.addPlayer(
                                data["msg"], sock, self.game.deck.
                                pieces_per_player)  # Adding player
                            msg = {
                                "action": "new_player",
                                "msg": "New Player " + data["msg"] +
                                " registered in game",
                                "nplayers": self.game.nplayers,
                                "game_players": self.game.max_players
                            }
                            print("User " + Colors.BBlue +
                                  "{}".format(data["msg"]) + Colors.Color_Off +
                                  " joined the game")
                            self.players[data["msg"]] = sock
                            # send info to all players
                            self.send_all(msg)

                            # check if table is full
                            if self.game.isFull():
                                print(Colors.BIPurple + "The game is Full" +
                                      Colors.Color_Off)
                                msg = {
                                    "action":
                                    "waiting_for_host",
                                    "msg":
                                    Colors.BRed +
                                    "Waiting for host to start the game" +
                                    Colors.Color_Off
                                }
                                self.send_all(msg, sock)
                            msgEncrypt = self.dh_keys[sock][2].cipher(
                                encodeBase64(msg))
                            return pickle.dumps(msgEncrypt)
                    else:
                        msg = {
                            "action": "disconnect",
                            "msg": "You are already in the game"
                        }
                        print("User {} tried to join a game he was already in".
                              format(data["msg"]))
                        msgEncrypt = self.dh_keys[sock][2].cipher(
                            encodeBase64(msg))
                        return pickle.dumps(msgEncrypt)

            if action == "start_game":
                msg = {
                    "action":
                    "host_start_game",
                    "msg":
                    Colors.BYellow + "The Host started the game" +
                    Colors.Color_Off
                }
                self.send_all(msg, sock)
                msgEncrypt = self.dh_keys[sock][2].cipher(encodeBase64(msg))
                return pickle.dumps(msgEncrypt)

            if action == "ready_to_play":
                msg = {
                    "action":
                    "host_start_game",
                    "msg":
                    Colors.BYellow + "The Host started the game" +
                    Colors.Color_Off
                }
                self.send_all(msg, sock)
                msgEncrypt = self.dh_keys[sock][2].cipher(encodeBase64(msg))
                return pickle.dumps(msgEncrypt)

            if action == "get_game_propreties":
                msg = {"action": "rcv_game_propreties"}
                msg.update(self.game.toJson())
                msgEncrypt = self.dh_keys[sock][2].cipher(encodeBase64(msg))
                return pickle.dumps(msgEncrypt)

            if action == "reg_points":
                if data["msg"][0] == None or data["msg"][0] == "None":
                    self.game.addPoints(data["msg"][2], data["msg"][1])
                else:
                    self.game.addPoints(data["msg"][0], data["msg"][1])

            if action == "KeyToPiece":
                print("DECIPHER", self.playerIndexRevealKey)
                piece = self.game.decipherPiece(data["piece"], data["key"])
                # if self.playerGetPiece == self.game.players[self.playerIndexRevealKey].socket:
                #     msg = {"action": "KeyToPieceAndWhatPiece", "key": data["key"], "pieceTeste": data["piece"],"piece": piece}
                #     print("MSGSEND:::::",msg)
                #     self.send_to_player(msg,self.playerGetPiece)
                # else:
                if "sendKey" not in data.keys():
                    msg = {
                        "action": "KeyToPiecePlayer",
                        "key": data["key"],
                        "piece": data["piece"]
                    }
                    print("MSGSEND:::::", msg)
                    self.send_to_player(msg, self.playerGetPiece)
                    time.sleep(0.2)  # give server time to send all messages
                if not isinstance(piece, tuple):
                    msg1 = {"action": "whatIsThisPiece", "piece": piece}
                    print("MSGSEND:::::", msg1)
                    self.send_to_player(
                        msg1,
                        self.game.players[self.playerIndexRevealKey].socket)
                self.playerIndexRevealKey -= 1

                if self.playerIndexRevealKey < 0:
                    print("DONE DECIPHER")

            player = self.game.currentPlayer()
            # check if the request is from a valid player

            if action == "selectionStage_end":  # tive que passar para fora do if do currentPlayer, pq pode ser qualquer um a mandar
                self.game.deck.deck = data["deck"]
                print("GETPIECEDECK--->", len(self.game.deck.deck))

                msg = {"action": "rcv_game_propreties"}

                #if not self.game.started:
                # if self.game.allPlayersWithPieces():
                #     for a in range (0,self.nplayers):
                #         p=self.game.nextPlayer()
                #         print("DEBUG DARIO: ".join(map(str, self.player.hand)))
                self.game.nextPlayer()
                #if len(data["deck"]) == (28 - self.game.nplayers * player.pieces_per_player):
                self.game.playerWithallPieces()
                #self.game.started = True
                self.game.next_action = "bitCommit"
                #msg.update({"completeDeck": self.game.completeDeck})
                #self.game.player_index = self.nplayers - 1

                # if self.game.allPlayersWithPieces():
                #     self.game.started = True
                #     self.game.next_action = "revelationStage"#"play"
                #     msg.update({"completeDeck": self.game.completeDeck})
                #     self.game.player_index = self.nplayers-1

                msg.update(self.game.toJson())
                self.send_all(msg, sock)
                msgEncrypt = self.dh_keys[sock][2].cipher(encodeBase64(msg))
                return pickle.dumps(msgEncrypt)

            if action == "prep_stage_end":
                self.game.public_keys_list = data["public_keys"]
                self.game.nextPlayer()

                msg = {
                    "action": "rcv_game_propreties",
                    "public_keys": self.game.public_keys_list
                }
                #if self.game.check_added_to_public_list():
                pieces = self.game.reveal_pieces()
                self.game.next_action = "de_anonymization_stage"  # "play"
                msg.update({"tiles": pieces})

                msg.update(self.game.toJson())
                self.send_all(msg, sock)
                msgEncrypt = self.dh_keys[sock][2].cipher(encodeBase64(msg))
                return pickle.dumps(msgEncrypt)

            if sock == player.socket:
                if action == "encryptDeck":
                    self.game.deck.deck = data["deck"]
                    self.game.completeDeck = data[
                        "deck"]  # guarda o deck todo, para depois saber os tuplos escolhidos

                    # print("NEW_DECK:::",self.game.deck.deck)
                    self.game.nextPlayer()
                    msg = {"action": "rcv_game_propreties"}
                    if self.game.allEncriptDeck:
                        self.game.player_index = self.nplayers - 1
                        self.game.next_action = "get_piece"

                    msg = {"action": "rcv_game_propreties"}
                    msg.update(self.game.toJson())
                    self.send_all(msg, sock)

                elif action == "get_pieceInGame":
                    self.game.deck.deck = data["deck"]
                    player.updatePieces(1)
                    print("PECA--->", data["piece"])
                    self.playerGetPiece = sock
                    msg = {"action": "whatIsThisPiece", "piece": data["piece"]}
                    self.send_to_player(
                        msg,
                        self.game.players[self.playerIndexRevealKey].socket)
                    self.playerIndexRevealKey -= 1
                    return None

                elif action == "get_piece":  # tive que passar para fora do if do currentPlayer, pq pode ser qualquer um a mandar

                    #player.updatePieces(1)
                    self.playerGetPiece = None
                    self.playerIndexRevealKey = self.nplayers - 1
                    self.game.deck.deck = data["deck"]
                    print("GETPIECEDECK--->", len(self.game.deck.deck))

                    msg = {"action": "rcv_game_propreties"}
                    msg.update(self.game.toJson())
                    self.send_all(msg, sock)

                elif action == "tuploToPiece":
                    if "key" in data.keys(
                    ):  # o primeiro a encriptar seja a pedir peça in game
                        piece = self.game.decipherPiece(
                            data["piece"], data["key"])
                    print(data["tuplo"])
                    key, peca = self.game.reveal_piece(data["tuplo"])
                    msg = {
                        "action": "tuploToPiece",
                        "key": key,
                        "piece": peca,
                        "old_piece": data["tuplo"]
                    }
                    self.send_to_player(msg, sock)
                    return None

                elif action == "revelationStage":
                    keys = data["keys"]

                    self.game.decipherCompleteDeck(keys)

                    print("COMPLETEDECK--->", self.game.completeDeck)
                    self.game.previousPlayer()

                    msg = {
                        "action": "rcv_game_propreties",
                        "keys": keys,
                        "completeDeck": self.game.completeDeck
                    }
                    if self.game.allSendKeys:
                        self.game.next_action = "prep_stage"
                        # self.game.next_action = "play"
                        msg.update({'public_keys': self.game.public_keys_list})

                    msg.update(self.game.toJson())
                    self.send_all(msg, sock)

                elif action == "bitCommit":
                    self.game.commits[data["userData"][2]] = (
                        data["userData"][0], data["userData"][1])
                    self.game.nextPlayer()
                    msg = {"action": "rcv_game_propreties"}
                    self.game.next_action = "bitCommit"
                    if self.game.commitsDone():
                        print("COMMITS")
                        print(self.game.commits)
                        input("BIT COMMITS FEITOS - ENTER PARA CONTINUAR")
                        self.game.started = True
                        self.game.next_action = "revelationStage"  # "play"
                        msg.update({"completeDeck": self.game.completeDeck})
                        self.game.player_index = self.nplayers - 1
                    msg.update(self.game.toJson())
                    # self.send_to_player(msg,self.game.players[self.game.player_index].socket)
                    self.send_all(msg, sock)

                if action == "verifyBC":
                    r2 = data["userData"][0]

                    tiles = data["userData"][1]
                    pseudos = data["userData"][2]

                    tuploInicial = self.game.commits[data["userData"][3]]

                    novoBC = bitCommit(tuploInicial[0], r2, tiles)
                    novoValor = novoBC.value()

                    if (novoValor == tuploInicial[1]):
                        # VERIFICAR CADA PLAYED HAND COM CADA BIT COMMIT
                        # for p1 in pseudos:
                        #     print(self.game.reveal_piece(p1)[1])
                        #
                        # for p2 in player.playedHand:
                        #     print(p2)

                        for p in pseudos:
                            checks = False
                            peca = self.game.reveal_piece(p)[1]

                            for playeds in player.playedHand:
                                # print(peca)
                                # print(playeds)
                                if player.samePiece(peca, playeds):
                                    checks = True

                            if not checks:
                                input("FEZ BATOTA - PECAS NAO CORRESPONDENTES")
                                break

                        if checks:
                            msg = {
                                "action": "reg_points",
                                "winner": player.name
                            }
                            msg.update(self.game.toJson())
                            self.send_all(msg, sock)

                    else:
                        input("FEZ BATOTA - BC NAO CORRESPONDENTES")

                elif action == "prep_stage":
                    self.game.public_keys_list = data["public_keys"]
                    self.game.nextPlayer()

                    msg = {
                        "action": "rcv_game_propreties",
                        "public_keys": self.game.public_keys_list
                    }
                    # if self.game.check_added_to_public_list():
                    #     pieces = self.game.reveal_pieces()
                    #     self.game.next_action = "de_anonymization_stage"#"play"
                    #     msg.update({"tiles":pieces})

                    msg.update(self.game.toJson())
                    self.send_all(msg, sock)

                elif action == "de_anonymization_done":
                    self.game.next_action = "play"
                    self.game.player_index = 0
                    msg = {"action": "rcv_game_propreties"}
                    msg.update(self.game.toJson())
                    self.send_all(msg, sock)

                elif action == "play_piece":
                    if data["piece"] is not None:
                        player.nopiece = False
                        player.updatePieces(-1)
                        player.playedHand.append(data["piece"])
                        if data["edge"] == 0:
                            self.game.deck.in_table.insert(0, data["piece"])
                        else:
                            self.game.deck.in_table.insert(
                                len(self.game.deck.in_table), data["piece"])

                    print("player pieces ", player.num_pieces)
                    print("player " + player.name + " played " +
                          str(data["piece"]))
                    print("in table -> " +
                          ' '.join(map(str, self.game.deck.in_table)) + "\n")
                    print("deck -> " +
                          ' '.join(map(str, self.game.deck.deck)) + "\n")
                    if data["win"]:
                        if player.checkifWin():
                            print(Colors.BGreen + " WINNER " + player.name +
                                  Colors.Color_Off)
                            # msg = {"action": "end_game","winner":player.name}
                            # choice=input("Save points? (blank/n")
                            # if choice is "":
                            #     print("Reading card...")
                            #     serial=str(check_signature())
                            #     self.pseudos[serial]= player.name+"10"
                            #     print(self.pseudos[serial])

                            msg = {"action": "end_game", "winner": player.name}

                    else:
                        msg = {"action": "rcv_game_propreties"}
                        next_p = self.game.nextPlayer()

                    msg.update(self.game.toJson())
                    self.send_all(msg, sock)
                # no pieces to pick
                elif action == "pass_play":
                    self.game.nextPlayer()
                    # If the player passed the previous move
                    if player.nopiece:
                        print("No piece END")
                        msg = {
                            "action": "end_game",
                            "winner": Colors.BYellow + "TIE" + Colors.Color_Off
                        }
                    # Update the variable nopiece so that the server can know if the player has passed the previous move
                    else:
                        print("No piece")
                        player.nopiece = True
                        msg = {"action": "rcv_game_propreties"}
                        msg.update(self.game.toJson())

                    self.send_all(msg, sock)
                    msgEncrypt = self.dh_keys[sock][2].cipher(
                        encodeBase64(msg))
                    return pickle.dumps(msgEncrypt)
                # someone cheated
                elif action == "cheat_detected":
                    input("servidor cheat detected")
                    self.game.next_action = "cheat_detected"
                    msg = {
                        "action": "cheat_detected",
                        "cheater": data["cheater"]
                    }
                    msg.update(self.game.toJson())
                    self.send_all(msg, sock)

                elif action == "cheat_end_game":
                    self.signal_handler(None, None)

            else:
                msg = {
                    "action": "wait",
                    "msg": Colors.BRed + "Not Your Turn" + Colors.Color_Off
                }

            if msg is None:
                return None
            else:
                msgEncrypt = self.dh_keys[sock][2].cipher(encodeBase64(msg))
                return pickle.dumps(msgEncrypt)
Exemplo n.º 8
0
    def handle_data(self, data):
        data = pickle.loads(data)
        # print("DATA: ", data)
        print("")
        if "server" in self.dh_keys:
            data = decodeBase64(self.dh_keys['server'][2].decipher(data))
        action = data["action"]
        # print(data)
        print("\n" + action)
        if action == "KeyToPiecePlayer":
            key = data["key"]
            print("KEYTOPIECE", data["piece"])
            piece = self.player.decipherPiece(key, data["piece"])
            # if piece in self.player.keyMapDeck.keys():
            #     piece = self.player.decipherPiece(self.player.keyMapDeck[piece], piece,True)
            if isinstance(piece, tuple):
                self.player.pickingPiece = False
                msg = {
                    "action": "tuploToPiece",
                    "deck": self.player.deck,
                    "tuplo": piece
                }
                msgEncrypt = self.dh_keys['server'][2].cipher(
                    encodeBase64(msg))
                self.sock.send(pickle.dumps(msgEncrypt))

        if action == "whatIsThisPiece":
            # print("PECA;;;;",data["piece"])
            if data["piece"] in self.player.keyMapDeck.keys():
                msg = {
                    "action": "KeyToPiece",
                    "key": self.player.keyMapDeck[data["piece"]],
                    "piece": data["piece"]
                }
                if self.player.pickingPiece:
                    piece = self.player.decipherPiece(
                        self.player.keyMapDeck[data["piece"]], data["piece"])
                    msg.update({"sendKey": False})
                    if isinstance(piece, tuple):
                        self.player.pickingPiece = False
                        msg = {
                            "action": "tuploToPiece",
                            "deck": self.player.deck,
                            "key": self.player.keyMapDeck[data["piece"]],
                            "piece": data["piece"],
                            "tuplo": piece
                        }

                msgEncrypt = self.dh_keys['server'][2].cipher(
                    encodeBase64(msg))
                self.sock.send(pickle.dumps(msgEncrypt))

        if action == "tuploToPiece":
            print(data["piece"])
            self.player.traduçãotuplo_peca(data["key"], data["piece"])
            msg = {"action": "get_piece", "deck": self.player.deck}
            msgEncrypt = self.dh_keys['server'][2].cipher(encodeBase64(msg))
            self.sock.send(pickle.dumps(msgEncrypt))
            print("DONE")

        if action == "login":
            nickname = ''.join(
                random.choices(string.ascii_uppercase + string.digits,
                               k=4))  # input(data["msg"])
            print("Your name is " + Colors.BBlue + nickname + Colors.Color_Off)
            print("keyRecive", data["key"])
            # diffieHellman
            privateNumber = random.randint(1, 16)
            keyToSend = diffieHellman(self.sharedBase, privateNumber)
            sharedKey = diffieHellman(int(data["key"]), privateNumber)
            self.dh_keys['server'] = [
                privateNumber, sharedKey,
                SymCipher(str(sharedKey))
            ]
            print("SharedKey: ", sharedKey)
            msg = {"action": "req_login", "msg": nickname, "key": keyToSend}
            self.player = Player(nickname, self.sock)
            self.sock.send(pickle.dumps(msg))
            return
            # todo login
        elif action == "you_host":
            self.player.host = True
        elif action == "new_player":
            print(data["msg"])
            nome = data["msg"].split(" ")[2]
            if nome != self.player.name:
                # diffieHellman
                privateNumber = random.randint(1, 16)
                keyToSend = diffieHellman(self.sharedBase, privateNumber)

                self.dh_keys[nome] = [privateNumber]

                msg = {
                    "action": "TalkToPlayer",
                    "actionPlayer": "openSession",
                    "msg": "Hello",
                    "key": keyToSend,
                    "from": self.player.name,
                    "to": nome
                }
                msgEncrypt = self.dh_keys['server'][2].cipher(
                    encodeBase64(msg))
                self.sock.send(pickle.dumps(msgEncrypt))
            print("There are " + str(data["nplayers"]) + "\\" +
                  str(data["game_players"]))

        elif action == "waiting_for_host":
            if self.player.host:
                input(Colors.BGreen + "PRESS ENTER TO START THE GAME" +
                      Colors.Color_Off)
                msg = {"action": "start_game"}
                msgEncrypt = self.dh_keys['server'][2].cipher(
                    encodeBase64(msg))
                self.sock.send(pickle.dumps(msgEncrypt))
                print("Sent ", msg)
            else:
                print(data["msg"])

        elif action == "TalkToPlayer":
            # print("DATA_PlayerAntes:", data)
            player = data["from"]  # quem mandou a mensagem
            if data["from"] in self.dh_keys.keys():
                if len(self.dh_keys[data["from"]]) == 3:
                    data = decodeBase64(self.dh_keys[data["from"]][2].decipher(
                        data["msg"]))
            print("DATA_Player:", data)
            actionPlayer = data["actionPlayer"]

            if actionPlayer == "openSession":

                if player not in self.dh_keys.keys():
                    # diffieHellman
                    privateNumber = random.randint(1, 16)
                    keyToSend = diffieHellman(self.sharedBase, privateNumber)
                    keyRecevied = int(data["key"])
                    print("Key recebida: ", keyRecevied)
                    sharedKey = diffieHellman(keyRecevied, privateNumber)
                    self.dh_keys[player] = [
                        privateNumber, sharedKey,
                        SymCipher(str(sharedKey))
                    ]
                    msg = {
                        "action": "TalkToPlayer",
                        "actionPlayer": "openSession",
                        "msg": "Hello",
                        "key": keyToSend,
                        "from": self.player.name,
                        "to": player
                    }
                    msgEncrypt = self.dh_keys['server'][2].cipher(
                        encodeBase64(msg))
                    self.sock.send(pickle.dumps(msgEncrypt))
                else:
                    keyRecevied = int(data["key"])
                    print("Key recebida: ", keyRecevied)
                    sharedKey = diffieHellman(keyRecevied,
                                              self.dh_keys[player][0])
                    self.dh_keys[player].append(sharedKey)
                    self.dh_keys[player].append(SymCipher(str(sharedKey)))
                    msgToPlayer = {
                        "actionPlayer": "SessionEstabelicida",
                        "msg": "WE GUICCI"
                    }
                    msgToPlayerEncrypt = self.dh_keys[player][2].cipher(
                        encodeBase64(msgToPlayer))
                    msg = {
                        "action": "TalkToPlayer",
                        "msg": msgToPlayerEncrypt,
                        "from": self.player.name,
                        "to": player
                    }
                    msgEncrypt = self.dh_keys['server'][2].cipher(
                        encodeBase64(msg))
                    self.sock.send(pickle.dumps(msgEncrypt))

            if actionPlayer == "SessionEstabelicida":
                print("Sessao Estabecida com ", player)

            if actionPlayer == "get_piece":
                self.player.deck = data["deck"]
                #print(self.dh_keys)
                #input("TESTE")

                if len(data["deck"]) == (
                        28 - self.player.pieces_per_player *
                        self.player.nplayers):  #todas já apanharam as pecas
                    msg = {
                        "action": "selectionStage_end",
                        "deck": self.player.deck
                    }
                else:
                    if not self.player.ready_to_play:
                        self.player.get_piece()
                    toPlayer = random.choice(
                        [x for x in self.dh_keys if x != "server"])
                    print("TOPLAYER", toPlayer)
                    msgToPlayer = {
                        "actionPlayer": "get_piece",
                        "deck": self.player.deck
                    }
                    msgToPlayerEncrypt = self.dh_keys[toPlayer][2].cipher(
                        encodeBase64(msgToPlayer))
                    msg = {
                        "action": "TalkToPlayer",
                        "msg": msgToPlayerEncrypt,
                        "from": self.player.name,
                        "to": toPlayer
                    }
                msgEncrypt = self.dh_keys['server'][2].cipher(
                    encodeBase64(msg))
                self.sock.send(pickle.dumps(msgEncrypt))

            if actionPlayer == "prep_stage":
                print("prep")
                self.player.public_keys_list = data["public_keys"]

                if self.player.check_added_to_public_list():
                    msg = {
                        "action": "prep_stage_end",
                        "public_keys": self.player.public_keys_list
                    }

                else:
                    if self.player.check_added_piece():
                        print("checks passed")
                        public_keys_list = self.player.preparation()

                    toPlayer = random.choice(
                        [x for x in self.dh_keys if x != "server"])
                    print("TOPLAYER", toPlayer)
                    msgToPlayer = {
                        "actionPlayer": "prep_stage",
                        "public_keys": self.player.public_keys_list
                    }
                    msgToPlayerEncrypt = self.dh_keys[toPlayer][2].cipher(
                        encodeBase64(msgToPlayer))
                    msg = {
                        "action": "TalkToPlayer",
                        "msg": msgToPlayerEncrypt,
                        "from": self.player.name,
                        "to": toPlayer
                    }
                msgEncrypt = self.dh_keys['server'][2].cipher(
                    encodeBase64(msg))
                self.sock.send(pickle.dumps(msgEncrypt))

        elif action == "host_start_game":
            print(data["msg"])
            msg = {"action": "get_game_propreties"}
            msgEncrypt = self.dh_keys['server'][2].cipher(encodeBase64(msg))
            self.sock.send(pickle.dumps(msgEncrypt))
            print("Sent ", msg)

        elif action == "cheat_detected":
            print("CHEAT DETECTED -> " + data["cheater"])
            msg = {"action": "cheat_end_game"}
            msgEncrypt = self.dh_keys['server'][2].cipher(encodeBase64(msg))
            self.sock.send(pickle.dumps(msgEncrypt))

        elif action == "rcv_game_propreties":
            self.player.nplayers = data["nplayers"]
            self.player.npieces = data["npieces"]
            self.player.pieces_per_player = data["pieces_per_player"]
            self.player.in_table = data["in_table"]
            self.player.deck = data["deck"]
            player_name = data["next_player"]

            if data["next_player"] == self.player.name:
                player_name = Colors.BRed + "YOU" + Colors.Color_Off
            # print("deck -> " + ' '.join(map(str, self.player.deck)) + "\n")
            # print("hand -> " + ' '.join(map(str, self.player.hand)))

            print("in table -> " + ' '.join(map(str, data["in_table"])) + "\n")
            print("Current player ->", player_name)
            print("next Action ->", data["next_action"])
            print("hand ->", self.player.hand)
            print("player score -> ", self.player.score)

            if "keys" in data.keys():
                self.player.decipherHand(data["keys"])
                self.chaves.update(data["keys"])

            if data["next_action"] == "de_anonymization_stage":
                self.player.de_anonymization_hand(data["tiles"])

            if self.player.name == data["next_player"]:

                if data["next_action"] == "encryptDeck":
                    new_deck = self.player.encryptDeck(data["deck"])
                    random.shuffle(new_deck)  # reordena o baralho
                    # print("NEW_DECK:::", new_deck)
                    msg = {"action": "encryptDeck", "deck": new_deck}
                    msgEncrypt = self.dh_keys['server'][2].cipher(
                        encodeBase64(msg))
                    self.sock.send(pickle.dumps(msgEncrypt))

                if data["next_action"] == "get_piece":
                    #print(self.dh_keys)
                    #input("TESTE")

                    if not self.player.ready_to_play:

                        self.player.get_piece()

                    toPlayer = random.choice(
                        [x for x in self.dh_keys if x != "server"])
                    print("TOPLAYER", toPlayer)
                    msgToPlayer = {
                        "actionPlayer": "get_piece",
                        "deck": self.player.deck
                    }
                    msgToPlayerEncrypt = self.dh_keys[toPlayer][2].cipher(
                        encodeBase64(msgToPlayer))
                    msg = {
                        "action": "TalkToPlayer",
                        "msg": msgToPlayerEncrypt,
                        "from": self.player.name,
                        "to": toPlayer
                    }
                    msgEncrypt = self.dh_keys['server'][2].cipher(
                        encodeBase64(msg))
                    self.sock.send(pickle.dumps(msgEncrypt))

                if data["next_action"] == "bitCommit":
                    tiles = self.player.hand
                    print("aqui")
                    R1 = random.randint(0, 1023)
                    R2 = random.randint(0, 1023)
                    com = bitCommit(R1, R2, tiles)
                    bitC = com.value()
                    self.player.bc = com
                    self.R1 = R1
                    print("aqui tbem")

                    msg = {
                        "action": "bitCommit",
                        "userData": (R1, bitC, self.player.name)
                    }
                    msgEncrypt = self.dh_keys['server'][2].cipher(
                        encodeBase64(msg))
                    print("e aqui")

                    self.sock.send(pickle.dumps(msgEncrypt))

                if data["next_action"] == "revelationStage":
                    print("CompleteDeck--->", len(data["completeDeck"]))
                    print("hand -> " + ' '.join(map(str, self.player.hand)))
                    # print("Deck--->", len(data["deck"]))

                    tilesInHands = [
                        tile for tile in data["completeDeck"]
                        if tile not in data["deck"]
                    ]
                    print("tilesHands--->", len(tilesInHands))

                    keys = {
                        encrypt: key
                        for (encrypt, key) in self.player.keyMapDeck.items()
                        if encrypt in tilesInHands
                    }
                    self.chaves.update(keys)
                    # print("Keys --->", keys)
                    self.player.decipherHand(keys)
                    # input("Press ENter \n\n")
                    msg = {"action": "revelationStage", "keys": keys}
                    msgEncrypt = self.dh_keys['server'][2].cipher(
                        encodeBase64(msg))
                    self.sock.send(pickle.dumps(msgEncrypt))

                if data["next_action"] == "prep_stage":
                    print("prep")
                    self.player.public_keys_list = data["public_keys"]
                    if self.player.check_added_piece():
                        print("checks passed")
                        public_keys_list = self.player.preparation()

                    toPlayer = random.choice(
                        [x for x in self.dh_keys if x != "server"])
                    print("TOPLAYER", toPlayer)
                    msgToPlayer = {
                        "actionPlayer": "prep_stage",
                        "public_keys": self.player.public_keys_list
                    }
                    msgToPlayerEncrypt = self.dh_keys[toPlayer][2].cipher(
                        encodeBase64(msgToPlayer))
                    msg = {
                        "action": "TalkToPlayer",
                        "msg": msgToPlayerEncrypt,
                        "from": self.player.name,
                        "to": toPlayer
                    }
                    msgEncrypt = self.dh_keys['server'][2].cipher(
                        encodeBase64(msg))
                    self.sock.send(pickle.dumps(msgEncrypt))

                if data["next_action"] == "de_anonymization_stage":
                    # self.player.de_anonymization_hand(data["tiles"])
                    msg = {"action": "de_anonymization_done", "status": "done"}
                    msgEncrypt = self.dh_keys['server'][2].cipher(
                        encodeBase64(msg))
                    self.sock.send(pickle.dumps(msgEncrypt))

                if data["next_action"] == "play":
                    # print("MAO--->",self.player.hand)
                    # input("Enter\n\n\n")
                    # input(Colors.BGreen+"Press ENter \n\n"+Colors.Color_Off)
                    # print("HAND----->",self.player.hand)
                    msg = self.player.play()
                    msgEncrypt = self.dh_keys['server'][2].cipher(
                        encodeBase64(msg))
                    self.sock.send(pickle.dumps(msgEncrypt))

            # caso nao seja a vez guarda o nome do jogador
            else:
                self.player.previousPlayer = data["next_player"]

        elif action == "end_game":

            winner = data["winner"]
            if data["winner"] == self.player.name:
                self.player.score += 100
                count = 0
                pseudonimos = []

                for a in self.player.bc.tiles:
                    for key, value in self.chaves.items():
                        if key == a:
                            a = self.player.decipherToTuple(value, a)

                    pseudonimos.append(a)

                for p in pseudonimos:
                    print(p)

                tup = (self.player.bc.float2, self.player.bc.tiles,
                       pseudonimos, self.player.name)

                msg = {"action": "verifyBC", "userData": tup}
                msgEncrypt = self.dh_keys['server'][2].cipher(
                    encodeBase64(msg))
                self.sock.send(pickle.dumps(msgEncrypt))

        elif action == "reg_points":

            if data["winner"] == self.player.name:
                winner = Colors.BRed + "YOU" + Colors.Color_Off
                choice = input("Save points? (blank/n")

                if choice is "":
                    print("Reading card...")
                    serial = getSerial()
                    msg = {
                        "action": "reg_points",
                        "msg": (serial, self.player.score, self.player.name)
                    }
                    msgEncrypt = self.dh_keys['server'][2].cipher(
                        encodeBase64(msg))
                    self.sock.send(pickle.dumps(msgEncrypt))
            else:
                winner = Colors.BBlue + data["winner"] + Colors.Color_Off
                choice = input("Save points? (blank/n")

                if choice is "":
                    print("Reading card...")
                    serial = getSerial()
                    msg = {
                        "action": "reg_points",
                        "msg": (serial, self.player.score, self.player.name)
                    }
                    msgEncrypt = self.dh_keys['server'][2].cipher(
                        encodeBase64(msg))
                    self.sock.send(pickle.dumps(msgEncrypt))

            print(Colors.BGreen + "End GAME, THE WINNER IS: " + winner)

        elif action == "wait":
            print(data["msg"])

        elif action == "disconnect":
            self.sock.close()
            print("PRESS ANY KEY TO EXIT ")
            sys.exit(0)