本文整理汇总了Python中Cryptodome.Random.new方法的典型用法代码示例。如果您正苦于以下问题:Python Random.new方法的具体用法?Python Random.new怎么用?Python Random.new使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Cryptodome.Random
的用法示例。
在下文中一共展示了Random.new方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: build_cipher
# 需要导入模块: from Cryptodome import Random [as 别名]
# 或者: from Cryptodome.Random import new [as 别名]
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")
示例2: getrandbits
# 需要导入模块: from Cryptodome import Random [as 别名]
# 或者: from Cryptodome.Random import new [as 别名]
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)))
示例3: _test_random_key
# 需要导入模块: from Cryptodome import Random [as 别名]
# 或者: from Cryptodome.Random import new [as 别名]
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)
示例4: generate_probable_safe_prime
# 需要导入模块: from Cryptodome import Random [as 别名]
# 或者: from Cryptodome.Random import new [as 别名]
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
示例5: test_tampering
# 需要导入模块: from Cryptodome import Random [as 别名]
# 或者: from Cryptodome.Random import new [as 别名]
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)
示例6: _generateRSAKey
# 需要导入模块: from Cryptodome import Random [as 别名]
# 或者: from Cryptodome.Random import new [as 别名]
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())
示例7: decrypt
# 需要导入模块: from Cryptodome import Random [as 别名]
# 或者: from Cryptodome.Random import new [as 别名]
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
示例8: test_generate_3args
# 需要导入模块: from Cryptodome import Random [as 别名]
# 或者: from Cryptodome.Random import new [as 别名]
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)
示例9: test_generate_2arg
# 需要导入模块: from Cryptodome import Random [as 别名]
# 或者: from Cryptodome.Random import new [as 别名]
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)
示例10: test_probable_prime
# 需要导入模块: from Cryptodome import Random [as 别名]
# 或者: from Cryptodome.Random import new [as 别名]
def test_probable_prime(candidate, randfunc=None):
"""Test if a number is prime.
A number is qualified as prime if it passes a certain
number of Miller-Rabin tests (dependent on the size
of the number, but such that probability of a false
positive is less than 10^-30) and a single Lucas test.
For instance, a 1024-bit candidate will need to pass
4 Miller-Rabin tests.
:Parameters:
candidate : integer
The number to test for primality.
randfunc : callable
The routine to draw random bytes from to select Miller-Rabin bases.
:Returns:
``PROBABLE_PRIME`` if the number if prime with very high probability.
``COMPOSITE`` if the number is a composite.
For efficiency reasons, ``COMPOSITE`` is also returned for small primes.
"""
if randfunc is None:
randfunc = Random.new().read
if not isinstance(candidate, Integer):
candidate = Integer(candidate)
# First, check trial division by the smallest primes
if int(candidate) in _sieve_base:
return PROBABLY_PRIME
try:
map(candidate.fail_if_divisible_by, _sieve_base)
except ValueError:
return COMPOSITE
# These are the number of Miller-Rabin iterations s.t. p(k, t) < 1E-30,
# with p(k, t) being the probability that a randomly chosen k-bit number
# is composite but still survives t MR iterations.
mr_ranges = ((220, 30), (280, 20), (390, 15), (512, 10),
(620, 7), (740, 6), (890, 5), (1200, 4),
(1700, 3), (3700, 2))
bit_size = candidate.size_in_bits()
try:
mr_iterations = list(filter(lambda x: bit_size < x[0],
mr_ranges))[0][1]
except IndexError:
mr_iterations = 1
if miller_rabin_test(candidate, mr_iterations,
randfunc=randfunc) == COMPOSITE:
return COMPOSITE
if lucas_test(candidate) == COMPOSITE:
return COMPOSITE
return PROBABLY_PRIME
示例11: generate_probable_prime
# 需要导入模块: from Cryptodome import Random [as 别名]
# 或者: from Cryptodome.Random import new [as 别名]
def generate_probable_prime(**kwargs):
"""Generate a random probable prime.
The prime will not have any specific properties
(e.g. it will not be a *strong* prime).
Random numbers are evaluated for primality until one
passes all tests, consisting of a certain number of
Miller-Rabin tests with random bases followed by
a single Lucas test.
The number of Miller-Rabin iterations is chosen such that
the probability that the output number is a non-prime is
less than 1E-30 (roughly 2^{-100}).
This approach is compliant to `FIPS PUB 186-4`__.
:Keywords:
exact_bits : integer
The desired size in bits of the probable prime.
It must be at least 160.
randfunc : callable
An RNG function where candidate primes are taken from.
prime_filter : callable
A function that takes an Integer as parameter and returns
True if the number can be passed to further primality tests,
False if it should be immediately discarded.
:Return:
A probable prime in the range 2^exact_bits > p > 2^(exact_bits-1).
.. __: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
"""
exact_bits = kwargs.pop("exact_bits", None)
randfunc = kwargs.pop("randfunc", None)
prime_filter = kwargs.pop("prime_filter", lambda x: True)
if kwargs:
print "Unknown parameters:", kwargs.keys()
if exact_bits is None:
raise ValueError("Missing exact_bits parameter")
if exact_bits < 160:
raise ValueError("Prime number is not big enough.")
if randfunc is None:
randfunc = Random.new().read
result = COMPOSITE
while result == COMPOSITE:
candidate = Integer.random(exact_bits=exact_bits,
randfunc=randfunc) | 1
if not prime_filter(candidate):
continue
result = test_probable_prime(candidate, randfunc)
return candidate
示例12: __init__
# 需要导入模块: from Cryptodome import Random [as 别名]
# 或者: from Cryptodome.Random import new [as 别名]
def __init__(self, key):
self.rndfile = Random.new()
if key == None:
log.write("Initalizing key")
self.key = self.rndfile.read(self.KEY_SIZE)
keyfile = open(self.KEYFILE, 'wb');
keyfile.write(self.key)
else:
self.key = key
self.IV = b"jamsomwareiscool"
示例13: encode
# 需要导入模块: from Cryptodome import Random [as 别名]
# 或者: from Cryptodome.Random import new [as 别名]
def encode(self, raw):
"""
Encodes data
:param data: Data to be encoded
:type data: str
:returns: string -- Encoded data
"""
raw = bytes(Padding.pad(data_to_pad=raw, block_size=self.bs))
iv = Random.new().read(AES.block_size)
cipher = AES.new(self.crypt_key, AES.MODE_CBC, iv)
return base64.b64encode(iv + cipher.encrypt(raw))
示例14: enc
# 需要导入模块: from Cryptodome import Random [as 别名]
# 或者: from Cryptodome.Random import new [as 别名]
def enc(enc_key, hmac_key, plaintext=None):
plaintext_bytes = plaintext.encode()
iv = Random.new().read(IV_SIZE)
h = hmac(hmac_key)
h.update(plaintext_bytes)
hmac_tag = base64.b64encode(h.digest()).decode()
ciphertext = base64.b64encode(cipher(enc_key, iv).encrypt(pad(plaintext_bytes))).decode()
return dict(algorithm=ALGO_NAME,
timestamp=calendar.timegm(time.gmtime()),
iv=base64.b64encode(iv).decode(),
hmac=hmac_tag,
text=ciphertext)
示例15: encrypt
# 需要导入模块: from Cryptodome import Random [as 别名]
# 或者: from Cryptodome.Random import new [as 别名]
def encrypt(self, raw):
"""
Encryptes the parameter raw.
:type raw: bytes
:rtype: str
:param: bytes to be encrypted.
:return: A base 64 encoded string.
"""
raw = self._pad(raw)
iv = Random.new().read(AES.block_size)
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return base64.urlsafe_b64encode(iv + cipher.encrypt(raw))