本文整理汇总了Python中Crypto.Random.get_random_bytes方法的典型用法代码示例。如果您正苦于以下问题:Python Random.get_random_bytes方法的具体用法?Python Random.get_random_bytes怎么用?Python Random.get_random_bytes使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Crypto.Random
的用法示例。
在下文中一共展示了Random.get_random_bytes方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: encrypt
# 需要导入模块: from Crypto import Random [as 别名]
# 或者: from Crypto.Random import get_random_bytes [as 别名]
def encrypt(self, plaintext, esn):
"""
Encrypt the given Plaintext with the encryption key
:param plaintext:
:return: Serialized JSON String of the encryption Envelope
"""
init_vector = get_random_bytes(16)
cipher = AES.new(self.encryption_key, AES.MODE_CBC, init_vector)
ciphertext = base64.standard_b64encode(
cipher.encrypt(Padding.pad(plaintext.encode('utf-8'), 16))).decode('utf-8')
encryption_envelope = {
'ciphertext': ciphertext,
'keyid': '_'.join((esn, str(self.sequence_number))),
'sha256': 'AA==',
'iv': base64.standard_b64encode(init_vector).decode('utf-8')
}
return json.dumps(encryption_envelope)
示例2: encrypt
# 需要导入模块: from Crypto import Random [as 别名]
# 或者: from Crypto.Random import get_random_bytes [as 别名]
def encrypt(self, password, assoc=None):
# encrypt password, ignore associated data
from Crypto.Random import get_random_bytes
salt = get_random_bytes(self.block_size)
from Crypto.Cipher import AES
IV = get_random_bytes(AES.block_size)
cipher = self._create_cipher(self.keyring_key, salt, IV)
password_encrypted = cipher.encrypt(self.pw_prefix + password)
# Serialize the salt, IV, and encrypted password in a secure format
data = dict(salt=salt, IV=IV, password_encrypted=password_encrypted)
for key in data:
# spare a few bytes: throw away newline from base64 encoding
data[key] = encodebytes(data[key]).decode()[:-1]
return json.dumps(data).encode()
示例3: auth_digital
# 需要导入模块: from Crypto import Random [as 别名]
# 或者: from Crypto.Random import get_random_bytes [as 别名]
def auth_digital(self, title_id, title_version, device_token, ticket):
self.verify_ticket(ticket, title_id)
plain_key = get_random_bytes(16)
aes = AES.new(plain_key, AES.MODE_CBC, iv=bytes(16))
encrypted_ticket = aes.encrypt(pad(ticket, 16))
rsa_key = RSA.construct((RSA_MODULUS, RSA_EXPONENT))
rsa = PKCS1_OAEP.new(rsa_key, SHA256)
encrypted_key = rsa.encrypt(plain_key)
req = HTTPRequest.post("/v3/application_auth_token")
req.form["application_id"] = "%016x" %title_id
req.form["application_version"] = "%08x" %title_version
req.form["device_auth_token"] = device_token
req.form["media_type"] = "DIGITAL"
req.form["cert"] = b64encode(encrypted_ticket)
req.form["cert_key"] = b64encode(encrypted_key)
response = self.request(req, True)
return response.json
示例4: verify
# 需要导入模块: from Crypto import Random [as 别名]
# 或者: from Crypto.Random import get_random_bytes [as 别名]
def verify(self, mac_tag):
"""Verify that a given **binary** MAC (computed by another party)
is valid.
Args:
mac_tag (byte string/byte string/memoryview): the expected MAC of the message.
Raises:
ValueError: if the MAC does not match. It means that the message
has been tampered with or that the MAC key is incorrect.
"""
secret = get_random_bytes(16)
mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=mac_tag)
mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=self.digest())
if mac1.digest() != mac2.digest():
raise ValueError("MAC check failed")
示例5: verify
# 需要导入模块: from Crypto import Random [as 别名]
# 或者: from Crypto.Random import get_random_bytes [as 别名]
def verify(self, mac_tag):
"""Verify that a given **binary** MAC (computed by another party)
is valid.
Args:
mac_tag (bytes/bytearray/memoryview): the expected MAC of the message.
Raises:
ValueError: if the MAC does not match. It means that the message
has been tampered with or that the MAC key is incorrect.
"""
secret = get_random_bytes(16)
mac1 = new(digest_bits=160, key=secret, data=mac_tag)
mac2 = new(digest_bits=160, key=secret, data=self.digest())
if mac1.digest() != mac2.digest():
raise ValueError("MAC check failed")
示例6: verify
# 需要导入模块: from Crypto import Random [as 别名]
# 或者: from Crypto.Random import get_random_bytes [as 别名]
def verify(self, mac_tag):
"""Verify that a given **binary** MAC (computed by another party)
is valid.
Args:
mac_tag (byte string/byte array/memoryview): the expected MAC of the message.
Raises:
ValueError: if the MAC does not match. It means that the message
has been tampered with or that the MAC key is incorrect.
"""
secret = get_random_bytes(16)
mac1 = new(digest_bits=160, key=secret, data=mac_tag)
mac2 = new(digest_bits=160, key=secret, data=self.digest())
if mac1.digest() != mac2.digest():
raise ValueError("MAC check failed")
示例7: verify
# 需要导入模块: from Crypto import Random [as 别名]
# 或者: from Crypto.Random import get_random_bytes [as 别名]
def verify(self, mac_tag):
"""Verify that a given **binary** MAC (computed by another party)
is valid.
Args:
mac_tag (byte string/byte array/memoryview): the expected MAC of the message.
Raises:
ValueError: if the MAC does not match. It means that the message
has been tampered with or that the MAC key is incorrect.
"""
secret = get_random_bytes(16)
mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=mac_tag)
mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=self.digest())
if mac1.digest() != mac2.digest():
raise ValueError("MAC check failed")
示例8: getRandomInteger
# 需要导入模块: from Crypto import Random [as 别名]
# 或者: from Crypto.Random import get_random_bytes [as 别名]
def getRandomInteger(N, randfunc=None):
"""Return a random number at most N bits long.
If :data:`randfunc` is omitted, then :meth:`Random.get_random_bytes` is used.
.. deprecated:: 3.0
This function is for internal use only and may be renamed or removed in
the future. Use :func:`Crypto.Random.random.getrandbits` instead.
"""
if randfunc is None:
randfunc = Random.get_random_bytes
S = randfunc(N>>3)
odd_bits = N % 8
if odd_bits != 0:
rand_bits = ord(randfunc(1)) >> (8-odd_bits)
S = struct.pack('B', rand_bits) + S
value = bytes_to_long(S)
return value
示例9: getRandomRange
# 需要导入模块: from Crypto import Random [as 别名]
# 或者: from Crypto.Random import get_random_bytes [as 别名]
def getRandomRange(a, b, randfunc=None):
"""Return a random number *n* so that *a <= n < b*.
If :data:`randfunc` is omitted, then :meth:`Random.get_random_bytes` is used.
.. deprecated:: 3.0
This function is for internal use only and may be renamed or removed in
the future. Use :func:`Crypto.Random.random.randrange` instead.
"""
range_ = b - a - 1
bits = size(range_)
value = getRandomInteger(bits, randfunc)
while value > range_:
value = getRandomInteger(bits, randfunc)
return a + value
示例10: generate
# 需要导入模块: from Crypto import Random [as 别名]
# 或者: from Crypto.Random import get_random_bytes [as 别名]
def generate(**kwargs):
"""Generate a new private key on the given curve.
Args:
curve (string):
Mandatory. It must be a curve name defined in :numref:`curve_names`.
randfunc (callable):
Optional. The RNG to read randomness from.
If ``None``, :func:`Crypto.Random.get_random_bytes` is used.
"""
curve_name = kwargs.pop("curve")
curve = _curves[curve_name]
randfunc = kwargs.pop("randfunc", get_random_bytes)
if kwargs:
raise TypeError("Unknown parameters: " + str(kwargs))
d = Integer.random_range(min_inclusive=1,
max_exclusive=curve.order,
randfunc=randfunc)
return EccKey(curve=curve_name, d=d)
示例11: _derive_Poly1305_key_pair
# 需要导入模块: from Crypto import Random [as 别名]
# 或者: from Crypto.Random import get_random_bytes [as 别名]
def _derive_Poly1305_key_pair(key, nonce):
"""Derive a tuple (r, s, nonce) for a Poly1305 MAC.
If nonce is ``None``, a new 16-byte nonce is generated.
"""
if len(key) != 32:
raise ValueError("Poly1305 with AES requires a 32-byte key")
if nonce is None:
nonce = get_random_bytes(16)
elif len(nonce) != 16:
raise ValueError("Poly1305 with AES requires a 16-byte nonce")
s = new(key[:16], MODE_ECB).encrypt(nonce)
return key[16:], s, nonce
示例12: new
# 需要导入模块: from Crypto import Random [as 别名]
# 或者: from Crypto.Random import get_random_bytes [as 别名]
def new(key, nonce=None):
"""Create a new Salsa20 cipher
:keyword key: The secret key to use. It must be 16 or 32 bytes long.
:type key: bytes/bytearray/memoryview
:keyword nonce:
A value that must never be reused for any other encryption
done with this key. It must be 8 bytes long.
If not provided, a random byte string will be generated (you can read
it back via the ``nonce`` attribute of the returned object).
:type nonce: bytes/bytearray/memoryview
:Return: a :class:`Crypto.Cipher.Salsa20.Salsa20Cipher` object
"""
if nonce is None:
nonce = get_random_bytes(8)
return Salsa20Cipher(key, nonce)
# Size of a data block (in bytes)
示例13: CreateKey
# 需要导入模块: from Crypto import Random [as 别名]
# 或者: from Crypto.Random import get_random_bytes [as 别名]
def CreateKey(self, private_key=None):
"""
Create a KeyPair
Args:
private_key (iterable_of_ints): (optional) 32 byte private key
Returns:
KeyPair: a KeyPair instance
"""
if private_key is None:
private_key = bytes(Random.get_random_bytes(32))
key = KeyPair(priv_key=private_key)
self._keys[key.PublicKeyHash.ToBytes()] = key
return key
示例14: make_client_hello
# 需要导入模块: from Crypto import Random [as 别名]
# 或者: from Crypto.Random import get_random_bytes [as 别名]
def make_client_hello(self):
h = unhexlify('0303') # TLS 1.2
#self.client_random = unhexlify('bc349559ac16c8f8362191395b4d04a435d870315f519eed8777488bc2b9600c')
self.client_random = get_random_bytes(0x20)
h += self.client_random # client's random
h += with_1byte_size(unhexlify('00000000000000')) # session ID
suits = b''
suits += pack('>H', 0xc005) # TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
suits += pack('>H', 0x003d) # TLS_RSA_WITH_AES_256_CBC_SHA256
suits += pack('>H', 0x008d) # TLS_RSA_WITH_AES_256_CBC_SHA256
h += with_2bytes_size(suits)
h += with_1byte_size(b'') # no compression options
exts = b''
exts += self.make_ext(0x004, pack('>H', 0x0017)) # truncated_hmac = 0x17
exts += self.make_ext(0x00b, with_1byte_size(unhexlify('00'))) # EC points format = uncompressed
# h += with_2bytes_size(exts)
h += pack('>H', len(exts)-2) + exts # -2? WHY?!...
return self.with_neg_hdr(0x01, h)
示例15: encrypt
# 需要导入模块: from Crypto import Random [as 别名]
# 或者: from Crypto.Random import get_random_bytes [as 别名]
def encrypt(self, value):
iv = Random.get_random_bytes(AES.block_size)
cipher = self.get_cipher(self.key, iv)
return iv + cipher.encrypt(value)