Python secrets.randbits() Examples
The following are 23
code examples of secrets.randbits().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
secrets
, or try the search function
.
Example #1
Source File: security.py From minikerberos with MIT License | 6 votes |
def construct_tgt_req(self): now = now = datetime.datetime.now(datetime.timezone.utc) kdc_req_body = {} kdc_req_body['kdc-options'] = KDCOptions(set(['forwardable','renewable','proxiable'])) kdc_req_body['cname'] = PrincipalName({'name-type': NAME_TYPE.PRINCIPAL.value, 'name-string': [self.spn.username]}) kdc_req_body['realm'] = self.spn.domain.upper() kdc_req_body['sname'] = PrincipalName({'name-type': NAME_TYPE.PRINCIPAL.value, 'name-string': ['krbtgt', self.spn.domain.upper()]}) kdc_req_body['till'] = (now + datetime.timedelta(days=1)).replace(microsecond=0) kdc_req_body['rtime'] = (now + datetime.timedelta(days=1)).replace(microsecond=0) kdc_req_body['nonce'] = secrets.randbits(31) kdc_req_body['etype'] = [2, 3, 16, 23, 17, 18] #we "support" all MS related enctypes pa_data_1 = {} pa_data_1['padata-type'] = int(PADATA_TYPE('PA-PAC-REQUEST')) pa_data_1['padata-value'] = PA_PAC_REQUEST({'include-pac': True}).dump() kdc_req = {} kdc_req['pvno'] = krb5_pvno kdc_req['msg-type'] = MESSAGE_TYPE.KRB_AS_REQ.value kdc_req['padata'] = [pa_data_1] kdc_req['req-body'] = KDC_REQ_BODY(kdc_req_body) return AS_REQ(kdc_req)
Example #2
Source File: __init__.py From concurrent-log-handler with Apache License 2.0 | 5 votes |
def randbits(nb): return random.Random().getrandbits(nb)
Example #3
Source File: keys.py From trinity with MIT License | 5 votes |
def _mk_private_key_bytes() -> bytes: return int_to_big_endian(secrets.randbits(256)).rjust(32, b'\x00')
Example #4
Source File: discovery.py From trinity with MIT License | 5 votes |
def lookup_random(self) -> Tuple[NodeAPI, ...]: target_key = int_to_big_endian( secrets.randbits(constants.KADEMLIA_PUBLIC_KEY_SIZE) ).rjust(constants.KADEMLIA_PUBLIC_KEY_SIZE // 8, b'\x00') return await self.lookup(target_key)
Example #5
Source File: server.py From inshack-2018 with GNU General Public License v3.0 | 5 votes |
def get_commit(inst): jackpot = secrets.randbits(10) blind = inst.getrandbits(32) commit = hashlib.md5(str(jackpot+blind).encode()).hexdigest() return [commit,jackpot,blind]
Example #6
Source File: server.py From inshack-2018 with GNU General Public License v3.0 | 5 votes |
def get_commit(inst): jackpot = secrets.randbits(10) blind = inst.getrandbits(32) commit = hashlib.md5(str(jackpot+blind).encode()).hexdigest() return [commit,jackpot,blind]
Example #7
Source File: keys.py From py-evm with MIT License | 5 votes |
def _mk_private_key_bytes() -> bytes: return int_to_big_endian(secrets.randbits(256)).rjust(32, b'\x00')
Example #8
Source File: common.py From Requester with MIT License | 5 votes |
def generate_nonce(): """Generate pseudorandom nonce that is unlikely to repeat. Per `section 3.3`_ of the OAuth 1 RFC 5849 spec. Per `section 3.2.1`_ of the MAC Access Authentication spec. A random 64-bit number is appended to the epoch timestamp for both randomness and to decrease the likelihood of collisions. .. _`section 3.2.1`: https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01#section-3.2.1 .. _`section 3.3`: https://tools.ietf.org/html/rfc5849#section-3.3 """ return unicode_type(unicode_type(randbits(64)) + generate_timestamp())
Example #9
Source File: port_manager.py From frida-skeleton with MIT License | 5 votes |
def secure_rand_port(cls): while True: port = secrets.randbits(16) if port < 1024: continue return port
Example #10
Source File: rlwe.py From PySyft with Apache License 2.0 | 5 votes |
def sample_poly_uniform(param): """Generate a polynomial from uniform distribution. Args: parms (EncryptionParam): Encryption parameters. Returns: A 2-dim list having integer from uniform distributions. """ coeff_modulus = param.coeff_modulus coeff_mod_size = len(coeff_modulus) coeff_count = param.poly_modulus max_random = 0x7FFFFFFFFFFFFFFF result = [0] * coeff_mod_size for i in range(coeff_mod_size): result[i] = [0] * coeff_count for j in range(coeff_mod_size): modulus = coeff_modulus[j] max_multiple = max_random - (max_random % modulus) - 1 for i in range(coeff_count): # This ensures uniform distribution. while True: rand = randbits(32) << 31 | randbits(32) >> 1 if rand < max_multiple: break result[j][i] = rand % modulus return result
Example #11
Source File: pynat.py From pynat with MIT License | 5 votes |
def randint(n): return secrets.randbits(n)
Example #12
Source File: generator.py From blocksmith with Apache License 2.0 | 5 votes |
def __init_pool(self): for i in range(self.POOL_SIZE): random_byte = secrets.randbits(8) self.__seed_byte(random_byte) time_int = int(time.time()) self.__seed_int(time_int)
Example #13
Source File: common.py From bazarr with GNU General Public License v3.0 | 5 votes |
def generate_nonce(): """Generate pseudorandom nonce that is unlikely to repeat. Per `section 3.3`_ of the OAuth 1 RFC 5849 spec. Per `section 3.2.1`_ of the MAC Access Authentication spec. A random 64-bit number is appended to the epoch timestamp for both randomness and to decrease the likelihood of collisions. .. _`section 3.2.1`: https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01#section-3.2.1 .. _`section 3.3`: https://tools.ietf.org/html/rfc5849#section-3.3 """ return unicode_type(unicode_type(randbits(64)) + generate_timestamp())
Example #14
Source File: flask_server.py From trusat-backend with Apache License 2.0 | 5 votes |
def get_nonce(): try: addr = request.get_json()["address"] except Exception as e: print(e) raise InvalidUsage('Ethereum address missing', status_code=400) if isValidEthereumAddress(addr) is False: raise InvalidUsage('Invalid Ethereum address', status_code=400) try: email = request.get_json()["email"] if isValidEmailAddress is False: raise InvalidUsage('Invalid email address', status_code=400) results = g.get('db').selectObserverAddressFromEmail(email) if len(results) == 42: return {} except Exception as e: print(e) try: public_address_count = g.get('db').getObserverCountByID(public_address=addr) except Exception as e: print(e) raise InvalidUsage('message', status_code=500) random_number = str(secrets.randbits(256)) response_message = '{"nonce":\"%s\"}' % random_number if public_address_count[0] == None or public_address_count[0] == 0: # New User try: g.get('db').addObserver(addr, "NULL", 0, "NULL") g.get('db').updateObserverNonceBytes(nonce=random_number, public_address=addr) except Exception as e: print(e) raise InvalidUsage('message', status_code=500) elif public_address_count[0] >= 1: # Old User try: g.get('db').updateObserverNonceBytes(nonce=random_number, public_address=addr) except Exception as e: print(e) raise InvalidUsage('message', status_code=500) return response_message
Example #15
Source File: test_bip39.py From btclib with MIT License | 5 votes |
def test_zeroleadingbit(): # it should not throw an error bip39.mnemonic_from_entropy(secrets.randbits(127), "en")
Example #16
Source File: entropy.py From btclib with MIT License | 5 votes |
def randbinstr( bits: int, entropy: Optional[BinStr] = None, hash: bool = True ) -> BinStr: """Return CSPRNG raw entropy XOR-ed with input raw entropy. If no exogenous raw entropy is provided as input, then entropy is generated with the system cryptographically strong pseudo-random number generator (CSPRNG). Then, this entropy is: - XOR-ed with CSPRNG system entropy - possibly hashed (if requested) """ if entropy is None or entropy == "": i = secrets.randbits(bits) else: if len(entropy) > bits: # only the leftmost bits are retained entropy = entropy[:bits] i = int(entropy, 2) # XOR the current entropy with CSPRNG system entropy i ^= secrets.randbits(bits) # hash the current entropy if hash: hf = sha512() max_bits = hf.digest_size * 8 if bits > max_bits: m = f"Too many bits required: {bits}, max is {max_bits}" raise ValueError(m) n_bytes = math.ceil(i.bit_length() / 8) h512 = sha512(i.to_bytes(n_bytes, byteorder="big")).digest() i = int.from_bytes(h512, byteorder="big") return binstr_from_int(i, bits)
Example #17
Source File: test_secrets.py From android_universal with MIT License | 5 votes |
def test_randbits(self): # Test randbits. errmsg = "randbits(%d) returned %d" for numbits in (3, 12, 30): for i in range(6): n = secrets.randbits(numbits) self.assertTrue(0 <= n < 2**numbits, errmsg % (numbits, n))
Example #18
Source File: ice.py From aioice with BSD 3-Clause "New" or "Revised" License | 4 votes |
def __init__( self, ice_controlling: bool, components: int = 1, stun_server: Optional[Tuple[str, int]] = None, turn_server: Optional[Tuple[str, int]] = None, turn_username: Optional[str] = None, turn_password: Optional[str] = None, turn_ssl: bool = False, turn_transport: str = "udp", use_ipv4: bool = True, use_ipv6: bool = True, ) -> None: self.ice_controlling = ice_controlling #: Local username, automatically set to a random value. self.local_username = random_string(4) #: Local password, automatically set to a random value. self.local_password = random_string(22) #: Whether the remote party is an ICE Lite implementation. self.remote_is_lite = False #: Remote username, which you need to set. self.remote_username: Optional[str] = None #: Remote password, which you need to set. self.remote_password: Optional[str] = None self.stun_server = stun_server self.turn_server = turn_server self.turn_username = turn_username self.turn_password = turn_password self.turn_ssl = turn_ssl self.turn_transport = turn_transport # private self._components = set(range(1, components + 1)) self._check_list: List[CandidatePair] = [] self._check_list_done = False self._check_list_state: asyncio.Queue = asyncio.Queue() self._early_checks: List[ Tuple[stun.Message, Tuple[str, int], StunProtocol] ] = [] self._id = next(connection_id) self._local_candidates: List[Candidate] = [] self._local_candidates_end = False self._local_candidates_start = False self._nominated: Dict[int, CandidatePair] = {} self._nominating: Set[int] = set() self._protocols: List[StunProtocol] = [] self._remote_candidates: List[Candidate] = [] self._remote_candidates_end = False self._query_consent_handle: Optional[asyncio.Future[None]] = None self._queue: asyncio.Queue = asyncio.Queue() self._tie_breaker = secrets.randbits(64) self._use_ipv4 = use_ipv4 self._use_ipv6 = use_ipv6
Example #19
Source File: flask_server.py From trusat-backend with Apache License 2.0 | 4 votes |
def claim_account(): try: email = request.get_json()['email'] except Exception as e: print(e) return {'result': False} if isValidEmailAddress(email) is False: raise InvalidUsage('message', status_code=400) try: with open('unsafe_private.pem', 'r') as file: private_key = file.read() private_rsa_key = load_pem_private_key(bytes(private_key, 'utf-8'), password=None, backend=default_backend()) results = g.get('db').selectObserverAddressFromEmail(email) if results is not None: results = results.decode('utf-8') else: return {'result': False} old_password = g.get('db').selectObserverPasswordFromAddress(results) if old_password is not None: old_password = old_password.decode('utf-8') try: if decode_jwt(old_password): return {'result': True} except: print('User already claimed account.') number = str(secrets.randbits(64)) jwt_payload = { 'email': email, 'secret': number, 'exp': datetime.utcnow() + timedelta(minutes=30) } encoded_jwt = encode(jwt_payload, private_rsa_key, algorithm='RS256') g.get('db').updateObserverPassword(encoded_jwt.decode('utf-8'), results) message_text = 'Please use the following link to verify your ownership of the following email ' + \ email + '\n\nhttps://trusat.org/claim/' + encoded_jwt.decode('utf-8') + '\nThis link will expire in 24 hours.' + \ '\n\nIf you did not request recovery of your account please contact us at:\nHelp@Beta.TruSat.org\n' data = {"from": "TruSat Help <" + MAILGUN_EMAIL_ADDRESS + ">", "to": [email], "subject": "TruSat - Recover Account", "text": message_text} response = requests.post( "https://api.mailgun.net/v3/beta.trusat.org/messages", auth=("api", MAILGUN_API_KEY), data=data ) if response.status_code != 200: print("Email failed to send.") raise InvalidUsage('message', status_code=500) else: return {'result': True} except Exception as e: print(e) raise InvalidUsage('message', status_code=500) return {'result': False}
Example #20
Source File: test_ssa.py From btclib with MIT License | 4 votes |
def test_batch_validation(): ec = secp256k1 hsize = hf().digest_size hlen = hsize * 8 ms = [] Qs = [] sigs = [] ms.append(secrets.randbits(hlen).to_bytes(hsize, "big")) q = 1 + secrets.randbelow(ec.n - 1) # bytes version Qs.append(mult(q, ec.G, ec)[0].to_bytes(ec.psize, "big")) sigs.append(ssa.sign(ms[0], q, None, ec, hf)) # test with only 1 sig ssa._batch_verify(ms, Qs, sigs, ec, hf) for _ in range(3): mhd = secrets.randbits(hlen).to_bytes(hsize, "big") ms.append(mhd) q = 1 + secrets.randbelow(ec.n - 1) # Point version Qs.append(mult(q, ec.G, ec)) sigs.append(ssa.sign(mhd, q, None, ec, hf)) ssa._batch_verify(ms, Qs, sigs, ec, hf) assert ssa.batch_verify(ms, Qs, sigs, ec, hf) ms.append(ms[0]) sigs.append(sigs[1]) Qs.append(Qs[0]) assert not ssa.batch_verify(ms, Qs, sigs, ec, hf) err_msg = "signature verification precondition failed" with pytest.raises(ValueError, match=err_msg): ssa._batch_verify(ms, Qs, sigs, ec, hf) sigs[-1] = sigs[0] # valid again ms[-1] = ms[0][:-1] err_msg = "invalid size: 31 bytes instead of 32" with pytest.raises(ValueError, match=err_msg): ssa._batch_verify(ms, Qs, sigs, ec, hf) ms[-1] = ms[0] # valid again ms.append(ms[0]) # add extra message err_msg = "mismatch between number of pubkeys " with pytest.raises(ValueError, match=err_msg): ssa._batch_verify(ms, Qs, sigs, ec, hf) ms.pop() # valid again sigs.append(sigs[0]) # add extra sig err_msg = "mismatch between number of pubkeys " with pytest.raises(ValueError, match=err_msg): ssa._batch_verify(ms, Qs, sigs, ec, hf) sigs.pop() # valid again err_msg = "field prime is not equal to 3 mod 4: " with pytest.raises(ValueError, match=err_msg): ssa._batch_verify(ms, Qs, sigs, secp224k1, hf)
Example #21
Source File: test_entropy.py From btclib with MIT License | 4 votes |
def test_conversions(): test_vectors = [ "10101011" * 32, "00101011" * 32, "00000000" + "10101011" * 31, ] for raw in test_vectors: assert binstr_from_binstr(raw) == raw i = int(raw, 2) assert binstr_from_int(i) == raw assert binstr_from_int(bin(i).upper()) == raw assert binstr_from_int(hex(i).upper()) == raw b = i.to_bytes(32, "big") assert binstr_from_bytes(b) == raw assert binstr_from_bytes(b.hex()) == raw assert binstr_from_entropy(raw) == raw assert binstr_from_entropy(i) == raw assert binstr_from_entropy(b) == raw max_bits = max(_bits) raw = "10" + "11111111" * (max_bits // 8) assert binstr_from_entropy(raw) == binstr_from_entropy(raw[:-2]) # entr integer has its leftmost bit set to 0 i = 1 << max_bits - 1 binstr_entropy = binstr_from_entropy(i) assert len(binstr_entropy) == max_bits # entr integer has its leftmost bit set to 1 i = 1 << max_bits binstr_entropy = binstr_from_entropy(i) assert len(binstr_entropy) == max_bits exp_i = i >> 1 i = int(binstr_entropy, 2) assert i == exp_i i = secrets.randbits(255) raw = binstr_from_int(i) assert int(raw, 2) == i assert len(raw) == 256 assert binstr_from_binstr(raw) == raw assert binstr_from_int(hex(i).upper()) == raw b = i.to_bytes(32, "big") assert binstr_from_bytes(b) == raw raw2 = binstr_from_int(i, 255) assert int(raw2, 2) == i assert len(raw2) == 255 assert binstr_from_binstr("0" + raw2) == raw raw2 = binstr_from_binstr(raw, 128) assert len(raw2) == 128 assert raw2 == raw[:128]
Example #22
Source File: borromean.py From btclib with MIT License | 4 votes |
def sign( msg: String, ks: Sequence[int], sign_key_idx: Sequence[int], sign_keys: Sequence[int], pubk_rings: PubkeyRing, ) -> Tuple[bytes, SValues]: """Borromean ring signature - signing algorithm https://github.com/ElementsProject/borromean-signatures-writeup https://github.com/Blockstream/borromean_paper/blob/master/borromean_draft_0.01_9ade1e49.pdf inputs: - msg: message to be signed (bytes) - sign_key_idx: list of indexes representing each signing key per ring - sign_keys: list containing the whole set of signing keys (one per ring) - pubk_rings: dictionary of sequences representing single rings of pubkeys """ if isinstance(msg, str): msg = msg.encode() m = _get_msg_format(msg, pubk_rings) e0bytes = m s: SValues = defaultdict(list) e: SValues = defaultdict(list) # step 1 for i, (pubk_ring, j_star, k) in enumerate( zip(pubk_rings.values(), sign_key_idx, ks) ): keys_size = len(pubk_ring) s[i] = [0] * keys_size e[i] = [0] * keys_size start_idx = (j_star + 1) % keys_size R = bytes_from_point(mult(k), ec) if start_idx != 0: for j in range(start_idx, keys_size): s[i][j] = secrets.randbits(256) e[i][j] = int_from_bits(_hash(m, R, i, j), ec.nlen) % ec.n assert 0 < e[i][j] < ec.n, "sign fail: how did you do that?!?" T = double_mult(-e[i][j], pubk_ring[j], s[i][j], ec.G) R = bytes_from_point(T, ec) e0bytes += R e0 = hf(e0bytes).digest() # step 2 for i, (j_star, k) in enumerate(zip(sign_key_idx, ks)): e[i][0] = int_from_bits(_hash(m, e0, i, 0), ec.nlen) % ec.n assert 0 < e[i][0] < ec.n, "sign fail: how did you do that?!?" for j in range(1, j_star + 1): s[i][j - 1] = secrets.randbits(256) T = double_mult(-e[i][j - 1], pubk_rings[i][j - 1], s[i][j - 1], ec.G) R = bytes_from_point(T, ec) e[i][j] = int_from_bits(_hash(m, R, i, j), ec.nlen) % ec.n assert 0 < e[i][j] < ec.n, "sign fail: how did you do that?!?" s[i][j_star] = k + sign_keys[i] * e[i][j_star] return e0, s
Example #23
Source File: client.py From minikerberos with MIT License | 4 votes |
def do_preauth(self, rep): #now getting server's supported encryption methods supp_enc_methods = collections.OrderedDict() for enc_method in METHOD_DATA.load(rep['e-data']).native: data_type = PaDataType(enc_method['padata-type']) if data_type == PaDataType.ETYPE_INFO or data_type == PaDataType.ETYPE_INFO2: if data_type == PaDataType.ETYPE_INFO: enc_info_list = ETYPE_INFO.load(enc_method['padata-value']) elif data_type == PaDataType.ETYPE_INFO2: enc_info_list = ETYPE_INFO2.load(enc_method['padata-value']) for enc_info in enc_info_list.native: supp_enc_methods[EncryptionType(enc_info['etype'])] = enc_info['salt'] logger.debug('Server supports encryption type %s with salt %s' % (EncryptionType(enc_info['etype']).name, enc_info['salt'])) logger.debug('Constructing TGT request with auth data') #now to create an AS_REQ with encrypted timestamp for authentication pa_data_1 = {} pa_data_1['padata-type'] = int(PADATA_TYPE('PA-PAC-REQUEST')) pa_data_1['padata-value'] = PA_PAC_REQUEST({'include-pac': True}).dump() now = datetime.datetime.now(datetime.timezone.utc) #creating timestamp asn1 timestamp = PA_ENC_TS_ENC({'patimestamp': now.replace(microsecond=0), 'pausec': now.microsecond}).dump() supp_enc = self.usercreds.get_preferred_enctype(supp_enc_methods) logger.debug('Selecting common encryption type: %s' % supp_enc.name) self.kerberos_cipher = _enctype_table[supp_enc.value] self.kerberos_cipher_type = supp_enc.value if 'salt' in enc_info and enc_info['salt'] is not None: self.server_salt = enc_info['salt'].encode() self.kerberos_key = Key(self.kerberos_cipher.enctype, self.usercreds.get_key_for_enctype(supp_enc, salt = self.server_salt)) enc_timestamp = self.kerberos_cipher.encrypt(self.kerberos_key, 1, timestamp, None) pa_data_2 = {} pa_data_2['padata-type'] = int(PADATA_TYPE('ENC-TIMESTAMP')) pa_data_2['padata-value'] = EncryptedData({'etype': supp_enc.value, 'cipher': enc_timestamp}).dump() kdc_req_body = {} kdc_req_body['kdc-options'] = KDCOptions(set(['forwardable','renewable','proxiable'])) kdc_req_body['cname'] = PrincipalName({'name-type': NAME_TYPE.PRINCIPAL.value, 'name-string': [self.usercreds.username]}) kdc_req_body['realm'] = self.usercreds.domain.upper() kdc_req_body['sname'] = PrincipalName({'name-type': NAME_TYPE.PRINCIPAL.value, 'name-string': ['krbtgt', self.usercreds.domain.upper()]}) kdc_req_body['till'] = (now + datetime.timedelta(days=1)).replace(microsecond=0) kdc_req_body['rtime'] = (now + datetime.timedelta(days=1)).replace(microsecond=0) kdc_req_body['nonce'] = secrets.randbits(31) kdc_req_body['etype'] = [supp_enc.value] kdc_req = {} kdc_req['pvno'] = krb5_pvno kdc_req['msg-type'] = MESSAGE_TYPE.KRB_AS_REQ.value kdc_req['padata'] = [pa_data_2,pa_data_1] kdc_req['req-body'] = KDC_REQ_BODY(kdc_req_body) req = AS_REQ(kdc_req) logger.debug('Sending TGT request to server') return self.ksoc.sendrecv(req.dump())