本文整理汇总了Python中random.SystemRandom类的典型用法代码示例。如果您正苦于以下问题:Python SystemRandom类的具体用法?Python SystemRandom怎么用?Python SystemRandom使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SystemRandom类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: createUserSessionKey
def createUserSessionKey(org, username, sessionId,
consistency=ConsistencyLevel.LOCAL_QUORUM,
session=None):
"""
Create a session key record in the usersessionkeys table for the given
user session
:org:
Name of organization for the user
:username:
Name of the user
:sessionid:
ID of the session to create a key for
"""
charList = (list(range(48, 58)) + # Numbers
list(range(65, 91)) + # Uppercase
list(range(97, 123))) # Lowercase
sysrand = SystemRandom()
sessionKey = ''.join(
chr(sysrand.choice(charList))
for i in range(64))
try:
createUserSessionKeyQuery = CassandraCluster.getPreparedStatement(
"""
INSERT INTO usersessionkeys ( sessionkey, org, username,
sessionid )
VALUES ( ?, ?, ?, ? )
""", keyspace=session.keyspace)
createUserSessionKeyQuery.consistency_level = consistency
session.execute(createUserSessionKeyQuery,
(sessionKey, org, username, sessionId))
return sessionKey
except Exception as e:
log.critical("Exception in AuthDB.createUserSessionKey: %s" % (e,))
示例2: check_collisions
def check_collisions(upper_bound):
"""
Function that keeps guessing random numbers 1 to N incluside, until it hits a collision (or doesn't)
"""
cryptogen = SystemRandom() # OS Internal system for generating cryptographic random numbers
already_found = set([]) # Set of numbers the adversary already found
iterations = 1
start = time.time()
found = False
try:
while not found: # Runs until a collision is found
item = cryptogen.randrange(1,upper_bound) # Uses the cryptographically secure PRNG to generate a random number
if item in already_found: # If it's in the set of things already found - print the statistics
found = True
print "duplicate found in %.2e tries in %f seconds" % (iterations, time.time()-start)
print "The upper bound on this probability is %.2f %%" % (coll(iterations,upper_bound)*100)
else: # If it's a new number, add it to the set of numbers checked
already_found.add(item)
iterations+=1
except KeyboardInterrupt: # If someone cancels the program midway - prints some statistics about the current progress
total_time = time.time()-start
print "Program cancelled - made %.2e attempts in %.4f seconds" % (iterations, total_time)
print "The upper bound on getting a duplicate is %.2f %%" % (coll(iterations,upper_bound)*100)
onepercent = ntimes(.01,upper_bound)
rate = total_time/iterations
seconds = onepercent*rate
print "To have 1%% probability of guessing you need at least %d tries, at this rate it would take %f seconds" % (onepercent, seconds)
print "%.2f minutes, %.2f hours, %.2f days, %.2f years" % (seconds/60, seconds/60/60, seconds/60/60/24, seconds/60/60/24/365)
示例3: __init__
def __init__(self, config, director, scheduler, _reactor=reactor):
self._reactor = reactor
self.director = director
self.scheduler = scheduler
self.config = config
self.measurement_path = FilePath(config.measurements_directory)
# We use a double submit token to protect against XSRF
rng = SystemRandom()
token_space = string.letters+string.digits
self._xsrf_token = b''.join([rng.choice(token_space)
for _ in range(30)])
self._director_started = False
self._is_initialized = config.is_initialized()
# We use exponential backoff to trigger retries of the startup of
# the director.
self._director_startup_retries = 0
# Maximum delay should be 30 minutes
self._director_max_retry_delay = 30*60
self.status_poller = LongPoller(
self._long_polling_timeout, _reactor)
self.director_event_poller = LongPoller(
self._long_polling_timeout, _reactor)
# XXX move this elsewhere
self.director_event_poller.start()
self.status_poller.start()
self.director.subscribe(self.handle_director_event)
if self._is_initialized:
self.start_director()
示例4: client_func
def client_func(E, P, Q):
n = E.order
gen = SystemRandom()
an = gen.randrange(n)
bn = gen.randrange(n)
am = an
bm = bn
Xn = P*an + Q*bn
Xm = Xn
while (True):
i = __H(Xn, L)
Xn += R[i]
an += c[i]
bn += d[i]
for j in range(2):
h = __H(Xm, L)
Xm += R[h]
am += c[h]
bm += d[h]
if Xn == Xm:
break
if (bn == bm):
raise ArithmeticError('Undefined value')
f = an-am
g = invmod(bm-bn, n)
ret = (f * g) % n
ret = (ret + n) % n
sendToServer(ret)
示例5: generate_groups
def generate_groups(self):
"""
Generates the groups based on a randomization algorithm.
:return: the generated groups: a list of lists (names)
"""
if not self.names:
raise AttributeError("Could not find names list. Try re-initializing Engine with valid filepath.")
groups = []
cryptogen = SystemRandom()
cryptogen.shuffle(self.names)
current_group = []
for name in self.names:
current_group.append(name)
is_last_name = self.names.index(name) == len(self.names) - 1
is_group_full = len(current_group) == self.group_size
if is_group_full or is_last_name:
groups.append(current_group)
current_group = []
logging.info("Created {} groups with max size {}.".format(len(groups), self.group_size))
return groups
示例6: __init__
def __init__(self, known_pattern=None, session=db_session):
'''Instantiates a color game based on a random color pattern.
If known_pattern is specified, this color pattern is used to create the game
instead of a random pattern. This should only be used for testing purposes.
If session is specified, this DB session is used instead of the standard session.
:param known_pattern: a list (or tuple) of one-letter colors (default: None)
:param session: the DB session (default: standard color game session)
'''
# Make sure to cleanup database resources on exit
register(self._cleanup)
# Set up DB session
self.s = session
if known_pattern is None:
sr = SystemRandom()
self.pattern = [sr.choice(colors_short) for _ in range(PATTERN_LENGTH)]
else:
self.pattern = known_pattern
self.pattern_set = set(self.pattern)
self.game = ColorGame(pattern=ColorPattern(self.pattern))
self.s.add(self.game)
self.s.commit()
示例7: get_passphrase
def get_passphrase(wordnum=6, specialsnum=1, delimiter='', lang='en',
capitalized=True, wordlist_fd=None):
"""Get a diceware passphrase.
The passphrase returned will contain `wordnum` words deliimted by
`delimiter`.
If `capitalized` is ``True``, all words will be capitalized.
If `wordlist_fd`, a file descriptor, is given, it will be used
instead of a 'built-in' wordlist (and `lang` will be
ignored). `wordlist_fd` must be open for reading.
The wordlist to pick words from is determined by `lang`,
representing a language (unless `wordlist_fd` is given).
"""
if wordlist_fd is None:
wordlist_fd = open(get_wordlist_path(lang), 'r')
word_list = get_wordlist(wordlist_fd)
rnd = SystemRandom()
words = [rnd.choice(word_list) for x in range(wordnum)]
if capitalized:
words = [x.capitalize() for x in words]
result = delimiter.join(words)
for _ in range(specialsnum):
result = insert_special_char(result, rnd=rnd)
return result
示例8: sign
def sign(self, message):
""" Signs message using ECDSA.
:param message: bytes to sign
:return: bytes representing r, s.
"""
m = hashlib.sha256()
m.update(message)
e = m.digest()
ln = self.sign_curve.order.bit_length() // 8
n = self.sign_curve.order
z = e[0:ln]
z = int.from_bytes(z, byteorder="big") # Matching the BigInteger form in the java signing.
certificate = 0
while certificate == 0:
rng = SystemRandom()
k = rng.randint(1, n)
kg = self.sign_curve.get_member(k)
r = kg.x
if r == 0:
continue
s = (mod_inv(k, n) * (z + (r * self.sign_key) % n) % n) % n
if s == 0:
continue
l = [r, s]
int_length = self.sign_curve.int_length // 8
certificate = list_to_bytes(l, int_length)
return certificate
示例9: new_password
def new_password(self, user, passhash):
"""
Return new random password
"""
chars = '23456qwertasdfgzxcvbQWERTASDFGZXCVB789yuiophjknmYUIPHJKLNM'
r = SystemRandom()
return ''.join(r.sample(chars, 8))
示例10: random_password
def random_password(description, min_chars=10, max_chars=20):
"""
Creates a random password from uppercase letters, lowercase letters and
digits with a length between min_chars and max_chars
"""
# Open saved passwords file or create new one.
try:
fh = open("info/passwords.json", "r+")
passwords = json.load(fh)
except IOError:
fh = open("info/passwords.json", "w+")
passwords = {}
# Return password if it exists already
if description in passwords:
fh.close()
return passwords[description]
# Create new password if it does not exist
else:
seeded_random = SystemRandom()
chars = ascii_letters + digits
password_length = seeded_random.randint(min_chars, max_chars)
password = "".join(seeded_random.choice(chars) for _ in range(password_length))
passwords[description] = password
fh.seek(0)
json.dump(passwords, fh, indent=4)
fh.close()
return password
示例11: populate
def populate(self, *excludePSets):
"""
_populate_
generate a bunch of seeds and stick them into this service
This is the lazy user method.
Optional args are names of PSets to *NOT* alter seeds.
Eg:
populate() will set all seeds
populate("pset1", "pset2") will set all seeds but not those in
psets named pset1 and pset2
"""
import random
from random import SystemRandom
_inst = SystemRandom()
_MAXINT = 900000000
# //
# // count seeds and create the required number of seeds
#//
newSeeds = [ _inst.randint(1, _MAXINT)
for i in range(self.countSeeds())]
self._lockedSeeds = list(excludePSets)
self.insertSeeds(*newSeeds)
self._lockedSeeds = []
return
示例12: csprng
def csprng(low, high, offset=0):
rng = SystemRandom()
rnum = rng.randint(low, high-1) + offset
if rnum < 0:
print("[-] Error: Random number generator returned out of bounds.")
return None
return rnum
示例13: generate_config
def generate_config(self, env_script, start_script, server_cert=None):
"""Generates the plugin configuration file
Parameters
----------
env_script : str
The CLI call used to load the environment in which the plugin is
installed
start_script : str
The script used to start the plugin
server_cert : str, optional
If the Qiita server used does not have a valid certificate, the
path to the Qiita certificate so the plugin can connect over
HTTPS to it
"""
logger.debug('Entered BaseQiitaPlugin.generate_config()')
sr = SystemRandom()
chars = ascii_letters + digits
client_id = ''.join(sr.choice(chars) for i in range(50))
client_secret = ''.join(sr.choice(chars) for i in range(255))
server_cert = server_cert if server_cert else ""
with open(self.conf_fp, 'w') as f:
f.write(CONF_TEMPLATE % (self.name, self.version, self.description,
env_script, start_script,
self._plugin_type, self.publications,
server_cert, client_id, client_secret))
示例14: generate_password
def generate_password(self):
import string
from random import SystemRandom
rnd = SystemRandom() # use SystemRandom to get real random numbers
chars = string.letters + string.digits
length = 20
return "".join(rnd.choice(chars) for _ in range(length))
示例15: generate
def generate(word_list, words=5, specials=0):
rnd = SystemRandom()
words = [ rnd.choice(word_list) for _ in range(words) ]
# Insert at most options.special special characters. This is not
# exactly the procedure described in the Diceware web page, because
# this handles the case where there are more than 6 words in the
# passphrase and more than 6 characters in the word.
if specials:
split_words = [ map(None, x) for x in words ]
for _ in range(specials):
# i is the index of the word in which the special character
# replacement takes place.
i = rnd.randrange(len(split_words))
# j is the index of the character to be replaced with a special
# character.
j = rnd.randrange(len(split_words[i]))
# k is the index of the special character
k = rnd.randrange(len(SPECIAL_CHARS))
# Split to individual characters, replace the k'th char, unsplit
split_words[i][j] = SPECIAL_CHARS[k]
with_specials = [ "".join(x) for x in split_words ]
else:
with_specials = words
return words, with_specials