Python Cryptodome.Random.get_random_bytes() Examples

The following are 30 code examples of Cryptodome.Random.get_random_bytes(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module Cryptodome.Random , or try the search function .
Example #1
Source File: MSLCrypto.py    From plugin.video.netflix with MIT License 6 votes vote down vote up
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; 
Example #2
Source File: model.py    From EvilOSX with GNU General Public License v3.0 6 votes vote down vote up
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() 
Example #3
Source File: HMAC.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
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") 
Example #4
Source File: crypto.py    From training with Apache License 2.0 6 votes vote down vote up
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 
Example #5
Source File: BLAKE2b.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
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") 
Example #6
Source File: BLAKE2s.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
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") 
Example #7
Source File: CMAC.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
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") 
Example #8
Source File: ECC.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #9
Source File: Salsa20.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #10
Source File: HMAC.py    From PokemonGo-DesktopMap with MIT License 6 votes vote down vote up
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") 
Example #11
Source File: CMAC.py    From PokemonGo-DesktopMap with MIT License 6 votes vote down vote up
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") 
Example #12
Source File: ECC.py    From PokemonGo-DesktopMap with MIT License 6 votes vote down vote up
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) 
Example #13
Source File: HMAC.py    From PokemonGo-DesktopMap with MIT License 6 votes vote down vote up
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") 
Example #14
Source File: BLAKE2b.py    From PokemonGo-DesktopMap with MIT License 6 votes vote down vote up
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") 
Example #15
Source File: BLAKE2s.py    From PokemonGo-DesktopMap with MIT License 6 votes vote down vote up
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") 
Example #16
Source File: CMAC.py    From PokemonGo-DesktopMap with MIT License 6 votes vote down vote up
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") 
Example #17
Source File: Salsa20.py    From PokemonGo-DesktopMap with MIT License 6 votes vote down vote up
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) 
Example #18
Source File: BLAKE2s.py    From PokemonGo-DesktopMap with MIT License 6 votes vote down vote up
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") 
Example #19
Source File: _mode_openpgp.py    From PokemonGo-DesktopMap with MIT License 5 votes vote down vote up
def _create_openpgp_cipher(factory, **kwargs):
    """Create a new block cipher, configured in OpenPGP mode.

    :Parameters:
      factory : module
        The module.

    :Keywords:
      key : byte string
        The secret key to use in the symmetric cipher.

      IV : byte string
        The initialization vector to use for encryption or decryption.

        For encryption, the IV must be as long as the cipher block size.

        For decryption, it must be 2 bytes longer (it is actually the
        *encrypted* IV which was prefixed to the ciphertext).
    """

    iv = kwargs.pop("IV", None)
    IV = kwargs.pop("iv", None)

    if (None, None) == (iv, IV):
        iv = get_random_bytes(factory.block_size)
    if iv is not None:
        if IV is not None:
            raise TypeError("You must either use 'iv' or 'IV', not both")
    else:
        iv = IV

    try:
        key = kwargs.pop("key")
    except KeyError, e:
        raise TypeError("Missing component: " + str(e)) 
Example #20
Source File: PKCS1_OAEP.py    From PokemonGo-DesktopMap with MIT License 5 votes vote down vote up
def new(key, hashAlgo=None, mgfunc=None, label=b(''), randfunc=None):
    """Return a cipher object `PKCS1OAEP_Cipher` that can be used to perform PKCS#1 OAEP encryption or decryption.

    :Parameters:
     key : RSA key object
      The key to use to encrypt or decrypt the message. This is a `Cryptodome.PublicKey.RSA` object.
      Decryption is only possible if *key* is a private RSA key.
     hashAlgo : hash object
      The hash function to use. This can be a module under `Cryptodome.Hash`
      or an existing hash object created from any of such modules. If not specified,
      `Cryptodome.Hash.SHA1` is used.
     mgfunc : callable
      A mask generation function that accepts two parameters: a string to
      use as seed, and the lenth of the mask to generate, in bytes.
      If not specified, the standard MGF1 is used (a safe choice).
     label : byte string
      A label to apply to this particular encryption. If not specified,
      an empty string is used. Specifying a label does not improve
      security.
     randfunc : callable
      A function that returns random bytes.
      The default is `Random.get_random_bytes`.

    :attention: Modify the mask generation function only if you know what you are doing.
      Sender and receiver must use the same one.
    """

    if randfunc is None:
        randfunc = Random.get_random_bytes
    return PKCS1OAEP_Cipher(key, hashAlgo, mgfunc, label, randfunc) 
Example #21
Source File: PKCS1_v1_5.py    From PokemonGo-DesktopMap with MIT License 5 votes vote down vote up
def new(key, randfunc=None):
    """Return a cipher object `PKCS115_Cipher` that can be used to perform PKCS#1 v1.5 encryption or decryption.

    :Parameters:
     key : RSA key object
      The key to use to encrypt or decrypt the message. This is a `Cryptodome.PublicKey.RSA` object.
      Decryption is only possible if *key* is a private RSA key.
     randfunc : callable
      Function that return random bytes.
      The default is `Cryptodome.Random.get_random_bytes`.
    """

    if randfunc is None:
        randfunc = Random.get_random_bytes
    return PKCS115_Cipher(key, randfunc) 
