-
Notifications
You must be signed in to change notification settings - Fork 0
/
domino.py
503 lines (400 loc) · 16.1 KB
/
domino.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
import random
import secrets
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives import padding
import os
class Player:
def __init__( self, pid, socket, npiecesplayer=0 ):
self.pid = pid
self.socket = socket
self.hand = {}
self.decryptedhand = {}
self.stock = []
self.score = 0
self.npiecesplayer = npiecesplayer
self.ready = False
self.map = {}
self.pseuddecryptedhand = {}
self.pseuddecryptedhandINIT = {}
self.tilesplayed = []
self.log = []
def select_piece( self ):
if not self.ready and self.npieces == self.npiecesplayer:
self.ready = True
class Domino:
def __init__( self, npiecesplayer=0 ):
# needed ?
self.npiecesplayer = npiecesplayer
self.nplayers = 0
self.playerlist = []
self.board = []
self.dominoset = [(6,6),(6,5),(6,4),(6,3),(6,2),(6,1),(6,0),
(5,5),(5,4),(5,3),(5,2),(5,1),(5,0),
(4,4),(4,3),(4,2),(4,1),(4,0),
(3,3),(3,2),(3,1),(3,0),
(2,2),(2,1),(2,0),
(1,1),(1,0),
(0,0)]
self.fakedominoset = [('7','7'),('7','6'),('7','5'),('7','4'),('7','3'),('7','2'),('7','1'),('7','0'),
('6','6'),('6','5'),('6','4'),('6','3'),('6','2'),('6','1'),('6','0'),
('5','5'),('5','4'),('5','3'),('5','2'),('5','1'),('5','0'),
('4','4'),('4','3'),('4','2'),('4','1'),('4','0'),
('3','3'),('3','2'),('3','1'),('3','0'),
('2','2'),('2','1'),('2','0'),
('1','1'),('1','0'),
('0','0')]
self.stock = []
self.playerorder = []
self.currentplayer = ""
self.pseudonymMap = {}
self.pseudonymKeys = {}
self.savepseudonyms = {}
self.map1 = {}
self.map2 = {}
self.map3 = {}
self.map4 = {}
# GAME VARS
self.log1 = []
self.log2 = []
self.log3 = []
self.log4 = []
def writeDecypher(self, outfile, content):
fout = open(outfile, 'wb')
fout.write(content)
fout.close()
def readDecypher(self, outfile):
fout = open(outfile, 'rb')
data = fout.read()
#print("\n\nDATAAAAAAAAAAAAAA")
#print(data)
fout.close()
return data
###########################################################################################
# codigo comum maybe
###########################################################################################
def hashPseudonym(self, i, key, tile):
digest = hashes.Hash(hashes.SHA256(), default_backend() )
# for i in range (0,len(plainTail)): # {
_digest = digest.copy()
# key = secrets.token_bytes(32)
_digest.update(bytes(i))
_digest.update(key)
_digest.update(bytes(tile))
p = _digest.finalize() # }
# digest.finalize()
return p
def aesCypher(self, content, key, firstencription):
nonce = secrets.token_bytes(12)
if (firstencription == True):
ciphertext = nonce + AESGCM(key).encrypt(nonce, bytes(str(content), encoding='utf-8'), b"")
else:
ciphertext = nonce + AESGCM(key).encrypt(nonce, content, b"")
return ciphertext
def aesDecypher(self, content, key):
# print("content[:12]", content[:12])
# print("content[12:]", content[12:])
return AESGCM(key).decrypt(content[:12], content[12:], b"")
def genPwdKey(self, pwd):
salt = b'\r00'
kdf = PBKDF2HMAC(hashes.SHA1(), 16, salt, 1000, default_backend())
return kdf.derive(bytes(pwd, 'UTF-8'))
def gen28keys(self):
pwds = [] # passwords
keys = []
duplicates = True
while(duplicates):
pwds = random.sample(range(100,999),28)
# teste para 2 chaves duplicadas
# pwds = [113, 545, 802, 101, 393, 385, 720, 729, 873, 660, 813, 762, 259, 186, 186, 430, 909, 769, 946, 686, 665, 549, 747, 355, 898, 731, 787, 571]
duplicates = any(pwds.count(element) > 1 for element in pwds)
# print("duplicates? ")
# print(bool(duplicates))
# print("\npwds")
# print(pwds)
for pwd in pwds:
keys.append( self.genPwdKey(str(pwd)) )
# print(keys)
# keys é o conjunto das 28 chaves
return keys
# old method
# return [113, 545, 802, 101, 393, 385, 720, 729, 873, 660, 813, 762, 259, 186, 186, 430, 909, 769, 946, 686, 665, 549, 747, 355, 898, 731, 787, 571]
###########################################################################################
# codigo servidor
###########################################################################################
def stagePseudonymization(self):
# print("eu to vivo\n")
keyset = self.gen28keys()
for i in range(len(self.dominoset)):
tile = self.dominoset[i]
key = keyset[i]
# GERAR PSEUDONIMOOOOOOO
# newvalue = self.pseudonymize(i, key, tile)
newvalue = self.hashPseudonym(i, key, tile)
self.dominoset[i] = i,newvalue # este e o deck que vai ser enviado para a fase de randomizacao
# self.pseudonymMap[str(newvalue)] = tile
self.pseudonymKeys[newvalue] = key
self.pseudonymMap[newvalue] = tile
self.savepseudonyms[i] = newvalue
self.dominoset = dict(self.dominoset)
def pseudonymize(self, i, key, tile):
# funcao toda mamada para criar pseudonimo
# mas por agora apenas uma ceninha simples
return i*2 + 1*1000 + tile[0]*10 + tile[1]*100
###########################################################################################
# codigo cliente
###########################################################################################
def stageRandomization(self, map, firstencription):
# print("eu to vivo\n")
# keyset = self.gen28keys()
dominoset_view = self.dominoset.values()
value_iterator = iter(dominoset_view)
newdominoset = {}
for index, pseudonym in self.dominoset.items():
# key = keyset.pop()
key = secrets.token_bytes(32)
newindex = self.aesCypher( index, key, firstencription )
newpseud = self.aesCypher( pseudonym, key, firstencription )
newdominoset[newindex] = newpseud
map[(newindex,newpseud)] = key
# print("\nmapa:")
# print(map)
# print("\nencriptado:")
# print(newdominoset)
newdominoset = list(newdominoset.items())
random.shuffle(newdominoset)
newdominoset = dict(newdominoset)
# print("\nshuffled:")
# print(newdominoset)
self.dominoset = newdominoset.copy()
###########################################################################################
# codigo palha
###########################################################################################
def assignPiece(self, piece, playerid):
# example -> piece = (5,2), playerid = 1
for player in self.playerlist:
if player.id == playerid:
player.hand.append(piece)
def execute_draw_phase(self):
playercount = len(self.playerlist)
for i in range(playercount):
player_highestdouble = -1
highestdouble = (-1,-1)
player_highestdomino = -1
highestdomino = (-1,-1)
for player in self.playerlist:
if not (player.id in playerorder):
for piece in player.hand:
if isDouble(piece):
if piece == compareDoubles(piece, highestdouble):
highestdouble = piece
player_highestdouble = player.id
else:
if piece == compareDominos(piece, highestdomino):
highestdomino = piece
player_highestdomino = player.id
if highestdouble != (-1,-1):
playerorder.append(player_highestdouble)
elif highestdomino != (-1,-1):
playerorder.append(player_highestdomino)
self.currentplayerid = playerorder[0]
def placePiece(self, side, piece):
if side=="left":
self.board.insert(0, piece)
else:
self.board.append(piece)
print("\n\n----------------------------------------------------------\n\nBoard",self.board,"\n\n")
self.updateTurn()
def updateTurn(self):
nextplayer = self.playerorder.pop()
self.playerorder.insert(0, nextplayer)
return nextplayer
###########################################################################################
# funcoes auxiliares
###########################################################################################
def pieceSum(piece):
# returns the number of dots in a piece
return piece[0] + piece[1]
def compareDominos(piece1, piece2):
# returns the domino with most dots
# if they have the same number of dots -> (5,0) better than (4,1)
if pieceSum(piece1) > pieceSum(piece2):
return piece1
elif pieceSum(piece1) < pieceSum(piece2):
return piece2
else:
if piece1[0] > piece2[0]:
return piece1
return piece2
def compareDoubles(piece1, piece2):
# returns highest double
if piece1[0] > piece2[0]:
return piece1
return piece2
def isDouble(piece):
# checks if a piece is a double
if piece[0] == piece[1]:
return True
return False
###########################################################################################
# main
###########################################################################################
def autoRun():
player1 = Player(id=1)
player2 = Player(id=2)
player3 = Player(id=3)
player4 = Player(id=4)
game = GameEngine([player1,player2,player3,player4],5)
print(game.dominoset)
game.stagePseudonymization()
print("\nCRIACAO DE PSEUDONIMOS")
print(game.dominoset)
game.stageRandomization(game.map1, True)
# print("\nRANDOMIZACAO JOGADOR 1")
# print(game.dominoset)
game.stageRandomization(game.map2, False)
# print("\nRANDOMIZACAO JOGADOR 2")
# print(game.dominoset)
game.stageRandomization(game.map3, False)
# print("\nRANDOMIZACAO JOGADOR 3")
# print(game.dominoset)
game.stageRandomization(game.map4, False)
# print("\nRANDOMIZACAO JOGADOR 4")
# print(game.dominoset)
print("quero decriptar este tuplo")
keyword = next(iter(game.dominoset))
print("index --->>>\n", keyword)
print("pseud --->>>\n", game.dominoset[keyword])
# print(game.map4)
def writeDecypher(outfile, content):
fout = open(outfile, 'wb')
fout.write(content)
fout.close()
def readDecypher(outfile):
fout = open(outfile, 'rb')
data = fout.read()
#print("\n\nDATAAAAAAAAAAAAAA")
#print(data)
fout.close()
return data
i = keyword
ti = game.dominoset[keyword]
for c, key in game.map4.items():
index = c[0]
pseud = c[1]
if(index == i and pseud == ti):
print("\n\nENCONTREI O TUPLO QUE EU QUERO DECIFRAR")
print(c)
print("\nA CHAVE CORRESPONDENTE")
print(key)
writeDecypher("tmp_i.txt", index)
writeDecypher("tmp_p.txt", pseud)
i = game.aesDecypher(index, key)
# i = game.aesDecypher("tmp_i.txt", key)
# decipherout.txt -> i
# i = readDecypher("decipherout.txt")
ti = game.aesDecypher(pseud, key)
# ti = game.aesDecypher("tmp_p.txt", key)
# decipherout.txt -> ti
#ti = readDecypher("decipherout.txt")
print("\nINDEX QUE EU QUERO ENCONTRAR NO MAPA 3")
print(i)
print("PSEUDONIMO TAL TAL TAL")
print(ti)
break
# print("\n\nMAPAAAAA\n")
# print(game.map3)
for c, key in game.map3.items():
index = c[0]
pseud = c[1]
if(index == i and pseud == ti):
print("c",c,"key",key)
writeDecypher("tmp_i.txt", index)
writeDecypher("tmp_p.txt", pseud)
i = game.aesDecypher(index, key)
# i = game.aesDecypher("tmp_i.txt", key)
# decipherout.txt -> i
# i = readDecypher("decipherout.txt")
ti = game.aesDecypher(pseud, key)
# ti = game.aesDecypher("tmp_p.txt", key)
# decipherout.txt -> ti
#ti = readDecypher("decipherout.txt")
print("index",i,"pseud",ti)
break
for c, key in game.map2.items():
index = c[0]
pseud = c[1]
if(index == i and pseud == ti):
print("c",c,"key",key)
writeDecypher("tmp_i.txt", index)
writeDecypher("tmp_p.txt", pseud)
i = game.aesDecypher(index, key)
# i = game.aesDecypher("tmp_i.txt", key)
# decipherout.txt -> i
# i = readDecypher("decipherout.txt")
ti = game.aesDecypher(pseud, key)
# ti = game.aesDecypher("tmp_p.txt", key)
# decipherout.txt -> ti
#ti = readDecypher("decipherout.txt")
print("index",i,"pseud",ti)
break
for c, key in game.map1.items():
index = c[0]
pseud = c[1]
if(index == i and pseud == ti):
print("c",c,"key",key)
writeDecypher("tmp_i.txt", index)
writeDecypher("tmp_p.txt", pseud)
i = game.aesDecypher(index, key).decode()
# i = game.aesDecypher("tmp_i.txt", key)
# decipherout.txt -> i
# i = readDecypher("decipherout.txt")
ti = game.aesDecypher(pseud, key).decode()
# ti = game.aesDecypher("tmp_p.txt", key)
# decipherout.txt -> ti
#ti = readDecypher("decipherout.txt")
print("index",i,"pseud",ti)
break
print("\nciphering text \"123\"")
key1 = secrets.token_bytes(32)
bytes1 = game.aesCypher(123, key1, True)
print("bytes1", bytes1)
key2 = secrets.token_bytes(32)
bytes2 = game.aesCypher(bytes1, key2, False)
print("bytes2", bytes2)
print("\ndecyphering bytes2")
bytes1 = game.aesDecypher(bytes2, key2)
print("bytes1", bytes1)
print("\ndecyphering bytes1")
text = game.aesDecypher(bytes1, key1).decode()
print("text", text)
# game.assignPiece((6,0),1)
# game.assignPiece((5,4),1)
# game.assignPiece((4,2),1)
# game.assignPiece((3,0),1)
# game.assignPiece((6,5),1)
# print("player1",player1.hand)
# player2.hand = [(5,0),(4,3),(6,3),(5,3),(4,1)]
# player3.hand = [(4,0),(3,2),(2,0),(6,4),(5,2)]
# player4.hand = [(3,1),(2,1),(5,1),(1,0),(6,2)]
# print("player2",player2.hand)
# print("player3",player3.hand)
# print("player4",player4.hand)
# game.execute_draw_phase()
# print("player turn order",game.playerorder)
# while(True):
# for player in game.playerlist:
# if player.id == game.currentplayerid:
# currentplayer = player
# print("Hand",currentplayer.hand)
# print("Piece from 0 -",len(currentplayer.hand)-1," ?")
# piece = currentplayer.hand[int(input())]
# side = input("Side? [left/right] ")
# game.placePiece(side, piece)
#def main():
# autoRun()
#if __name__ == "__main__":
# main()