本文整理汇总了Python中random.SystemRandom.randrange方法的典型用法代码示例。如果您正苦于以下问题:Python SystemRandom.randrange方法的具体用法?Python SystemRandom.randrange怎么用?Python SystemRandom.randrange使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类random.SystemRandom
的用法示例。
在下文中一共展示了SystemRandom.randrange方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate
# 需要导入模块: from random import SystemRandom [as 别名]
# 或者: from random.SystemRandom import randrange [as 别名]
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
示例2: roll
# 需要导入模块: from random import SystemRandom [as 别名]
# 或者: from random.SystemRandom import randrange [as 别名]
def roll(count, sides):
results = []
rand = SystemRandom()
for x in range(count):
if sides == 100 or sides == 1000:
#Special Case for 100 sized dice
results.append(rand.randint(1, 10))
results.append(rand.randrange(0, 100, 10))
if sides == 1000:
results.append(rand.randrange(0, 1000, 100))
else:
results.append(rand.randint(1, sides))
return results
示例3: create_captcha
# 需要导入模块: from random import SystemRandom [as 别名]
# 或者: from random.SystemRandom import randrange [as 别名]
def create_captcha():
rand = SystemRandom()
left_number_index = rand.randrange(0, len(NUMBER_WORDS))
right_number_index = rand.randrange(0, len(NUMBER_WORDS))
operator_index = rand.randrange(0, len(OPERATORS))
answer = OPERATORS[operator_index][1](left_number_index, right_number_index)
return (
'Was ist {:s} {:s} {:s}?'.format(
NUMBER_WORDS[left_number_index],
OPERATORS[operator_index][0],
NUMBER_WORDS[right_number_index]
),
answer,
)
示例4: newAccount
# 需要导入模块: from random import SystemRandom [as 别名]
# 或者: from random.SystemRandom import randrange [as 别名]
def newAccount():
"""
Create's a new account under this user. Balance
is always 0
"""
try:
check_params(request, ["session", "pin"])
user = validate_session(request.form["session"])
except StandardError as e:
return respond(str(e), code=400), 400
gen = SystemRandom()
accnum = str(''.join(map(str, [gen.randrange(9) for i in range(10)])))
pin = int(request.form["pin"])
newaccount = Account(accnum, user, 0.00, pin)
try:
db.session.add(newaccount)
db.session.commit()
add_log(LOG_ACCOUNT, "User %s created a new account (%s)" % (user.username, accnum))
except:
db.session.rollback()
return respond("An internal error has occured. Please try again.", code=400), 400
# Delete their session
delete_session(request.form["session"])
return respond("Account created!", data={'account': newaccount.id, 'pin': newaccount.pin})
示例5: client_func
# 需要导入模块: from random import SystemRandom [as 别名]
# 或者: from random.SystemRandom import randrange [as 别名]
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)
示例6: check_collisions
# 需要导入模块: from random import SystemRandom [as 别名]
# 或者: from random.SystemRandom import randrange [as 别名]
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)
示例7: generate_salt
# 需要导入模块: from random import SystemRandom [as 别名]
# 或者: from random.SystemRandom import randrange [as 别名]
def generate_salt():
# This uses os.urandom() underneath
cryptogen = SystemRandom()
# Create 16 byte hex salt
salt_sequence = [cryptogen.randrange(256) for _ in range(16)]
return ''.join([format(r, 'x') for r in salt_sequence])
示例8: createRandomToken
# 需要导入模块: from random import SystemRandom [as 别名]
# 或者: from random.SystemRandom import randrange [as 别名]
def createRandomToken(self):
'''Create a random byte sequence to use as a repeating token'''
r = SystemRandom()
token = bytearray()
numBytes = r.choice([3, 4, 5, 6])
for i in range(numBytes):
token.append(r.randrange(256))
return token
示例9: get_prime
# 需要导入模块: from random import SystemRandom [as 别名]
# 或者: from random.SystemRandom import randrange [as 别名]
def get_prime(low, high):
csprng = SystemRandom()
n = csprng.randrange(low, high)
if n % 2 == 0:
n += 1
while not miller_rabin(n):
n += 2
return n
示例10: serial
# 需要导入模块: from random import SystemRandom [as 别名]
# 或者: from random.SystemRandom import randrange [as 别名]
def serial(E, P, Q):
print 'Algorithm: serial'
c = []; d = []; R = []
n = E.order
L = 4
gen = SystemRandom()
for i in range(L):
c.append(gen.randrange(n-1)+1)
d.append(gen.randrange(n-1)+1)
R.append(P*c[-1] + Q*d[-1])
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
return (ret + n) % n
示例11: _gen_key
# 需要导入模块: from random import SystemRandom [as 别名]
# 或者: from random.SystemRandom import randrange [as 别名]
def _gen_key():
from random import SystemRandom
r = SystemRandom()
l = r.randrange(len(KEY_DIGITS)**KEY_LENGTH)
key = ''
while l >= KEY_BASE:
remainder = l % KEY_BASE
key += KEY_DIGITS[remainder]
l = l / KEY_BASE
key += KEY_DIGITS[l]
key = key[::-1]
return key
示例12: random_prime
# 需要导入模块: from random import SystemRandom [as 别名]
# 或者: from random.SystemRandom import randrange [as 别名]
def random_prime():
random = SystemRandom()
prime_generator = iter(primes())
prime_number = next(prime_generator)
for _ in range(random.randrange(42)):
prime_number = next(prime_generator)
while not is_marsenne_prime(prime_number):
prime_number = next(prime_generator)
return marsenne_number(prime_number)
示例13: main
# 需要导入模块: from random import SystemRandom [as 别名]
# 或者: from random.SystemRandom import randrange [as 别名]
def main():
if os.access("/usr/share/dict/words", os.R_OK): # Debian
file = "/usr/share/dict/words"
elif os.access("/usr/share/dict/linux.words", os.R_OK): # CentOS
file = "/usr/share/dict/linux.words"
elif os.access("words.txt", os.R_OK): # cwd, Windows, user-placed file
file = "words.txt"
else:
sys.exit("Could not locate the system dictionary file - please manually edit the file location.")
if benchmark:
start = time.time()
file = open(file, "r")
wordlist = file.readlines()
file.close()
cryptogen = SystemRandom()
wordindexes = [cryptogen.randrange(len(wordlist)) for i in range(numwords)]
words = [wordlist[index] for index in wordindexes]
if numerifywords: # enact before capitalization
words = [word.replace("o", "0") for word in words] # 'o' to zero: just one way of mangling letters
# words = [word.replace('a', '@') for word in words]
# words = [word.replace('s', '5') for word in words]
words = [word.capitalize() for word in words]
words = [word.rstrip() for word in words] # remove line breaks
words = [word.replace("'s", "") for word in words] # remove apostrophe s
rndnumber = cryptogen.randrange(numberlimit)
print("".join(words) + str(rndnumber))
if benchmark:
print("\ntime taken " + str(time.time() - start) + " sec")
示例14: __init__
# 需要导入模块: from random import SystemRandom [as 别名]
# 或者: from random.SystemRandom import randrange [as 别名]
class RandomGenerator:
def __init__(self):
self.gen = SystemRandom()
def get_random_vector(self, length):
random_vector = np.array([self.gen.randrange(2) for i in range(length)])
return random_vector
def get_random_weight_vector(self, length, weight):
random_indices = set([self.gen.randrange(length) for i in range(weight)])
while len(random_indices) < weight:
random_indices.update([self.gen.randrange(length)])
random_vector = np.zeros(length, dtype='int')
random_vector[list(random_indices)] = 1
return random_vector
def flip_coin(self):
return self.gen.randrange(2)
示例15: rand
# 需要导入模块: from random import SystemRandom [as 别名]
# 或者: from random.SystemRandom import randrange [as 别名]
def rand(end, start=None, step=None):
r = SystemRandom()
if isinstance(end, (int, long)):
if not start:
start = 0
if not step:
step = 1
return r.randrange(start, end, step)
elif hasattr(end, '__iter__'):
if start or step:
raise errors.AnsibleFilterError('start and step can only be used with integer values')
return r.choice(end)
else:
raise errors.AnsibleFilterError('random can only be used on sequences and integers')