Example #22
Source File: utils.py    From ontology-python-sdk with GNU Lesser General Public License v3.0 5 votes vote down vote up
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] 
Example #23
Source File: _mode_eax.py    From PokemonGo-DesktopMap with MIT License 5 votes vote down vote up
def verify(self, received_mac_tag):
        """Validate the *binary* MAC tag.

        The caller invokes this function at the very end.

        This method checks if the decrypted message is indeed valid
        (that is, if the key is correct) and it has not been
        tampered with while in transit.

        :Parameters:
          received_mac_tag : byte string
            This is the *binary* MAC, as received from the sender.
        :Raises MacMismatchError:
            if the MAC does not match. The message has been tampered with
            or the key is incorrect.
        """

        if self.verify not in self._next:
            raise TypeError("verify() cannot be called"
                                " when encrypting a message")
        self._next = [self.verify]

        if not self._mac_tag:
            tag = bchr(0) * self.block_size
            for i in xrange(3):
                tag = strxor(tag, self._omac[i].digest())
            self._mac_tag = tag[:self._mac_len]

        secret = get_random_bytes(16)

        mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=self._mac_tag)
        mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=received_mac_tag)

        if mac1.digest() != mac2.digest():
            raise ValueError("MAC check failed") 
Example #24
Source File: _mode_ocb.py    From PokemonGo-DesktopMap with MIT License 5 votes vote down vote up
def verify(self, received_mac_tag):
        """Validate the *binary* MAC tag.

        Call this method after the final `decrypt` (the one with no arguments)
        to check if the message is authentic and valid.

        :Parameters:
          received_mac_tag : byte string
            This is the *binary* MAC, as received from the sender.
        :Raises ValueError:
            if the MAC does not match. The message has been tampered with
            or the key is incorrect.
        """

        if self.verify not in self._next:
            raise TypeError("verify() cannot be called now for this cipher")

        assert(len(self._cache_P) == 0)

        self._next = [self.verify]

        if self._mac_tag is None:
            self._compute_mac_tag()

        secret = get_random_bytes(16)
        mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=self._mac_tag)
        mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=received_mac_tag)

        if mac1.digest() != mac2.digest():
            raise ValueError("MAC check failed") 
Example #25
Source File: _mode_ocb.py    From PokemonGo-DesktopMap with MIT License 5 votes vote down vote up
def _create_ocb_cipher(factory, **kwargs):
    """Create a new block cipher, configured in OCB mode.

    :Parameters:
      factory : module
        A symmetric cipher module from `Cryptodome.Cipher`
        (like `Cryptodome.Cipher.AES`).

    :Keywords:
      nonce : byte string
        A  value that must never be reused for any other encryption.
        Its length can vary from 1 to 15 bytes.
        If not specified, a random 15 bytes long nonce is generated.

      mac_len : integer
        Length of the MAC, in bytes.
        It must be in the range ``[8..16]``.
        The default is 16 (128 bits).

    Any other keyword will be passed to the underlying block cipher.
    See the relevant documentation for details (at least ``key`` will need
    to be present).
    """

    try:
        nonce = kwargs.pop("nonce", None)
        if nonce is None:
            nonce = get_random_bytes(15)
        mac_len = kwargs.pop("mac_len", 16)
    except KeyError, e:
        raise TypeError("Keyword missing: " + str(e)) 
Example #26
Source File: _mode_ccm.py    From PokemonGo-DesktopMap with MIT License 5 votes vote down vote up
def verify(self, received_mac_tag):
        """Validate the *binary* MAC tag.

        The caller invokes this function at the very end.

        This method checks if the decrypted message is indeed valid
        (that is, if the key is correct) and it has not been
        tampered with while in transit.

        :Parameters:
          received_mac_tag : byte string
            This is the *binary* MAC, as received from the sender.
        :Raises ValueError:
            if the MAC does not match. The message has been tampered with
            or the key is incorrect.
        """

        if self.verify not in self._next:
            raise TypeError("verify() cannot be called"
                            " when encrypting a message")
        self._next = [self.verify]

        self._digest()
        secret = get_random_bytes(16)

        mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=self._mac_tag)
        mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=received_mac_tag)

        if mac1.digest() != mac2.digest():
            raise ValueError("MAC check failed") 
Example #27
Source File: cryptodome.py    From keylime with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def generate_random_key(size=32):
    return get_random_bytes(size) 
Example #28
Source File: secure_utils.py    From aztk with MIT License 5 votes vote down vote up
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] 
Example #29
Source File: _mode_gcm.py    From PokemonGo-DesktopMap with MIT License 5 votes vote down vote up
def verify(self, received_mac_tag):
        """Validate the *binary* MAC tag.

        The caller invokes this function at the very end.

        This method checks if the decrypted message is indeed valid
        (that is, if the key is correct) and it has not been
        tampered with while in transit.

        :Parameters:
          received_mac_tag : byte string
            This is the *binary* MAC, as received from the sender.
        :Raises ValueError:
            if the MAC does not match. The message has been tampered with
            or the key is incorrect.
        """

        if self.verify not in self._next:
            raise TypeError("verify() cannot be called"
                            " when encrypting a message")
        self._next = [self.verify]

        secret = get_random_bytes(16)

        mac1 = BLAKE2s.new(digest_bits=160, key=secret,
                           data=self._compute_mac())
        mac2 = BLAKE2s.new(digest_bits=160, key=secret,
                           data=received_mac_tag)

        if mac1.digest() != mac2.digest():
            raise ValueError("MAC check failed") 
Example #30
Source File: default_crypto.py    From plugin.video.netflix with MIT License 5 votes vote down vote up
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)