本文整理汇总了Python中Cryptodome.Random类的典型用法代码示例。如果您正苦于以下问题:Python Random类的具体用法?Python Random怎么用?Python Random使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Random类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: start_journalist_server
def start_journalist_server():
Random.atfork()
journalist.app.run(
port=journalist_port,
debug=True,
use_reloader=False,
threaded=True)
示例2: create_entry
def create_entry(self, group = None, title = "", image = 1, url = "",
username = "", password = "", comment = "",
y = 2999, mon = 12, d = 28, h = 23, min_ = 59,
s = 59):
"""This method creates a new entry.
The group which should hold the entry is needed.
image must be an unsigned int >0, group a v1Group.
It is possible to give an expire date in the following way:
- y is the year between 1 and 9999 inclusive
- mon is the month between 1 and 12
- d is a day in the given month
- h is a hour between 0 and 23
- min_ is a minute between 0 and 59
- s is a second between 0 and 59
The special date 2999-12-28 23:59:59 means that entry expires never.
"""
if (type(title) is not str or
type(image) is not int or image < 0 or
type(url) is not str or
type(username) is not str or
type(password) is not str or
type(comment) is not str or
type(y) is not int or
type(mon) is not int or
type(d) is not int or
type(h) is not int or
type(min_) is not int
or type(s) is not int or
type(group) is not v1Group):
raise KPError("One argument has not a valid type.")
elif group not in self.groups:
raise KPError("Group doesn't exist.")
elif (y > 9999 or y < 1 or mon > 12 or mon < 1 or d > 31 or d < 1 or
h > 23 or h < 0 or min_ > 59 or min_ < 0 or s > 59 or s < 0):
raise KPError("No legal date")
elif (((mon == 1 or mon == 3 or mon == 5 or mon == 7 or mon == 8 or
mon == 10 or mon == 12) and d > 31) or
((mon == 4 or mon == 6 or mon == 9 or mon == 11) and d > 30) or
(mon == 2 and d > 28)):
raise KPError("Given day doesn't exist in given month")
Random.atfork()
uuid = Random.get_random_bytes(16)
entry = v1Entry(group.id_, group, image, title, url, username,
password, comment,
datetime.now().replace(microsecond = 0),
datetime.now().replace(microsecond = 0),
datetime.now().replace(microsecond = 0),
datetime(y, mon, d, h, min_, s),
uuid)
self.entries.append(entry)
group.entries.append(entry)
self._num_entries += 1
return True
示例3: __init__
def __init__(self, filepath=None, password=None, keyfile=None,
read_only=False, new = False):
""" Initialize a new or an existing database.
If a 'filepath' and a 'masterkey' is passed 'load' will try to open
a database. If 'True' is passed to 'read_only' the database will open
read-only. It's also possible to create a new one, just pass 'True' to
new. This will be ignored if a filepath and a masterkey is given this
will be ignored.
"""
if filepath is not None and password is None and keyfile is None:
raise KPError('Missing argument: Password or keyfile '
'needed additionally to open an existing database!')
elif type(read_only) is not bool or type(new) is not bool:
raise KPError('read_only and new must be bool')
elif ((filepath is not None and type(filepath) is not str) or
(type(password) is not str and password is not None) or
(type(keyfile) is not str and keyfile is not None)):
raise KPError('filepath, masterkey and keyfile must be a string')
elif (filepath is None and password is None and keyfile is None and
new is False):
raise KPError('Either an existing database should be opened or '
'a new should be created.')
self.groups = []
self.entries = []
self.root_group = v1Group()
self.read_only = read_only
self.filepath = filepath
self.password = password
self.keyfile = keyfile
# This are attributes that are needed internally. You should not
# change them directly, it could damage the database!
self._group_order = []
self._entry_order = []
self._signature1 = 0x9AA2D903
self._signature2 = 0xB54BFB65
self._enc_flag = 2
self._version = 0x00030002
self._final_randomseed = ''
self._enc_iv = ''
self._num_groups = 1
self._num_entries = 0
self._contents_hash = ''
Random.atfork()
self._transf_randomseed = Random.get_random_bytes(32)
self._key_transf_rounds = 150000
# Due to the design of KeePass, at least one group is needed.
if new is True:
self._group_order = [("id", 1), (1, 4), (2, 9), (7, 4), (8, 2),
(0xFFFF, 0)]
group = v1Group(1, 'Internet', 1, self, parent = self.root_group)
self.root_group.children.append(group)
self.groups.append(group)
示例4: AES_encrypt_Login
def AES_encrypt_Login(self, user, psw, returnOrdType=3):
assert (type(user)) == str
assert (type(psw)) == str
logger = self._SetLogger(package=__name__)
# if isinstance(user, str): b_user = user.encode('utf-8') # covert to bytes
# if isinstance(psw, str): b_psw = psw.encode('utf-8') # covert to bytes
# b_user = user.encode('utf-8') # covert to bytes
# b_psw = psw.encode('utf-8') # covert to bytes
logger.info(' encrypting password with user value')
b_key = self._prepareKey(user)
nounce = Random.get_random_bytes(16)
cipher = AES.new(b_key, AES.MODE_CFB, nounce)
# - text to be ciphered
ciphertext = cipher.encrypt(psw.encode('utf-8')) # covert to bytes
# - encrypting della psw
b_cipheredPsw = self._AES_cryptedFormatData(nounce, ciphertext, returnOrdType)
pswLen = len(b_cipheredPsw)
# - cipheredPsw is bytearray '''
h_cipheredPsw = self.bytesToHex(b_cipheredPsw) # hex contenuto in string
logger.info(' h_cipheredPsw %s' % h_cipheredPsw)
# crypting dello user, usiamo la HexPSW come Key
logger.info(' encrypting user value with password in strHex format')
b_key = self._prepareKey(b_cipheredPsw)
nounce = Random.get_random_bytes(16)
cipher = AES.new(b_key, AES.MODE_CFB, nounce)
# - text to be ciphered
ciphertext = cipher.encrypt(user.encode('utf-8')) # convert to bytes
# - encrypting dello user
b_cipheredUser = self._AES_cryptedFormatData(nounce, ciphertext, returnOrdType)
# - cipheredPsw is bytearray '''
h_cipheredUser = self.bytesToHex(b_cipheredUser) # hex contenuto in string
logger.info(' h_cipheredUser %s' % h_cipheredUser)
'''
costruzione del dato di ritorno composto dai dati HEX di PSW + USER con
l'aggiunta della lunghezza della PSW calcolata sul bytes_data.
'''
myData = h_cipheredPsw + h_cipheredUser + '{0:02x}'.format(pswLen)
logger = self._SetLogger(package=__name__, exiting=True)
return myData
示例5: getrandbits
def getrandbits(self, k):
"""Return an integer with k random bits."""
if self._randfunc is None:
self._randfunc = Random.new().read
mask = (1 << k) - 1
return mask & bytes_to_long(self._randfunc(ceil_div(k, 8)))
示例6: test_tampering
def test_tampering(self):
password = '1' * 100
key = passwort.generate_key()
k1 = passwort.Keychain()
k1.use_key(key)
k1.set('example.com', passwort.Keychain.PASSWORD_FIELD, password)
k1.save(self.temp_filename)
v1 = k1.get('example.com', passwort.Keychain.PASSWORD_FIELD)
self.assertEqual(v1, password)
k2 = passwort.Keychain()
k2.use_key(key)
k2.load(self.temp_filename)
v2 = k2.get('example.com', passwort.Keychain.PASSWORD_FIELD)
self.assertEqual(v2, v1)
tmp = open(self.temp_filename)
data = json.load(tmp)
tmp.close()
enc_password_value = base64.b64decode(data['example.com']['password']['text'])
tampered_value = Random.new().read(16) + enc_password_value[16:]
data['example.com']['password']['text'] = base64.b64encode(tampered_value).decode()
f = open(self.temp_filename, "w")
f.write(json.dumps(data))
f.close()
k3 = passwort.Keychain()
k3.use_key(key)
k3.load(self.temp_filename)
with self.assertRaises(NameError):
k3.get('example.com', passwort.Keychain.PASSWORD_FIELD)
示例7: _test_random_key
def _test_random_key(self, bits):
elgObj = ElGamal.generate(bits, Random.new().read)
self._check_private_key(elgObj)
self._exercise_primitive(elgObj)
pub = elgObj.publickey()
self._check_public_key(pub)
self._exercise_public_primitive(elgObj)
示例8: generate_probable_safe_prime
def generate_probable_safe_prime(**kwargs):
"""Generate a random, probable safe prime.
Note this operation is much slower than generating a simple prime.
:Keywords:
exact_bits : integer
The desired size in bits of the probable safe prime.
randfunc : callable
An RNG function where candidate primes are taken from.
:Return:
A probable safe prime in the range
2^exact_bits > p > 2^(exact_bits-1).
"""
exact_bits = kwargs.pop("exact_bits", None)
randfunc = kwargs.pop("randfunc", None)
if kwargs:
print "Unknown parameters:", kwargs.keys()
if randfunc is None:
randfunc = Random.new().read
result = COMPOSITE
while result == COMPOSITE:
q = generate_probable_prime(exact_bits=exact_bits - 1, randfunc=randfunc)
candidate = q * 2 + 1
if candidate.size_in_bits() != exact_bits:
continue
result = test_probable_prime(candidate, randfunc=randfunc)
return candidate
示例9: decrypt
def decrypt(self, ciphertext, key, padding="pkcs1_padding"):
if padding == "pkcs1_padding":
cipher = PKCS1_v1_5.new(key)
if self.with_digest:
dsize = SHA.digest_size
else:
dsize = 0
sentinel = Random.new().read(32 + dsize)
text = cipher.decrypt(ciphertext, sentinel)
if dsize:
_digest = text[-dsize:]
_msg = text[:-dsize]
digest = SHA.new(_msg).digest()
if digest == _digest:
text = _msg
else:
raise DecryptionFailed()
else:
if text == sentinel:
raise DecryptionFailed()
elif padding == "pkcs1_oaep_padding":
cipher = PKCS1_OAEP.new(key)
text = cipher.decrypt(ciphertext)
else:
raise Exception("Unsupported padding")
return text
示例10: _generateRSAKey
def _generateRSAKey(self, BITS=2048, PKCS=8):
random_generator = Random.new().read
passPhrase = self._passPhrase # ValueError: RSA key format is not supported
passPhrase = None # Funziona
print ('generating..... key')
key = Crypto.PublicKey.RSA.generate(BITS, random_generator)
print ('created.......', key)
print ('encrypting..... key')
privateKey = key.exportKey(passphrase=passPhrase, pkcs=PKCS, protection="scryptAndAES128-CBC")
print ('creating....... PrivateKey to file:', self._privateKeyFile)
file = open(self._privateKeyFile, "wb")
file.write(privateKey)
file.close()
print ('creating....... PublicKey to file:', self._publicKeyFile)
file = open(self._publicKeyFile, "wb")
file.write(key.publickey().exportKey())
file.close()
print ('key.can_encrypt......: ', key.can_encrypt())
print ('key.can_sign.........: ', key.can_sign())
print ('key.has_private......: ', key.has_private())
示例11: build_cipher
def build_cipher(self, iv="", alg="aes_128_cbc"):
"""
:param iv: init vector
:param alg: cipher algorithm
:return: A Cipher instance
"""
typ, bits, cmode = alg.split("_")
if not iv:
if self.iv:
iv = self.iv
else:
iv = Random.new().read(AES.block_size)
else:
assert len(iv) == AES.block_size
if bits not in ["128", "192", "256"]:
raise Exception("Unsupported key length")
try:
assert len(self.key) == int(bits) >> 3
except AssertionError:
raise Exception("Wrong Key length")
try:
return AES.new(self.key, POSTFIX_MODE[cmode], iv), iv
except KeyError:
raise Exception("Unsupported chaining mode")
示例12: test_generate_2arg
def test_generate_2arg(self):
"""RSA (default implementation) generated key (2 arguments)"""
rsaObj = self.rsa.generate(1024, Random.new().read)
self._check_private_key(rsaObj)
self._exercise_primitive(rsaObj)
pub = rsaObj.publickey()
self._check_public_key(pub)
self._exercise_public_primitive(rsaObj)
示例13: test_generate_3args
def test_generate_3args(self):
rsaObj = self.rsa.generate(1024, Random.new().read,e=65537)
self._check_private_key(rsaObj)
self._exercise_primitive(rsaObj)
pub = rsaObj.publickey()
self._check_public_key(pub)
self._exercise_public_primitive(rsaObj)
self.assertEqual(65537,rsaObj.e)
示例14: __init__
def __init__(self, module, params):
from Cryptodome import Random
unittest.TestCase.__init__(self)
self.module = module
self.iv = Random.get_random_bytes(module.block_size)
self.key = b(params['key'])
self.plaintext = 100 * b(params['plaintext'])
self.module_name = params.get('module_name', None)
示例15: start_source_server
def start_source_server():
# We call Random.atfork() here because we fork the source and
# journalist server from the main Python process we use to drive
# our browser with multiprocessing.Process() below. These child
# processes inherit the same RNG state as the parent process, which
# is a problem because they would produce identical output if we
# didn't re-seed them after forking.
Random.atfork()
config.SESSION_EXPIRATION_MINUTES = self.session_expiration
source_app = create_app(config)
source_app.run(
port=source_port,
debug=True,
use_reloader=False,
threaded=True)