當前位置: 首頁>>代碼示例>>Python>>正文


Python secrets.randbits方法代碼示例

本文整理匯總了Python中secrets.randbits方法的典型用法代碼示例。如果您正苦於以下問題:Python secrets.randbits方法的具體用法?Python secrets.randbits怎麽用?Python secrets.randbits使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在secrets的用法示例。


在下文中一共展示了secrets.randbits方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: construct_tgt_req

# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import randbits [as 別名]
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) 
開發者ID:skelsec,項目名稱:minikerberos,代碼行數:25,代碼來源:security.py

示例2: sample_poly_uniform

# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import randbits [as 別名]
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 
開發者ID:OpenMined,項目名稱:PySyft,代碼行數:30,代碼來源:rlwe.py

示例3: randbinstr

# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import randbits [as 別名]
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) 
開發者ID:fametrano,項目名稱:btclib,代碼行數:40,代碼來源:entropy.py

示例4: test_zeroleadingbit

# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import randbits [as 別名]
def test_zeroleadingbit():
    # it should not throw an error
    bip39.mnemonic_from_entropy(secrets.randbits(127), "en") 
開發者ID:fametrano,項目名稱:btclib,代碼行數:5,代碼來源:test_bip39.py

示例5: __init_pool

# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import randbits [as 別名]
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) 
開發者ID:Destiner,項目名稱:blocksmith,代碼行數:8,代碼來源:generator.py

示例6: randbits

# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import randbits [as 別名]
def randbits(nb):
            return random.Random().getrandbits(nb) 
開發者ID:Preston-Landers,項目名稱:concurrent-log-handler,代碼行數:4,代碼來源:__init__.py

示例7: randint

# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import randbits [as 別名]
def randint(n):
        return secrets.randbits(n) 
開發者ID:arantonitis,項目名稱:pynat,代碼行數:4,代碼來源:pynat.py

示例8: secure_rand_port

# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import randbits [as 別名]
def secure_rand_port(cls):
        while True:
            port = secrets.randbits(16)
            if port < 1024:
                continue
            return port 
開發者ID:Margular,項目名稱:frida-skeleton,代碼行數:8,代碼來源:port_manager.py

示例9: generate_nonce

# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import randbits [as 別名]
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()) 
開發者ID:kylebebak,項目名稱:Requester,代碼行數:15,代碼來源:common.py

示例10: _mk_private_key_bytes

# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import randbits [as 別名]
def _mk_private_key_bytes() -> bytes:
    return int_to_big_endian(secrets.randbits(256)).rjust(32, b'\x00') 
開發者ID:ethereum,項目名稱:py-evm,代碼行數:4,代碼來源:keys.py

示例11: get_commit

# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import randbits [as 別名]
def get_commit(inst):
    jackpot = secrets.randbits(10)
    blind = inst.getrandbits(32)
    commit = hashlib.md5(str(jackpot+blind).encode()).hexdigest()
    return [commit,jackpot,blind] 
開發者ID:InsecurityAsso,項目名稱:inshack-2018,代碼行數:7,代碼來源:server.py

示例12: lookup_random

# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import randbits [as 別名]
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) 
開發者ID:ethereum,項目名稱:trinity,代碼行數:7,代碼來源:discovery.py

示例13: get_nonce

# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import randbits [as 別名]
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 
開發者ID:TruSat,項目名稱:trusat-backend,代碼行數:42,代碼來源:flask_server.py

示例14: test_randbits

# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import randbits [as 別名]
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)) 
開發者ID:bkerler,項目名稱:android_universal,代碼行數:9,代碼來源:test_secrets.py

示例15: do_preauth

# 需要導入模塊: import secrets [as 別名]
# 或者: from secrets import randbits [as 別名]
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()) 
開發者ID:skelsec,項目名稱:minikerberos,代碼行數:63,代碼來源:client.py


注:本文中的secrets.randbits方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。