本文整理匯總了Python中random.SystemRandom方法的典型用法代碼示例。如果您正苦於以下問題:Python random.SystemRandom方法的具體用法?Python random.SystemRandom怎麽用?Python random.SystemRandom使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類random
的用法示例。
在下文中一共展示了random.SystemRandom方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: reset_config
# 需要導入模塊: import random [as 別名]
# 或者: from random import SystemRandom [as 別名]
def reset_config(self):
original_items = self.__items__
try:
import random
import string
# If config file not found, create a new random string as token
token = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(32))
with open(self.config_path, 'w') as outfile:
with self._mutex:
original_items.update(dict(
token=token,
registered=False,
ws_host="wss://www.getanywhere.io",
api_host="https://www.getanywhere.io",
stream_host="http://stream.getanywhere.io"
))
self.__items__ = original_items
yaml.dump(self.__items__, outfile, default_flow_style=False)
except:
self.sentry.captureException()
import traceback; traceback.print_exc()
示例2: test_main
# 需要導入模塊: import random [as 別名]
# 或者: from random import SystemRandom [as 別名]
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
示例3: get_engine_arguments
# 需要導入模塊: import random [as 別名]
# 或者: from random import SystemRandom [as 別名]
def get_engine_arguments(self, engine):
"""Return a list of fuzzer options."""
arguments = {}
for option_name, option_value in six.iteritems(
self._get_option_section(engine)):
# Check option value for usage of random() function.
match = self.OPTIONS_RANDOM_REGEX.match(option_value)
if match:
min_value, max_value = match.groups()
option_value = str(random.SystemRandom().randint(
int(min_value), int(max_value)))
if option_name == 'dict':
option_value = self._get_dict_path(option_value)
arguments[option_name] = option_value
return FuzzerArguments(arguments)
示例4: _get_fuzzer_binary_name_and_path
# 需要導入模塊: import random [as 別名]
# 或者: from random import SystemRandom [as 別名]
def _get_fuzzer_binary_name_and_path(self):
"""Returns the fuzzer binary name and its path."""
# Fuchsia doesn't use file paths to call fuzzers, just the name of the
# fuzzer, so we set both from FUZZ_TARGET here.
if environment.platform() == 'FUCHSIA':
fuzzer_binary_name = fuzzer_path = environment.get_value('FUZZ_TARGET')
return fuzzer_binary_name, fuzzer_path
build_directory = environment.get_value('BUILD_DIR')
if not build_directory:
raise BuiltinFuzzerException('BUILD_DIR environment variable is not set.')
fuzzers = fuzzers_utils.get_fuzz_targets(build_directory)
if not fuzzers:
raise BuiltinFuzzerException(
'No fuzzer binaries found in |BUILD_DIR| directory.')
fuzzer_binary_name = environment.get_value('FUZZ_TARGET')
if fuzzer_binary_name:
fuzzer_path = _get_fuzzer_path(fuzzers, fuzzer_binary_name)
else:
fuzzer_path = random.SystemRandom().choice(fuzzers)
fuzzer_binary_name = os.path.basename(fuzzer_path)
return fuzzer_binary_name, fuzzer_path
示例5: insertFuzz
# 需要導入模塊: import random [as 別名]
# 或者: from random import SystemRandom [as 別名]
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))
示例6: setParams
# 需要導入模塊: import random [as 別名]
# 或者: from random import SystemRandom [as 別名]
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;
示例7: _get_random_username_from_email
# 需要導入模塊: import random [as 別名]
# 或者: from random import SystemRandom [as 別名]
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
示例8: split_secret
# 需要導入模塊: import random [as 別名]
# 或者: from random import SystemRandom [as 別名]
def split_secret(threshold, total, secret):
if not isinstance(secret, bytes):
raise TypeError("Secret as byte string required")
if threshold > 255:
raise ValueError("threshold <= 255")
if total > 255:
raise ValueError("total shares <= 255")
shares = dict()
for i in range(total):
shares[i+1] = b""
for b in secret:
q = [b]
for i in range(threshold - 1):
a = random.SystemRandom().randint(0, 255)
q.append(a)
for x in range(total):
shares[x+1] += bytes([_fn(x + 1, q)])
return shares
示例9: generate_entropy
# 需要導入模塊: import random [as 別名]
# 或者: from random import SystemRandom [as 別名]
def generate_entropy(strength=256, hex=True):
"""
Generate 128-256 bits entropy bytes string
:param int strength: entropy bits strength, by default is 256 bit.
:param boolean hex: return HEX encoded string result flag, by default True.
:return: HEX encoded or bytes entropy string.
"""
if strength not in [128, 160, 192, 224, 256]:
raise ValueError('strength should be one of the following [128, 160, 192, 224, 256]')
a = random.SystemRandom().randint(0, ECDSA_SEC256K1_ORDER)
i = int((time.time() % 0.01 ) * 100000)
h = a.to_bytes(32, byteorder="big")
# more entropy from system timer and sha256 derivation
while i:
h = hashlib.sha256(h).digest()
i -= 1
if not i and int_from_bytes(h, byteorder="big") > ECDSA_SEC256K1_ORDER:
i += 1
return h[:int(strength/8)] if not hex else h[:int(strength/8)].hex()
示例10: get_random_secret_key
# 需要導入模塊: import random [as 別名]
# 或者: from random import SystemRandom [as 別名]
def get_random_secret_key():
import random
import hashlib
import time
try:
random = random.SystemRandom()
using_sysrandom = True
except NotImplementedError:
import warnings
warnings.warn('A secure pseudo-random number generator is not available '
'on your system. Falling back to Mersenne Twister.')
using_sysrandom = False
chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$^&*(-_=+)'
if not using_sysrandom:
random.seed(
hashlib.sha256(
("%s%s%s" % (
random.getstate(),
time.time(),
'BioQueue')).encode('utf-8')
).digest())
return ''.join(random.choice(chars) for i in range(50))
示例11: get_bigbluebutton_url
# 需要導入模塊: import random [as 別名]
# 或者: from random import SystemRandom [as 別名]
def get_bigbluebutton_url(request: HttpRequest, user_profile: UserProfile) -> HttpResponse:
# https://docs.bigbluebutton.org/dev/api.html#create for reference on the api calls
# https://docs.bigbluebutton.org/dev/api.html#usage for reference for checksum
id = "zulip-" + str(random.randint(100000000000, 999999999999))
password = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(10))
checksum = hashlib.sha1(("create" + "meetingID=" + id + "&moderatorPW="
+ password + "&attendeePW=" + password + "a" + settings.BIG_BLUE_BUTTON_SECRET).encode()).hexdigest()
url = add_query_to_redirect_url("/calls/bigbluebutton/join", urlencode({
"meeting_id": "\"" + id + "\"",
"password": "\"" + password + "\"",
"checksum": "\"" + checksum + "\""
}))
return json_success({"url": url})
# We use zulip_login_required here mainly to get access to the user's
# full name from Zulip to prepopulate the user's name in the
# BigBlueButton meeting. Since the meeting's details are encoded in
# the link the user is clicking, there is no validation tying this
# meeting to the Zulip organization it was created in.
示例12: generate_password
# 需要導入模塊: import random [as 別名]
# 或者: from random import SystemRandom [as 別名]
def generate_password(length=16):
while True:
password = [random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(length)]
password.insert(8, "-")
if not any(c in string.ascii_uppercase for c in password):
continue
if not any(c in string.ascii_lowercase for c in password):
continue
if not any(c in string.digits for c in password):
continue
return ''.join(password)
示例13: __init__
# 需要導入模塊: import random [as 別名]
# 或者: from random import SystemRandom [as 別名]
def __init__(self):
if sys.platform.startswith("linux"):
self.bin = os.path.join(TOOL_DIR, "radamsa-linux")
if os.path.isfile(self.bin):
os.chmod(self.bin, os.stat(self.bin).st_mode | stat.S_IXUSR)
else:
raise RuntimeError("Missing file %s" % self.bin)
elif sys.platform.startswith("win32"):
self.bin = os.path.join(TOOL_DIR, "radamsa-windows.exe")
if not os.path.isfile(self.bin):
raise RuntimeError("Missing file %s" % self.bin)
else:
raise RuntimeError("RadamsaFuzzer not supported on this platform")
self.sys_rnd = random.SystemRandom()
示例14: generate_secret_key
# 需要導入模塊: import random [as 別名]
# 或者: from random import SystemRandom [as 別名]
def generate_secret_key():
"""
Generate a random secret key, suitable to be used as a SECRET_KEY setting.
"""
return "".join(
[
random.SystemRandom().choice(
"abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)"
)
for i in range(50)
]
)
示例15: random_token
# 需要導入模塊: import random [as 別名]
# 或者: from random import SystemRandom [as 別名]
def random_token(extra=None, hash_func=hashlib.sha256):
"""
Extracted from `django-user-accounts`
"""
if extra is None:
extra = []
bits = extra + [str(random.SystemRandom().getrandbits(512))]
return hash_func("".join(bits)).hexdigest()