本文整理汇总了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)
示例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
示例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)
示例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")
示例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)
示例6: randbits
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import randbits [as 别名]
def randbits(nb):
return random.Random().getrandbits(nb)
示例7: randint
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import randbits [as 别名]
def randint(n):
return secrets.randbits(n)
示例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
示例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())
示例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')
示例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]
示例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)
示例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
示例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))
示例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())