def Bob(alice, args): global NAME NAME = "Bob" A, C, prime = alice.recv() H = alice.recv() print(log("Получены Hi")) B = [] N = alice.recv() r = set() while len(r) != args.n: r.add(random.randint(2, N // 2)) r = list(r) random.shuffle(r) r = r[:20] Z = [pow(i, 2, N) for i in r] print( log("Сгенерировано {} Z=r^2 (mod N) квадратичных вычетов".format( args.n))) alice.send(Z) rb = alice.recv() B = [1 if rb[i] == r[i] else 0 for i in range(args.n)] K = -1 for i in range(args.n): if B[i]: K = i break print(log("На основе ответов Алисы сгенерированы биты B")) alice.send(B) alice.send(r) if alice.recv(): return M = alice.recv() print(log("Начинаем проверку утверждений")) print(log("если Bi = 0, то A^Mi = Hi (mod prime)")) print(log("если Bi = 1, то A^Mi = Hi*Hj^-1 (mod prime)")) ANS = [] for i in range(args.n): if B[i]: ANS.append( pow(A, M[i], prime) == ((H[i] * reverse(H[K], prime)) % prime)) else: ANS.append(pow(A, M[i], prime) == (H[i] % prime)) print(log("ANS: {}".format(ANS))) Z = alice.recv() FINAL = (pow(A, Z, prime) == (C * reverse(H[K], prime)) % prime) if False not in ANS and FINAL: print( log("FINAL={} Я уверен что Алиса знает X с вероятностью {:03f}". format(FINAL, 1 - 1 / (2**args.n))))
def reinforce(self, positions): p = [] k = [] for i in range(len(positions)): if not positions[i]: p.append(i) for i in self.pweights: if i in p: k.append(i) random.shuffle(k) j = 0 for i in range(len(self.pweights)): if self.pweights[i] in k: self.pweights[i] = k[j] j += 1
def Alice(bob, KEY, args): global NAME NAME = "Alice" net = NeuralNet(KEY) MESS = [i for i in range(256)] random.shuffle(MESS) MESS = bytes(MESS) print(log("Отправляем зашифрованное сетью секретное сообщение")) DMESS = net.encrypt(MESS) bob.send(DMESS) while True: DMESS = bob.recv() positions = NeuralNet.analise(MESS, DMESS) bob.send(positions) if False not in positions: break bob.recv() print(log("Все биты совпали, сеть готова для шифрования"))
def Alice(bob, eva, args): global NAME NAME = "Alice" print( log("Генерируем {} сообщений шифруя {}-bit ключом".format( args.n, args.b))) blocks = [] keys = [] for i in range(args.n): key = Random.new().read(32) keys.append(key) M = "MESSAGE X={} KEY={}".format(i, key) M = M.encode("utf-8") M += (32 - len(M) % 32) * b'\0' blockkey = Random.new().read(args.b // 8) if args.b % 8: a = 0 b = 1 for j in range(args.b % 8): a ^= b b <<= 1 blockkey += (Random.new().read(1)[0] & a).to_bytes(1, "little") blockkey += (32 - len(blockkey)) * b"\0" cipher = AES.new(blockkey, 1) blocks.append(cipher.encrypt(M)) random.shuffle(blocks) print(log("Публикуем сгенерированные сообщения")) bob.put(blocks) eva.put(blocks) while not bob.empty(): pass M = bob.get() print( log("Получено секретное сообщение от Боба с ключом номер {}\n M: {}". format(*M))) cipher = AES.new(keys[M[0]], 1) M = cipher.decrypt(M[1]) for i in range(len(M) - 1, 0, -1): if M[i] != 0: break M = M[:i + 1].decode("utf-8") print(log("M: {}".format(M)))
def runTest(self): """Cryptodome.Random.new()""" # Import the Random module and try to use it from Cryptodome import Random randobj = Random.new() x = randobj.read(16) y = randobj.read(16) self.assertNotEqual(x, y) z = Random.get_random_bytes(16) self.assertNotEqual(x, z) self.assertNotEqual(y, z) # Test the Random.random module, which # implements a subset of Python's random API # Not implemented: # seed(), getstate(), setstate(), jumpahead() # random(), uniform(), triangular(), betavariate() # expovariate(), gammavariate(), gauss(), # longnormvariate(), normalvariate(), # vonmisesvariate(), paretovariate() # weibullvariate() # WichmannHill(), whseed(), SystemRandom() from Cryptodome.Random import random x = random.getrandbits(16 * 8) y = random.getrandbits(16 * 8) self.assertNotEqual(x, y) # Test randrange if x > y: start = y stop = x else: start = x stop = y for step in range(1, 10): x = random.randrange(start, stop, step) y = random.randrange(start, stop, step) self.assertNotEqual(x, y) self.assertEqual(start <= x < stop, True) self.assertEqual(start <= y < stop, True) self.assertEqual((x - start) % step, 0) self.assertEqual((y - start) % step, 0) for i in range(10): self.assertEqual(random.randrange(1, 2), 1) self.assertRaises(ValueError, random.randrange, start, start) self.assertRaises(ValueError, random.randrange, stop, start, step) self.assertRaises(TypeError, random.randrange, start, stop, step, step) self.assertRaises(TypeError, random.randrange, start, stop, "1") self.assertRaises(TypeError, random.randrange, "1", stop, step) self.assertRaises(TypeError, random.randrange, 1, "2", step) self.assertRaises(ValueError, random.randrange, start, stop, 0) # Test randint x = random.randint(start, stop) y = random.randint(start, stop) self.assertNotEqual(x, y) self.assertEqual(start <= x <= stop, True) self.assertEqual(start <= y <= stop, True) for i in range(10): self.assertEqual(random.randint(1, 1), 1) self.assertRaises(ValueError, random.randint, stop, start) self.assertRaises(TypeError, random.randint, start, stop, step) self.assertRaises(TypeError, random.randint, "1", stop) self.assertRaises(TypeError, random.randint, 1, "2") # Test choice seq = range(10000) x = random.choice(seq) y = random.choice(seq) self.assertNotEqual(x, y) self.assertEqual(x in seq, True) self.assertEqual(y in seq, True) for i in range(10): self.assertEqual(random.choice((1, 2, 3)) in (1, 2, 3), True) self.assertEqual(random.choice([1, 2, 3]) in [1, 2, 3], True) if sys.version_info[0] is 3: self.assertEqual( random.choice(bytearray(b('123'))) in bytearray(b('123')), True) self.assertEqual(1, random.choice([1])) self.assertRaises(IndexError, random.choice, []) self.assertRaises(TypeError, random.choice, 1) # Test shuffle. Lacks random parameter to specify function. # Make copies of seq seq = range(500) x = list(seq) y = list(seq) random.shuffle(x) random.shuffle(y) self.assertNotEqual(x, y) self.assertEqual(len(seq), len(x)) self.assertEqual(len(seq), len(y)) for i in range(len(seq)): self.assertEqual(x[i] in seq, True) self.assertEqual(y[i] in seq, True) self.assertEqual(seq[i] in x, True) self.assertEqual(seq[i] in y, True) z = [1] random.shuffle(z) self.assertEqual(z, [1]) if sys.version_info[0] == 3: z = bytearray(b('12')) random.shuffle(z) self.assertEqual(b('1') in z, True) self.assertRaises(TypeError, random.shuffle, b('12')) self.assertRaises(TypeError, random.shuffle, 1) self.assertRaises(TypeError, random.shuffle, "11") self.assertRaises(TypeError, random.shuffle, (1, 2)) # 2to3 wraps a list() around it, alas - but I want to shoot # myself in the foot here! :D # if sys.version_info[0] == 3: # self.assertRaises(TypeError, random.shuffle, range(3)) # Test sample x = random.sample(seq, 20) y = random.sample(seq, 20) self.assertNotEqual(x, y) for i in range(20): self.assertEqual(x[i] in seq, True) self.assertEqual(y[i] in seq, True) z = random.sample([1], 1) self.assertEqual(z, [1]) z = random.sample((1, 2, 3), 1) self.assertEqual(z[0] in (1, 2, 3), True) z = random.sample("123", 1) self.assertEqual(z[0] in "123", True) z = random.sample(range(3), 1) self.assertEqual(z[0] in range(3), True) if sys.version_info[0] == 3: z = random.sample(b("123"), 1) self.assertEqual(z[0] in b("123"), True) z = random.sample(bytearray(b("123")), 1) self.assertEqual(z[0] in bytearray(b("123")), True) self.assertRaises(TypeError, random.sample, 1)
def runTest(self): """Cryptodome.Random.new()""" # Import the Random module and try to use it from Cryptodome import Random randobj = Random.new() x = randobj.read(16) y = randobj.read(16) self.assertNotEqual(x, y) z = Random.get_random_bytes(16) self.assertNotEqual(x, z) self.assertNotEqual(y, z) # Test the Random.random module, which # implements a subset of Python's random API # Not implemented: # seed(), getstate(), setstate(), jumpahead() # random(), uniform(), triangular(), betavariate() # expovariate(), gammavariate(), gauss(), # longnormvariate(), normalvariate(), # vonmisesvariate(), paretovariate() # weibullvariate() # WichmannHill(), whseed(), SystemRandom() from Cryptodome.Random import random x = random.getrandbits(16*8) y = random.getrandbits(16*8) self.assertNotEqual(x, y) # Test randrange if x>y: start = y stop = x else: start = x stop = y for step in range(1,10): x = random.randrange(start,stop,step) y = random.randrange(start,stop,step) self.assertNotEqual(x, y) self.assertEqual(start <= x < stop, True) self.assertEqual(start <= y < stop, True) self.assertEqual((x - start) % step, 0) self.assertEqual((y - start) % step, 0) for i in range(10): self.assertEqual(random.randrange(1,2), 1) self.assertRaises(ValueError, random.randrange, start, start) self.assertRaises(ValueError, random.randrange, stop, start, step) self.assertRaises(TypeError, random.randrange, start, stop, step, step) self.assertRaises(TypeError, random.randrange, start, stop, "1") self.assertRaises(TypeError, random.randrange, "1", stop, step) self.assertRaises(TypeError, random.randrange, 1, "2", step) self.assertRaises(ValueError, random.randrange, start, stop, 0) # Test randint x = random.randint(start,stop) y = random.randint(start,stop) self.assertNotEqual(x, y) self.assertEqual(start <= x <= stop, True) self.assertEqual(start <= y <= stop, True) for i in range(10): self.assertEqual(random.randint(1,1), 1) self.assertRaises(ValueError, random.randint, stop, start) self.assertRaises(TypeError, random.randint, start, stop, step) self.assertRaises(TypeError, random.randint, "1", stop) self.assertRaises(TypeError, random.randint, 1, "2") # Test choice seq = range(10000) x = random.choice(seq) y = random.choice(seq) self.assertNotEqual(x, y) self.assertEqual(x in seq, True) self.assertEqual(y in seq, True) for i in range(10): self.assertEqual(random.choice((1,2,3)) in (1,2,3), True) self.assertEqual(random.choice([1,2,3]) in [1,2,3], True) if sys.version_info[0] is 3: self.assertEqual(random.choice(bytearray(b('123'))) in bytearray(b('123')), True) self.assertEqual(1, random.choice([1])) self.assertRaises(IndexError, random.choice, []) self.assertRaises(TypeError, random.choice, 1) # Test shuffle. Lacks random parameter to specify function. # Make copies of seq seq = range(500) x = list(seq) y = list(seq) random.shuffle(x) random.shuffle(y) self.assertNotEqual(x, y) self.assertEqual(len(seq), len(x)) self.assertEqual(len(seq), len(y)) for i in range(len(seq)): self.assertEqual(x[i] in seq, True) self.assertEqual(y[i] in seq, True) self.assertEqual(seq[i] in x, True) self.assertEqual(seq[i] in y, True) z = [1] random.shuffle(z) self.assertEqual(z, [1]) if sys.version_info[0] == 3: z = bytearray(b('12')) random.shuffle(z) self.assertEqual(b('1') in z, True) self.assertRaises(TypeError, random.shuffle, b('12')) self.assertRaises(TypeError, random.shuffle, 1) self.assertRaises(TypeError, random.shuffle, "11") self.assertRaises(TypeError, random.shuffle, (1,2)) # 2to3 wraps a list() around it, alas - but I want to shoot # myself in the foot here! :D # if sys.version_info[0] == 3: # self.assertRaises(TypeError, random.shuffle, range(3)) # Test sample x = random.sample(seq, 20) y = random.sample(seq, 20) self.assertNotEqual(x, y) for i in range(20): self.assertEqual(x[i] in seq, True) self.assertEqual(y[i] in seq, True) z = random.sample([1], 1) self.assertEqual(z, [1]) z = random.sample((1,2,3), 1) self.assertEqual(z[0] in (1,2,3), True) z = random.sample("123", 1) self.assertEqual(z[0] in "123", True) z = random.sample(range(3), 1) self.assertEqual(z[0] in range(3), True) if sys.version_info[0] == 3: z = random.sample(b("123"), 1) self.assertEqual(z[0] in b("123"), True) z = random.sample(bytearray(b("123")), 1) self.assertEqual(z[0] in bytearray(b("123")), True) self.assertRaises(TypeError, random.sample, 1)
def __init__(self, key): self.pweights = [i for i in range(8)] random.shuffle(self.pweights) self.weights = NeuralNet.inttoarray(key)
def generate(self) -> str: password_list = [] for count, chars in self.category_map: password_list.extend(choice(chars) for i in range(count)) shuffle(password_list) return ''.join(password_list)