我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用random.SystemRandom()。
def add_spans(): """Calls the opentracing API, doesn't use any LightStep-specific code. """ with opentracing.tracer.start_span(operation_name='trivial/initial_request') as parent_span: parent_span.set_tag('url', 'localhost') parent_span.log_event('All good here!', payload={'N': 42, 'pi': 3.14, 'abc': 'xyz'}) parent_span.set_tag('span_type', 'parent') parent_span.set_baggage_item('checked', 'baggage') rng = random.SystemRandom() for i in range(50): time.sleep(rng.random() * 0.2) sys.stdout.write('.') sys.stdout.flush() # This is how you would represent starting work locally. with opentracing.start_child_span(parent_span, operation_name='trivial/child_request') as child_span: child_span.log_event('Uh Oh!', payload={'error': True}) child_span.set_tag('span_type', 'child') # Play with the propagation APIs... this is not IPC and thus not # where they're intended to be used. text_carrier = {} opentracing.tracer.inject(child_span.context, opentracing.Format.TEXT_MAP, text_carrier) span_context = opentracing.tracer.extract(opentracing.Format.TEXT_MAP, text_carrier) with opentracing.tracer.start_span( 'nontrivial/remote_span', child_of=span_context) as remote_span: remote_span.log_event('Remote!') remote_span.set_tag('span_type', 'remote') time.sleep(rng.random() * 0.1) opentracing.tracer.flush()
def index(): if request.args.get('code'): unlock_code = request.args.get('code') # unlock, new password re = s.query(RecoveryEmail).filter(RecoveryEmail.password_code==unlock_code).one_or_none() if re: jid = re.jid re.password_code = None s.merge(re) s.commit() # set new password and send email email_address = re.email password = ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for _ in range(10)) p = subprocess.Popen(['/usr/bin/prosodyctl', 'passwd', jid], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT) args = bytes("%s\n%s\n" % (password, password), encoding='utf8') p.communicate(args) sendMail(email_address, 'new password', password) content = render_template('success.html', message='password was sent') else: content = render_template('error.html', message='link invalid') else: content = render_template('index.html') return content
def try_counters(counters, modulus, N, X=None, multi_bin=True): ''' Validate that a counter run with counters, modulus, N, X, and multi_bin works, and produces consistent results Also try a randomly selected number modulus_random between modulus_min and modulus, and a randomly selected number N_random between 0 and min(q_random, N) and a randomly selected number X_random between 0 and min(q_random, X) If X is None, use the 2-argument form of increment, otherwise, use the 3-argument form ''' # randrange is not uniformly distributed in python versions < 3.2 modulus_random = SystemRandom().randrange(modulus_min, modulus) N_random = SystemRandom().randrange(0, min(modulus_random, N)) X_random = None if X is not None: X_random = SystemRandom().randrange(0, min(modulus_random, X)) run_counters(counters, modulus_random, N_random, X_random, multi_bin) run_counters(counters, modulus, N, X, multi_bin) # Check the counter table is valid, and perform internal checks
def __init__(self): self.dead = SystemRandom().randint(0, 100) < 25 self.responsibility = SystemRandom().randint(0, 0xffffff) self.has_keys = set([SystemRandom().randint(0, 0xffffff) for i in range(SystemRandom().randint(0, 10))]) self.known_nodes = set([nodeName() for i in range(SystemRandom().randint(0, 10))]) self.data = "GOOD_DATA" if (SystemRandom().randint(0, 100) < 50) else "BAD_DATA" r = SystemRandom().randint(0, 100) if r < 10: self.responsibility = KEY self.has_keys.add(KEY) elif r < 25: shift = r % 16 + 1 self.responsibility = (KEY >> shift) << shift elif r < 50: self.has_keys.add(self.responsibility)
def generate_password(size=10, charset=_52charset): """generate random password using given length & charset :param size: size of password. :param charset: optional string specified set of characters to draw from. the default charset contains all normal alphanumeric characters, except for the characters ``1IiLl0OoS5``, which were omitted due to their visual similarity. :returns: :class:`!str` containing randomly generated password. .. note:: Using the default character set, on a OS with :class:`!SystemRandom` support, this function should generate passwords with 5.7 bits of entropy per character. """ return getrandstr(rng, charset, size) #============================================================================= # object type / interface tests #=============================================================================
def SignECDSA(self,m): #Sign a message. The private key is self.d . h=hashlib.new("SHA256") h.update(m) z=int(h.hexdigest(),16) r=0 s=0 while not r or not s: #k=random.randint(1,self.n-1) k=random.SystemRandom().randint(1,self.n-1) # Better random fix R=self*k R.Normalize() r=R.x[0]%self.n s=(InvMod(k,self.n)*(z+r*self.d))%self.n return (r,s)
def randomString(len=16, prefix="TEST:"): """ Create a random string to be used to build data for tests """ if len > 500000: lis = list(string.ascii_lowercase) return ''.join(random.choice(lis) for _ in range(len)) rand = random.SystemRandom() charset = string.ascii_uppercase + string.digits random_string = prefix for _ in range(len): random_string += rand.choice(charset) return random_string
def BIP32_create_master(): rnd = random.SystemRandom() a = rnd.randint(0, MAX_INT_PRIVATE_KEY) i = int((time.time() % 0.01) * 100000) h = a.to_bytes(32, byteorder="big") Key = b"Bitcoin seed" while True: h = hashlib.sha256(h).digest() if i > 1: i -= 1 else: if int.from_bytes(h, byteorder="big") < MAX_INT_PRIVATE_KEY: break I = hmac_sha512(Key, h) M, C = I[:32], I[32:] return b'\x04\x88\xAD\xE4\x00\x00\x00\x00\x00\x00\x00\x00\x00' + C + b'\x00' + M
def _get_random_username_from_email(email): localpart = email.split('@')[0] cleaned_localpart = re.sub(r'[^\w]', '-', localpart).lower() # if we can't create a unique user name within this many attempts # then something else is probably wrong and we should give up max_name_creation_attempts = 100 for i in range(max_name_creation_attempts): random_number = random.SystemRandom().random() * 10000 name = '%s-%d' % (cleaned_localpart, random_number) if not ckan.model.User.get(name): return name return cleaned_localpart ## Modifications for rest api
def _random_password(length=DEFAULT_LENGTH, chars=C.DEFAULT_PASSWORD_CHARS): '''Return a random password string of length containing only chars :kwarg length: The number of characters in the new password. Defaults to 20. :kwarg chars: The characters to choose from. The default is all ascii letters, ascii digits, and these symbols ``.,:-_`` .. note: this was moved from the old ansible utils code, as nothing else appeared to use it. ''' assert isinstance(chars, text_type), '%s (%s) is not a text_type' % (chars, type(chars)) random_generator = random.SystemRandom() password = [] while len(password) < length: new_char = random_generator.choice(chars) password.append(new_char) return u''.join(password)
def test_main(verbose=None): testclasses = [MersenneTwister_TestBasicOps, TestDistributions, TestModule] try: random.SystemRandom().random() except NotImplementedError: pass else: testclasses.append(SystemRandom_TestBasicOps) support.run_unittest(*testclasses) # verify reference counting import sys if verbose and hasattr(sys, "gettotalrefcount"): counts = [None] * 5 for i in range(len(counts)): support.run_unittest(*testclasses) counts[i] = sys.gettotalrefcount() print(counts)
def test_main(verbose=None): testclasses = [WichmannHill_TestBasicOps, MersenneTwister_TestBasicOps, TestDistributions, TestModule] try: random.SystemRandom().random() except NotImplementedError: pass else: testclasses.append(SystemRandom_TestBasicOps) test_support.run_unittest(*testclasses) # verify reference counting import sys if verbose and hasattr(sys, "gettotalrefcount"): counts = [None] * 5 for i in xrange(len(counts)): test_support.run_unittest(*testclasses) counts[i] = sys.gettotalrefcount() print counts
def randPoint(self,can,point_dico): r = 5 secure_random = random.SystemRandom() coord = secure_random.choice(self.randomList) array = coord.split('_') x = int(array[0]) y = int(array[1]) can.create_oval(x-r, y-r, x+r, y+r, fill=self.getColor()) point = {} point['x'] = x point['y'] = y return point #Dictionnaire de point de l'IA. ce Dictionnaire permettra de connaitre tous les emplacements des points de l'IA.
def insertFuzz(url, fuzz): """ :Description: This function inserts the Fuzz as GET Parameter in the URL :param url: Target URL :type type: String :param fuzz: Fuzzing string :type fuzz: String :return: The URL with a concatenated string consisting of a random string and the fuzz. :note: Some fuzzing symbols can be part of a normal response. In order to distinctly find the fuzz that was sent, a random string is added before the fuzz. """ fuzz = urllib.quote_plus(fuzz) #url encoding randomString = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(6)) return randomString, url.replace('FUZZ', randomString + str(fuzz))
def setParams(params, fuzz): """ :Description: This function sets the Fuzz in the POST Parameter. :param url: Target URL :type type: String :param fuzz: Fuzzing string :type fuzz: String :return: The post parameter with a concatenated string consisting of a random string and the fuzz :note: Some fuzzing symbols can be part of a normal response. In order to distinctly find the fuzz that was sent, a random string is added before the fuzz. """ randomString = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(6)) parameter = copy.deepcopy(params) #makes a deep copy. this is needed because using a reference does not work for param in parameter: if parameter[param] == 'FUZZ': parameter[param] = randomString + str(fuzz) return randomString, parameter;
def test_post_large_message(self): blob_size = 100000 for i in range(0,2): message = ''.join(chr(random.SystemRandom().randint(0,255)) for _ in range(random.SystemRandom().randint(blob_size,blob_size*10))) pre_shared_key = '0192837465OKMijnUHBygv' #generate the encrypted package enc_derived_key, enc_salt, enc_iv, real_gist_file_name = gister_transmit.generate_key_material(pre_shared_key) encrypted_package = gister_transmit.generate_upload_package(message, enc_derived_key, enc_iv, real_gist_file_name) gist_id = gister_transmit.upload_package_to_gist(encrypted_package) #pass the encrypted package, key, and iv to the decrypter time.sleep(5) encrypted_package = gister_receive.retrieve_message(gist_id) decrypted_message = gister_receive.decrypt_message(encrypted_package, enc_derived_key) self.assertTrue(decrypted_message == message)
def random_base32_token(length: int=16, rng=random.SystemRandom(), charset='ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'): """ This method just provides a quick way to obtain a proper key to use for a 2-factor authentication secret key. :param length: Normally 16 :type length: int :param rng: Normally, the system RNG :type rng: method :param charset: The base32 character set :type charset: str :return: A 16-character base32 encoded token :rtype: str """ token = ''.join(rng.choice(charset) for i in range(length)) return '-'.join((token[0:4], token[4:8], token[8:12], token[12:16]))
def pwgen(length=None): """Generate a random pasword.""" if length is None: # A random length is ok to use a weak PRNG length = random.choice(range(35, 45)) alphanumeric_chars = [ l for l in (string.ascii_letters + string.digits) if l not in 'l0QD1vAEIOUaeiou'] # Use a crypto-friendly PRNG (e.g. /dev/urandom) for making the # actual password random_generator = random.SystemRandom() random_chars = [ random_generator.choice(alphanumeric_chars) for _ in range(length)] return(''.join(random_chars))
def ran(N): return ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N)) #given a string s, returns a list containing an encrypted string and a key
def crypt_secure_randint(r): ''' input: r : the range in which we want the random integer [-r,r] output: a cryptographiically secure random integer in [-r,r] ''' cryptogen = SystemRandom() #takes entropy from operating system return cryptogen.randrange(-r,r+1)
def crypt_secure_randint(a, b): ''' input: r : the range in which we want the random integer [a,b] output: a cryptographiically secure random integer in [a,b] ''' cryptogen = SystemRandom() #takes entropy from operating system return cryptogen.randrange(a, b+1)
def request_password(): jid = request.form.get('jid') re = s.query(RecoveryEmail).filter(RecoveryEmail.jid==jid, RecoveryEmail.confirmed==True).one_or_none() if re: password_code = ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for _ in range(64)) re.password_code = password_code s.merge(re) s.commit() password_code_link = 'https://www.pimux.de/password/?code=%s' % password_code sendMail(re.email, 'password reset request', 'click here: %s' % password_code_link) content = render_template('success.html', message='link was sent') else: content = render_template('error.html', message='user not found') return content
def getRandomString(n): return ''.join(random.SystemRandom().choice( string.ascii_lowercase + string.digits) for _ in range(n))
def get_http_header(self, options=None, pki_string=None): header = {"Accept": "application/json", "Content-type": "application/json"} if pki_string is not None: random_header_value = "".join( random.SystemRandom().choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for _ in range(self.RANDOM_STRING_SIZE)) header.update( {'Authorization': self.prepare_auth_string(options, random_header_value, pki_string)}) header.update({'x-iyzi-rnd': random_header_value}) header.update({'x-iyzi-client-version': 'iyzipay-python-1.0.29'}) return header
def generatePhrase(numWords): phrase = re.compile("[0-9]+\t(.*)") path_to_diceware = resource_filename("factotum", "diceware.wordlist.asc") with open(path_to_diceware, "r") as diceware: password = diceware.readlines() password = [m.group(1) for l in password for m in [phrase.search(l)] if m] random.SystemRandom().shuffle(password) return ' '.join(password[0:numWords])
def _get_random(self, length=64): valid_chars = string.ascii_letters + string.digits + '-' + '_' return ''.join(random.SystemRandom().choice(valid_chars) for x in range(length))
def _generate_oauth_nonce(cls, length=8): return ''.join([str(random.SystemRandom().randint(0, 9)) for _ in range(length)])
def random_value(modulus): ''' call python's random.randrange(modulus) ''' # random.randrange() takes one argument: a maximum value # and returns a random value in [0, modulus) # it is *NOT* uniformy distributed in python versions < 3.2 # but this test is not sophisticated enough to pick that up # https://docs.python.org/3.5/library/random.html#random.randrange return SystemRandom().randrange(modulus)
def try_adjust_count_signed(modulus): ''' check that adjust_count_signed works as expected for modulus, and a randomly chosen number between modulus_min and modulus ''' # randrange is not uniformly distributed in python versions < 3.2 modulus_random = SystemRandom().randrange(modulus_min, modulus) check_adjust_count_signed(modulus_random) check_adjust_count_signed(modulus)
def noise(sigma, sum_of_sq, p_exit): ''' Sample noise from a gussian distribution the distribution is over +/- sigma, scaled by the noise weight, which is calculated from the exit probability p_exit, and the overall sum_of_sq bandwidth returns a floating-point value between +sigma and -sigma, scaled by noise_weight ''' sigma_i = p_exit * sigma / sqrt(sum_of_sq) # the noise needs to be cryptographically secure, because knowing the RNG # state could allow an adversary to remove the noise random_sample = SystemRandom().gauss(0, sigma_i) return random_sample
def sample(modulus): ''' Sample a uniformly distributed value from the SystemRandom CSPRNG (uses rejection sampling to avoid bias) returns a long uniformly distributed in [0, modulus) ''' # sanitise input modulus = long(modulus) assert modulus > 0 # to get values up to modulus-1, we need this many bits sample_bit_count = (modulus-1).bit_length() # handle the case where modulus is 1 if sample_bit_count == 0: sample_bit_count = 1 # check the bit count is sane assert modulus <= 2L**sample_bit_count assert modulus >= 2L**(sample_bit_count-1) ## Unbiased sampling through rejection sampling while True: # sample that many bits v = SystemRandom().getrandbits(sample_bit_count) assert v >= 0 assert v < 2L**sample_bit_count # the maximum rejection rate is 1 in 2, when modulus is 2**N + 1 if 0L <= v < modulus: break return v
def init_key(ctx): try: key = ctx.SHARED_KEY = os.environ['SHARED_KEY'] except KeyError: key = "".join([chr(random.SystemRandom().randint(40, 126)) for x in range(20)]) os.environ['SHARED_KEY'] = ctx.SHARED_KEY = key os.environ['PREFORKPID'] = str(os.getpid()) return key
def nodeName(): return SystemRandom().choice(list(node_names))
def makeNames(n): for node in BOOTSTRAP: node_names.add(node) for i in range(n): name = SystemRandom().choice(LETTERS) + SystemRandom().choice(LETTERS) node_names.add(name)