Python源码示例:Cryptodome.Random.get_random_bytes()
示例1
def _openssl_encrypt(password, plaintext):
"""
:type password: str
:type plaintext: str
:rtype: str
"""
# Thanks to Joe Linoff, taken from https://stackoverflow.com/a/42773185
salt = get_random_bytes(8)
key, iv = PayloadFactory._get_key_and_iv(password, salt)
# PKCS#7 padding
padding_len = 16 - (len(plaintext) % 16)
padded_plaintext = plaintext + (chr(padding_len) * padding_len)
# Encrypt
cipher = AES.new(key, AES.MODE_CBC, iv)
cipher_text = cipher.encrypt(padded_plaintext.encode())
# Make OpenSSL compatible
openssl_cipher_text = b"Salted__" + salt + cipher_text
return b64encode(openssl_cipher_text).decode()
示例2
def encrypt_file(public_key, src_file, dest_file):
try:
with open(src_file) as f:
rsa_key = RSA.import_key(open(public_key).read())
session_key = get_random_bytes(16)
# Encrypt session key
cipher_rsa = PKCS1_OAEP.new(rsa_key)
encrypted_session_key = cipher_rsa.encrypt(session_key)
# Encrypt data
cipher_aes = AES.new(session_key, AES.MODE_EAX)
ciphertext, tag = cipher_aes.encrypt_and_digest(f.read().encode("utf-8"))
except Exception as e:
print("Unable to encrypt file: {}".format(src_file))
raise e
try:
with open(dest_file, "wb") as f:
for x in (encrypted_session_key, cipher_aes.nonce, tag, ciphertext):
f.write(x)
except Exception as e:
print("Unable to write output file {}".format(dest_file))
raise e
示例3
def verify(self, mac_tag):
"""Verify that a given **binary** MAC (computed by another party)
is valid.
:Parameters:
mac_tag : byte string
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")
示例4
def verify(self, mac_tag):
"""Verify that a given **binary** MAC (computed by another party)
is valid.
:Parameters:
mac_tag : byte string
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
def verify(self, mac_tag):
"""Verify that a given **binary** MAC (computed by another party)
is valid.
:Parameters:
mac_tag : byte string
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
def verify(self, mac_tag):
"""Verify that a given **binary** MAC (computed by another party)
is valid.
:Parameters:
mac_tag : byte string
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")
示例7
def generate(**kwargs):
"""Generate a new private key on the given curve.
:Keywords:
curve : string
Mandatory. It must be "P-256", "prime256v1" or "secp256r1".
randfunc : callable
Optional. The RNG to read randomness from.
If ``None``, the system source is used.
"""
curve = kwargs.pop("curve")
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, d=d)
示例8
def new(key, nonce=None):
"""Create a new Salsa20 cipher
:Parameters:
key : byte string
The secret key to use in the symmetric cipher.
It must be 16 or 32 bytes long.
nonce : byte string
A value that must never be reused for any other encryption.
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).
:Return: an `Salsa20Cipher` object
"""
if nonce is None:
nonce = get_random_bytes(8)
return Salsa20Cipher(key, nonce)
#: Size of a data block (in bytes)
示例9
def verify(self, mac_tag):
"""Verify that a given **binary** MAC (computed by another party)
is valid.
:Parameters:
mac_tag : byte string
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")
示例10
def verify(self, mac_tag):
"""Verify that a given **binary** MAC (computed by another party)
is valid.
:Parameters:
mac_tag : byte string
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")
示例11
def verify(self, mac_tag):
"""Verify that a given **binary** MAC (computed by another party)
is valid.
:Parameters:
mac_tag : byte string
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")
示例12
def verify(self, mac_tag):
"""Verify that a given **binary** MAC (computed by another party)
is valid.
:Parameters:
mac_tag : byte string
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")
示例13
def generate(**kwargs):
"""Generate a new private key on the given curve.
:Keywords:
curve : string
Mandatory. It must be "P-256", "prime256v1" or "secp256r1".
randfunc : callable
Optional. The RNG to read randomness from.
If ``None``, the system source is used.
"""
curve = kwargs.pop("curve")
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, d=d)
示例14
def verify(self, mac_tag):
"""Verify that a given **binary** MAC (computed by another party)
is valid.
:Parameters:
mac_tag : byte string
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")
示例15
def verify(self, mac_tag):
"""Verify that a given **binary** MAC (computed by another party)
is valid.
:Parameters:
mac_tag : byte string
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")
示例16
def verify(self, mac_tag):
"""Verify that a given **binary** MAC (computed by another party)
is valid.
:Parameters:
mac_tag : byte string
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")
示例17
def new(key, nonce=None):
"""Create a new Salsa20 cipher
:Parameters:
key : byte string
The secret key to use in the symmetric cipher.
It must be 16 or 32 bytes long.
nonce : byte string
A value that must never be reused for any other encryption.
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).
:Return: an `Salsa20Cipher` object
"""
if nonce is None:
nonce = get_random_bytes(8)
return Salsa20Cipher(key, nonce)
#: Size of a data block (in bytes)
示例18
def encrypt(self, data, esn, sequence_number):
"""
Encrypt the given Plaintext with the encryption key
:param plaintext:
:return: Serialized JSON String of the encryption Envelope
"""
iv = get_random_bytes(16)
encryption_envelope = {
'ciphertext': '',
'keyid': esn + '_' + str(sequence_number),
'sha256': 'AA==',
'iv': base64.standard_b64encode(iv).decode('ascii')
}
# Padd the plaintext
plaintext = Padding.pad(data.encode('utf-8'), 16)
# Encrypt the text
cipher = AES.new(self.encryption_key, AES.MODE_CBC, iv)
citext = cipher.encrypt(plaintext)
encryption_envelope['ciphertext'] = base64.standard_b64encode(citext).decode('ascii')
return encryption_envelope;
示例19
def get_random_bytes(length: int) -> bytes:
"""
This interface is used to get a random byte string of the desired length.
:param length: the desired length of a random byte string.
:return: a random byte string of the desired length.
"""
return Random.get_random_bytes(length)
示例20
def get_random_hex_str(length: int) -> str:
"""
:param length:
:return: a random hexadecimal string of the desired length.
"""
return Random.get_random_bytes(length).hex()[:length]
示例21
def generate_key():
key = Random.get_random_bytes(32)
return key
示例22
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)
示例23
def encrypt_password(ssh_pub_key, password):
if not password:
return [None, None, None, None]
recipient_key = RSA.import_key(ssh_pub_key)
session_key = get_random_bytes(16)
# Encrypt the session key with the public RSA key
cipher_rsa = PKCS1_OAEP.new(recipient_key)
encrypted_aes_session_key = cipher_rsa.encrypt(session_key)
# Encrypt the data with the AES session key
cipher_aes = AES.new(session_key, AES.MODE_EAX)
ciphertext, tag = cipher_aes.encrypt_and_digest(password.encode())
return [encrypted_aes_session_key, cipher_aes.nonce, tag, ciphertext]
示例24
def generate_random_key(size=32):
return get_random_bytes(size)
示例25
def encrypt(plaintext, key):
#Deal with the case when field is empty
if plaintext is None:
plaintext = b''
nonce = get_random_bytes(AES.block_size)
cipher = AES.new(key, AES.MODE_GCM, nonce = nonce)
(cipher_text, digest) = cipher.encrypt_and_digest(_pad(plaintext))
return base64.b64encode(nonce + cipher_text + digest)
示例26
def __init__(self, debug=False):
self._version = 2
self._compression = 'zlib'
self._data = ''
self._text = ''
self._attachment = ''
self._attachment_name = ''
self._password = ''
self._debug = debug
self._iteration_count = CIPHER_ITERATION_COUNT
self._salt_bytes = CIPHER_SALT_BYTES
self._block_bits = CIPHER_BLOCK_BITS
self._tag_bits = CIPHER_TAG_BITS
self._key = get_random_bytes(int(self._block_bits / 8))
示例27
def _encryptV2(self):
from pbincli.utils import json_encode
iv = get_random_bytes(int(self._tag_bits / 8))
salt = get_random_bytes(self._salt_bytes)
key = self.__deriveKey(salt)
# prepare encryption authenticated data and message
adata = [
[
b64encode(iv).decode(),
b64encode(salt).decode(),
self._iteration_count,
self._block_bits,
self._tag_bits,
'aes',
'gcm',
self._compression
],
self._formatter,
int(self._discussion),
int(self._burnafterreading)
]
cipher_message = {'paste':self._text}
if self._attachment:
cipher_message['attachment'] = self._attachment
cipher_message['attachment_name'] = self._attachment_name
cipher = self.__initializeCipher(key, iv, adata, int(self._tag_bits /8 ))
ciphertext, tag = cipher.encrypt_and_digest(self.__compress(json_encode(cipher_message)))
if self._debug: print("PBKDF2 Key:\t{}\nCipherText:\t{}\nCipherTag:\t{}"
.format(b64encode(key), b64encode(ciphertext), b64encode(tag)))
self._data = {'v':2,'adata':adata,'ct':b64encode(ciphertext + tag).decode(),'meta':{'expire':self._expiration}}
示例28
def generate_nonce(size):
"""Generate a secure random for cryptographic use.
:param size: Number of bytes for the nonce
:return: Generated random bytes
"""
return Random.get_random_bytes(size)
示例29
def generate_nonce(size):
# TODO still has old dependencies but has to be deleted
""" Generate a secure random for cryptographic use.
:param size: Number of bytes for the nonce
:return: Generated random bytes
"""
return Random.get_random_bytes(size)
示例30
def new(rsa_key, **kwargs):
"""Return a signature scheme object `PSS_SigScheme` that
can be used to perform PKCS#1 PSS signature or verification.
:Parameters:
rsa_key : RSA key object
The key to use to sign or verify the message.
This is a `Cryptodome.PublicKey.RSA` object.
Signing is only possible if *key* is a private RSA key.
:Keywords:
mask_func : callable
A mask generation function that accepts two parameters: a string to
use as seed, and the length of the mask in bytes to generate.
If not specified, the standard MGF1 is used.
salt_bytes : int
Length of the salt, in bytes.
If not specified, it matches the output size of the hash function.
If zero, the signature scheme becomes deterministic.
rand_func : callable
A function that returns random bytes.
The default is `Cryptodome.Random.get_random_bytes`.
"""
mask_func = kwargs.pop("mask_func", None)
salt_len = kwargs.pop("salt_bytes", None)
rand_func = kwargs.pop("rand_func", None)
if rand_func is None:
rand_func = Random.get_random_bytes
if kwargs:
raise ValueError("Unknown keywords: " + str(list(kwargs.keys())))
return PSS_SigScheme(rsa_key, mask_func, salt_len, rand_func)