示例#1
0
 def maliciousReceiver(self, contactInfo):
     p = contactInfo[0][0]
     g = contactInfo[0][1]
     sender = contactInfo[1]
     intendedTarget = contactInfo[2]
     self.pgPairs[sender] = contactInfo[0]
     self.private[sender] = random.randrange(
         p)  # This is why eavesdropping is pointless
     self.public[sender] = pow(g, self.private[sender], p)
     self.pgPairs[intendedTarget] = contactInfo[0]
     self.private[intendedTarget] = random.randrange(
         p)  # This is why eavesdropping is pointless
     self.public[intendedTarget] = pow(g, self.private[sender], p)
示例#2
0
文件: client.py 项目: FRadford/JAM
    def dh_key_exchange(self, received: KeyExchangeMessage = None) -> SHA3_256:
        """
        Facilitates both sides of a basic Diffie-Hellman key exchange and generates a shared secret, the hash of this
        secret is returned to be used as a key for the cipher
        """

        # TODO: Fix key exchange. Probably by keeping a key for every other user.
        if not received:
            secret = randrange(
                1, self.helper.prime
            )  # Random integer between 1 and prime - 1: to be kept secret

            public = (self.helper.root**secret
                      ) % self.helper.prime  # Public part, shared in the clear

            # Send public information
            self.exchange = True
            self.send_yaml(
                KeyExchangeMessage("Request Key Exchange", self.helper.prime,
                                   self.helper.root, public, self.recipient,
                                   self.username))

            # response = yaml.load(self.receive_single()).text
            response = self.receive_single().text

            self.exchange = False
            self.wait.set()

            # Calculate and return shared secret
            return SHA3_256.new(
                self.int_to_bytes((response**secret) % self.helper.prime))
        else:
            self.send_yaml(
                KeyExchangeMessage("Key Exchange Accepted",
                                   recipient=self.recipient,
                                   sender=self.username))

            secret = randrange(
                1, received.prime
            )  # Random integer between 1 and prime - 1: to be kept secret

            public = (received.root**secret
                      ) % received.prime  # Public part, shared in the clear

            self.send_yaml(Message(public, self.recipient,
                                   self.username))  # Send public information

            # Calculate and return shared secret
            return SHA3_256.new(
                self.int_to_bytes(
                    (received.public**secret) % self.helper.prime))
示例#3
0
def miller_rabin(n):
    '''
	Applies the MillerRabin Test to n (odd)
	
	returns True iff n passes the MillerRabinTest for
	K random bases
	'''
    #Compute s and d such that n-1 = (2^s)d, with d odd
    d = n - 1
    s = 0
    while d % 2 == 0:
        d >>= 1
        s += 1

    #Applies the test K times
    #The probability of a false positive is less than (1/4)^K
    K = 20

    i = 1
    while (i <= K):
        # 1 < a < n-1
        a = randrange(2, n - 1)
        if not miller_rabin_pass(a, s, d, n):
            return False
        i += 1

    return True
示例#4
0
 def receiveContact(self, contactInfo):
     if (self.name == contactInfo[2]):
         p = contactInfo[0][0]
         g = contactInfo[0][1]
         sender = contactInfo[1]
         self.pgPairs[sender] = contactInfo[0]
         self.private[sender] = random.randrange(p)
         self.public[sender] = pow(g, self.private[sender], p)
     else:
         print("They aren't trying to talk to me, that's ok!")
示例#5
0
 def choose_cipher(self, pre_encryption_text):
     if random.randrange(2) == 1:
         device = CBC()
         print('*******CBC*****')
         return device.encrypt(pre_encryption_text,
                               self.random_key(block_size),
                               Random.new().read(16))
     else:
         device = ECB()
         print("*****NOT CBC******")
         return device.encryptECB(pre_encryption_text,
                                  self.random_key(block_size))
示例#6
0
 def initiateContact(self, other: str, pgVals: (int, int) = None):
     if (pgVals is None):
         elGam = ElGamal.generate(
             256, RandBytes)  # Would be larger p in practice
         p = int(elGam.p)
         g = int(elGam.g)
     else:
         p = pgVals[0]
         g = pgVals[1]
     self.pgPairs[other] = (p, g)
     self.private[other] = random.randrange(p)
     self.public[other] = pow(g, self.private[other], p)
     return ((p, g), self.name, other)
示例#7
0
文件: server.py 项目: FRadford/JAM
    def dh_key_exchange(self, prime: int, root: int, received_public: int):
        secret = randrange(
            1,
            prime)  # Random integer between 1 and prime - 1: to be kept secret

        public = (root**secret) % prime  # Public part, shared in the clear

        self.handler.send_yaml(KeyExchangeMessage("Key Exchange Accepted"),
                               self)
        self.handler.send_yaml(Message(public),
                               self)  # Send public information

        # Calculate and return shared secret
        self.key = SHA3_256.new(
            self.handler.int_to_bytes(
                (received_public**secret) % self.helper.prime)).digest()
示例#8
0
 def prep_plaintext(self, plaintext):
     mypkcs7 = PKCS7()
     key = self.random_key(block_size)
     return (mypkcs7.PKCS7_padding(
         Random.new().read(random.randrange(5, 11)) + plaintext +
         Random.new().read(random.randrange(5, 11)), len(key)))
示例#9
0
 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)
示例#10
0
 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)