def _init_file_metadata(self, path): self.metadata_dict[path] = {} # binascii.hexlify('\0'*16) self.metadata_dict[path]["file_last_block"] = '' rand_iv = random.getrandbits(64) self.metadata_dict[path]["iv"] = rand_iv self._write_metadata(self.metadata_file)
def create_key(self): """Generates a unique, pseudorandom AES key, stored ephemerally in memory as an instance attribute. Its destruction is ensured by the automatic nightly reboots of the SecureDrop application server combined with the freed memory-overwriting PAX_MEMORY_SANITIZE feature of the grsecurity-patched kernel it uses (for further details consult https://github.com/freedomofpress/securedrop/pull/477#issuecomment-168445450). """ self.key = os.urandom(self.AES_key_size / 8) self.iv = random.getrandbits(self.AES_block_size) self.initialize_cipher()
def gen_prime(nbits): ''' Generates a prime of b bits using the miller_rabin_test ''' while True: p = getrandbits(nbits) #force p to have nbits and be odd p |= 2**nbits | 1 if miller_rabin(p): return p
def enc(key1, key2, iv, data1, data2): cipher1 = AES.new(byte_xor(key1, iv), AES.MODE_ECB) cipher2 = AES.new(byte_xor(key2, iv), AES.MODE_ECB) n = 128 u = n // 16 k = n - u d1 = prep_data(u // 8, data1) d2 = prep_data(u // 8, data2) print(d1) print(d2) c = list(d1) i = 0 j = 0 p = random.getrandbits(k) r = p while 1: c[i] = (cipher1.encrypt(d1[i] + r.to_bytes(k // 8, "big"))) T = cipher2.decrypt(c[i]) t = T[0:1] rr = T[1:] if t != d2[i]: if j < 2 ** (2 * u): j += 1 r += 1 continue else: print("Encryption of the pair of input data blocks ti and mi has not been fulfilled!") if i < len(d1) - 1: p = random.getrandbits(k) r = p i += 1 j = 0 print(i) else: break print(c) return c
def enc_probabilistic(key, iv, data): n = 128 u = n // 16 k = n - u cipher1 = AES.new(byte_xor(key1, iv), AES.MODE_ECB) d1 = prep_data(u // 8, data1) c = list(d1) i = 0 while i < len(d1): r = random.getrandbits(k) c[i] = (cipher1.encrypt(d1[i] + r.to_bytes(k // 8, "big"))) i += 1 return c
def random_prime(bit_size: int, rounds: int = 40) -> int: """ Generate a random prime number within given bit range. :param bit_size: maximum bit size of the prime number :param rounds: iterations of the prime probability test (Miller-Robin) :return: first probable prime number """ while True: num = getrandbits(bit_size) if BBS.is_probably_prime(num, rounds): return num
def __imul__(self, scalar): """Multiply this point by a scalar""" if scalar < 0: raise ValueError("Scalar multiplication is only defined for non-negative integers") sb = long_to_bytes(scalar) result = _ec_lib.ec_ws_scalar(self._point.get(), c_uint8_ptr(sb), c_size_t(len(sb)), c_ulonglong(getrandbits(64))) if result: raise ValueError("Error %d during scalar multiplication" % result) return self
def generate_peers(num_peers: int) -> list: """Generate the given number of peers""" peer_list = [] for _ in progressbar.progressbar(range(0, num_peers)): tx = sha256(getrandbits(256).to_bytes(32, 'big')).digest().hex() # We used a fixed tx value b/c it has no importance for the eval (pri, pub) = generate_key_pair() p = protocol.Peer( ip_address=ipaddress.IPv4Address(get_random_bytes(4)), port=int(random.randint(3000, 4000)), public_key=pub.to_string(), private_key=pri.to_string(), cont_tx=opreturn.Transaction(tx, 0), service=bytes([0x01, 0x00]) ) peer_list.append(p) return peer_list
def inplace_pow(self, exponent, modulus=None): exp_value = int(exponent) if exp_value < 0: raise ValueError("Exponent must not be negative") # No modular reduction if modulus is None: self._value = pow(self._value, exp_value) return self # With modular reduction mod_value = int(modulus) if mod_value < 0: raise ValueError("Modulus must be positive") if mod_value == 0: raise ZeroDivisionError("Modulus cannot be zero") # C extension only works with odd moduli if (mod_value & 1) == 0: self._value = pow(self._value, exp_value, mod_value) return self max_len = len(long_to_bytes(max(self._value, exp_value, mod_value))) base_b = long_to_bytes(self._value, max_len) exp_b = long_to_bytes(exp_value, max_len) modulus_b = long_to_bytes(mod_value, max_len) out = create_string_buffer(max_len) error = _raw_montgomery.monty_pow( base_b, exp_b, modulus_b, out, c_size_t(max_len), c_ulonglong(getrandbits(64)) ) if error: raise ValueError("monty_pow failed with error: %d" % error) result = bytes_to_long(get_raw_buffer(out)) self._value = result return self
def create_request_packets(self, http_request: str, https: bool = True): self.logger.debug('Initialising ff request') request = FfRequest(version=FfRequest.Version.V1, request_id=random.getrandbits(64)) self.create_secure_options(request, https) secure_options = self.serialize_secure_options(request.secure_options) payload = secure_options + bytearray(http_request.encode('utf8')) if (self.config.pre_shared_key): payload = self.encrypted_request_payload(request, payload) request.options.append( FfRequest.Option(FfRequest.Option.Type.BREAK, 0, bytearray([]))) request.payload = payload return self.packetise_request(request)
def keyGenerator(pubKey_fname, file, iv): # Generating 1024 random bits, and creating SHA-256 (for 32 bits compatibility with AES) h = SHA256.new(str(random.getrandbits(1024))) # Reading public key to encrypt AES key with keyPair = RSA.importKey(open(pubKey_fname, "r").read()) keyCipher = PKCS1_OAEP.new(keyPair.publickey()) # Saving encrypted key to *.key file f = open(file.split('.')[0] + ".key", "w") f.write(iv + keyCipher.encrypt(h.digest())) f.close() # Returning generated key to encrypt file with return h.digest()
def create_request_packets(self, http_request: str, https: bool = True): self.logger.debug('Initialising ff request') request = FfRequest(version=FfRequest.Version.V1, request_id=random.getrandbits(64)) if https: request.options.append( FfRequest.Option(FfRequest.Option.Type.HTTPS, 1, bytearray([1]))) if (self.config.pre_shared_key): http_request = self.encrypted_request_payload( request, http_request) request.options.append( FfRequest.Option(FfRequest.Option.Type.EOL, 0, bytearray([]))) request.payload = http_request return self.packetise_request(request)
def register(self, username, password): cursor = self.handler.server.database.cursor() salt = str(getrandbits(64)) statement = "INSERT INTO users(username, password, salt) VALUES (?,?,?)" try: cursor.execute( statement, (username, SHA3_256.new(bytes(password + salt, "utf-8")).hexdigest(), salt)) self.handler.send_encrypted_message("Successfully Registered.", self) self.username = username except sqlite3.IntegrityError: self.handler.send_encrypted_message("Username Already Registered.", self) self.handler.server.database.commit() self.handler.server.database.close() self.handler.server.database = None
def init_p192(): p = 0xfffffffffffffffffffffffffffffffeffffffffffffffff b = 0x64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1 order = 0xffffffffffffffffffffffff99def836146bc9b1b4d22831 Gx = 0x188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012 Gy = 0x07192b95ffc8da78631011ed6b24cdd573f977a11e794811 p192_modulus = long_to_bytes(p, 24) p192_b = long_to_bytes(b, 24) p192_order = long_to_bytes(order, 24) ec_p192_context = VoidPointer() result = _ec_lib.ec_ws_new_context(ec_p192_context.address_of(), c_uint8_ptr(p192_modulus), c_uint8_ptr(p192_b), c_uint8_ptr(p192_order), c_size_t(len(p192_modulus)), c_ulonglong(getrandbits(64))) if result: raise ImportError("Error %d initializing P-192 context" % result) context = SmartPointer(ec_p192_context.get(), _ec_lib.ec_free_context) p192 = _Curve( Integer(p), Integer(b), Integer(order), Integer(Gx), Integer(Gy), None, 192, "1.2.840.10045.3.1.1", # ANSI X9.62 / SEC2 context, "NIST P-192", "ecdsa-sha2-nistp192") global p192_names _curves.update(dict.fromkeys(p192_names, p192))
def init_p256(): p = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff b = 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b order = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551 Gx = 0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296 Gy = 0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5 p256_modulus = long_to_bytes(p, 32) p256_b = long_to_bytes(b, 32) p256_order = long_to_bytes(order, 32) ec_p256_context = VoidPointer() result = _ec_lib.ec_ws_new_context(ec_p256_context.address_of(), c_uint8_ptr(p256_modulus), c_uint8_ptr(p256_b), c_uint8_ptr(p256_order), c_size_t(len(p256_modulus)), c_ulonglong(getrandbits(64)) ) if result: raise ImportError("Error %d initializing P-256 context" % result) context = SmartPointer(ec_p256_context.get(), _ec_lib.ec_free_context) p256 = _Curve(Integer(p), Integer(b), Integer(order), Integer(Gx), Integer(Gy), None, 256, "1.2.840.10045.3.1.7", # ANSI X9.62 context, "NIST P-256", "ecdsa-sha2-nistp256") global p256_names _curves.update(dict.fromkeys(p256_names, p256))
def init_p521(): p = 0x000001ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff b = 0x00000051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00 order = 0x000001fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409 Gx = 0x000000c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66 Gy = 0x0000011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650 p521_modulus = long_to_bytes(p, 66) p521_b = long_to_bytes(b, 66) p521_order = long_to_bytes(order, 66) ec_p521_context = VoidPointer() result = _ec_lib.ec_ws_new_context(ec_p521_context.address_of(), c_uint8_ptr(p521_modulus), c_uint8_ptr(p521_b), c_uint8_ptr(p521_order), c_size_t(len(p521_modulus)), c_ulonglong(getrandbits(64)) ) if result: raise ImportError("Error %d initializing P-521 context" % result) context = SmartPointer(ec_p521_context.get(), _ec_lib.ec_free_context) p521 = _Curve(Integer(p), Integer(b), Integer(order), Integer(Gx), Integer(Gy), None, 521, "1.3.132.0.35", # SEC 2 context, "NIST P-521", "ecdsa-sha2-nistp521") global p521_names _curves.update(dict.fromkeys(p521_names, p521))
def init_p224(): p = 0xffffffffffffffffffffffffffffffff000000000000000000000001 b = 0xb4050a850c04b3abf54132565044b0b7d7bfd8ba270b39432355ffb4 order = 0xffffffffffffffffffffffffffff16a2e0b8f03e13dd29455c5c2a3d Gx = 0xb70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21 Gy = 0xbd376388b5f723fb4c22dfe6cd4375a05a07476444d5819985007e34 p224_modulus = long_to_bytes(p, 28) p224_b = long_to_bytes(b, 28) p224_order = long_to_bytes(order, 28) ec_p224_context = VoidPointer() result = _ec_lib.ec_ws_new_context(ec_p224_context.address_of(), c_uint8_ptr(p224_modulus), c_uint8_ptr(p224_b), c_uint8_ptr(p224_order), c_size_t(len(p224_modulus)), c_ulonglong(getrandbits(64))) if result: raise ImportError("Error %d initializing P-224 context" % result) context = SmartPointer(ec_p224_context.get(), _ec_lib.ec_free_context) p224 = _Curve( Integer(p), Integer(b), Integer(order), Integer(Gx), Integer(Gy), None, 224, "1.3.132.0.33", # SEC 2 context, "NIST P-224", "ecdsa-sha2-nistp224") global p224_names _curves.update(dict.fromkeys(p224_names, p224))
def init_p384(): p = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff b = 0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef order = 0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973 Gx = 0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760aB7 Gy = 0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5F p384_modulus = long_to_bytes(p, 48) p384_b = long_to_bytes(b, 48) p384_order = long_to_bytes(order, 48) ec_p384_context = VoidPointer() result = _ec_lib.ec_ws_new_context(ec_p384_context.address_of(), c_uint8_ptr(p384_modulus), c_uint8_ptr(p384_b), c_uint8_ptr(p384_order), c_size_t(len(p384_modulus)), c_ulonglong(getrandbits(64)) ) if result: raise ImportError("Error %d initializing P-384 context" % result) context = SmartPointer(ec_p384_context.get(), _ec_lib.ec_free_context) p384 = _Curve(Integer(p), Integer(b), Integer(order), Integer(Gx), Integer(Gy), None, 384, "1.3.132.0.34", # SEC 2 context, "NIST P-384", "ecdsa-sha2-nistp384") global p384_names _curves.update(dict.fromkeys(p384_names, p384))
def intermediate_keys(prime: int, root: int, bit_size: int = 256) -> (int, int): rand = getrandbits(bit_size) return rand, pow(root, rand, prime)
def connect_to_merchant(self, host, port): self.socket.connect((host, port)) # -------------------------------------- Setup protocol ------------------------------------------- # 1 self.get_merchant_public_key() # Encrypt client key with AES symmetric key + AES symmetric key encrypted with merchant rsa public key payload = hybrid_encryption(self.public_key, self.merchant_public_key) self.socket.send(pickle.dumps(payload)) # Received data from Merchant. (Session id and SigM(Sid)) data = self.socket.recv(8192) payload = pickle.loads(data) encrypted_aes_key = payload['k_encryption'] decrypted_aes_key = utils.rsa_decryption(encrypted_aes_key, self.private_key) self.session_id = utils.aes_decryption(decrypted_aes_key, payload['session_id']) self.session_signature = utils.aes_decryption(decrypted_aes_key, payload['sid_signature']) if utils.verify_signature(self.session_id, self.merchant_public_key, self.session_signature): print(f"[RECEIVED] Session id: \n{self.session_id}\n") print( f"[RECEIVED] Session signature: \n{self.session_signature}\n") else: print("[ERROR] Invalid signature") exit(0) # ------------------------------------------- Exchange ------------------------------------------- self.get_pg_public_key() nonce = random.getrandbits(16) order_description = "Omen by HP 15-dc0018nq" amount = 3000 # PO signature po_client_signature = utils.proceed_signature( pickle.dumps([order_description, self.session_id, amount, nonce]), self.private_key) # payment order po = { "OrderDesc": order_description, "SID": self.session_id, "Amount": amount, "NC": nonce, "SigC": po_client_signature } # payment information pi = { "CardN": "4034783123305160", "CardExp": "04/2025", "CCode": "627", "SID": self.session_id, "Amount": amount, "PubKC": self.public_key, "NC": nonce, "M": "Amazon" } print(f"[CREATE] PO: \n{po}\n") print(f"[CREATE] PI: \n{pi}\n") # PI client signature pi_client_signature = utils.proceed_signature(pickle.dumps(pi), self.private_key) print(f"[CREATE] PI Client Signature: \n{pi_client_signature}\n") # Encrypt PI, SigC(PI) with PG RSA public key k = utils.generate_k() encrypted_pi = utils.aes_encryption( k, pickle.dumps([pi, pi_client_signature])) encrypted_key = utils.rsa_encryption(k, self.pg_public_key) pm = { "encrypted_data": encrypted_pi, # encrypted_data = PI, SigC(PI) "encrypted_key": encrypted_key } print(f"[CREATE] PM: \n{pm}\n") # Encrypt PM, PO with M rsa public key k = utils.generate_k() encrypted_pm_po = utils.aes_encryption(k, pickle.dumps([pm, po])) encrypted_pm_po_key = utils.rsa_encryption(k, self.merchant_public_key) payload = {"pm_po": encrypted_pm_po, "pm_po_key": encrypted_pm_po_key} # 3. print(f"[SENT] PM, PO: \n{payload}\n") self.socket.send(pickle.dumps(payload)) # 6. # Receive payload Resp, Sid, SigPG(Resp, Sid, Amount, NC) data = self.socket.recv(4096) payload = pickle.loads(data) print( f"[RECEIVED] Resp, Sid, SigPG(Resp, Sid, Amount, NC): \n{payload}\n" ) # Decrypt data decrypted_payload_key = utils.rsa_decryption(payload["encrypted_key"], self.private_key) decrypted_payload = pickle.loads( utils.aes_decryption(decrypted_payload_key, payload["encrypted_payload"])) # Verify signature and session id if self.session_id == decrypted_payload["SID"]: if utils.verify_signature( pickle.dumps([ decrypted_payload["Resp"], self.session_id, pi["Amount"], pi["NC"] ]), self.pg_public_key, decrypted_payload["SigPG"]): print( f"[RECEIVED] Response of transaction: \n{decrypted_payload['Resp']}\n" ) self.socket.close() else: print(f"[ERROR] Invalid signature") else: print(f"[ERROR] Invalid session id")
filename = get_pow_eval_path() + '/' + get_filename(REPS, MIN, MAX, STEP) eval_dir = get_pow_eval_path() with open(filename, 'w') as fd: fd.write("------------------------HEADER------------------------\n") fd.write("PoW Eval") fd.write("Difficulty (from, to, step): {}\n".format( str((MIN, MAX, STEP)))) fd.write("Repetitions per config: {}\n".format(REPS)) fd.write("Difficulty; # Hash Operations; Repetition\n") fd.write("----------------------END-HEADER----------------------\n") for r in progressbar(range(0, REPS)): for diff in range(MIN, MAX, STEP): hash_operations = 0 # We use pre-generated but 'real' public keys, chosen randomly pubkey = choice(peers).public_key_hash() # We use a random merkleroothash merkle = sha256(getrandbits(256).to_bytes(32, 'big')).digest().hex() seed = _calc_powork_seed(pubkey, merkle) hash_operations += 1 # One hash operation for seed computation hash_operations += _calculate_hash_powork_nonce( diff, seed, NONCE_LENGTH, True) # Write Result with open(filename, 'a') as fd: fd.write('{};{:d};{}\n'.format(diff, hash_operations, r))
def nonce(size): return getrandbits(size)
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 _random_bytes(n): return _hide(bytearray(getrandbits(8) for _ in range(n)))
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): self.b = random.getrandbits(BITS) self.bebsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.getprotobyname('TCP'))
def __init__(self): self.p = number.getPrime(BITS) self.a = random.getrandbits(BITS) % self.p self.g = 2 self.bibsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.bibsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)