Esempio n. 1
0
    def __init__(self, key, nonce, mac_len=16):
        self._mac_len = mac_len
        self._omac = [cmac.CMAC(algo.AES(key), defb()) for i in range(3)]

        for i in range(3):
            self._omac[i].update(
                bytes(1) * (algo.AES.block_size // 8 - 1) +
                struct.pack("B", i)  # noqa: W503
            )

        self._omac[0].update(nonce)
        self._auth = _AuthWrapper(self._omac[1])

        # create a cache since cryptography allows us to calculate tag
        # only once... why...
        self._omac_cache = []
        self._omac_cache.append(self._omac[0].finalize())

        self._cipher = CrCipher(
            algo.AES(key),
            modes.CTR(self._omac_cache[0]),
            defb(),
        )

        self.__ctx = None
        self._updated = False
        self.__tag = None
Esempio n. 2
0
 def _construct_hash(name, data=b"", digest_size=None):
     if name in VAR_DIGEST_SIZE:
         if digest_size is None and name in XOFS:  # pragma: no cover
             raise ValueError("value of digest-size is required")
         hash_ = h.Hash(HASHES[name](digest_size), defb())
     else:
         hash_ = h.Hash(HASHES[name](), defb())
     hash_.update(data)
     return hash_
Esempio n. 3
0
    def load(cls, data: bytes) -> DHPublicKey:
        """Deserialize and load the public key.

        Args:
            data (bytes): The serialized public key as ``bytes-like`` object.

        Returns:
            DHPublicKey: A public key object.

        Raises:
            ValueError: If the key could not be deserialized.
        """
        fmts = {
            b"-----": ser.load_pem_public_key,
            b"0": ser.load_der_public_key,
        }

        try:
            loader = fmts[[*filter(data.startswith, fmts)][0]]
        except IndexError:
            raise ValueError("Invalid format.") from None

        try:
            key = loader(memoryview(data), defb())
            return cls(key=key)
        except ValueError as e:
            raise ValueError(
                "Cannot deserialize key. Incorrect key format.", ) from e
Esempio n. 4
0
    def load(cls, data: bytes) -> DHParameters:
        """Load the :any:`DHParameters` from the encoded format.

        Args:
            data (bytes, bytearray):
                The parameters as an encoded bytes object.

        Returns:
            DHParameters: DH parameter object.
        """
        fmts = {
            b"-----BEGIN DH PARAMETERS": ser.load_pem_parameters,
            b"0": ser.load_der_parameters,
        }

        try:
            loader = fmts[[*filter(data.startswith, fmts)][0]]
        except IndexError:
            raise ValueError("Invalid format.") from None
        try:
            params = loader(data, defb())
            if not isinstance(params, dh.DHParameters):
                raise ValueError("Invalid parameter format.")
            return cls(None, parameter=params)
        except ValueError as e:
            raise ValueError(
                "Cannot deserialize key. Either Key format is invalid or "
                "passphrase is missing or incorrect.") from e
Esempio n. 5
0
 def __getPolyKey(self, key):
     cipher = Cipher(algo.ChaCha20(key, self._nonceCounter), None, defb())
     cipher = cipher.encryptor()
     key = cipher.update(
         b"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
     )
     return key
Esempio n. 6
0
    def load(cls, data: bytes) -> RSAPublicKey:
        """Loads the public key as ``bytes`` object and returns
        the Key interface.

        Args:
            data (bytes):
                The key as bytes object.

        Returns:
            RSAPublicKey: The RSA public key.

        Raises:
            ValueError: if the key could not be deserialized.
        """
        fmts = {
            b"ssh-rsa ": ser.load_ssh_public_key,
            b"-----": ser.load_pem_public_key,
            b"0": ser.load_der_public_key,
        }

        try:
            loader = fmts[[*filter(data.startswith, fmts)][0]]
        except IndexError:
            raise ValueError("Invalid format.") from None

        try:
            return cls(loader(memoryview(data), defb()))
        except ValueError as e:
            raise ValueError(
                "Cannot deserialize key. The key format might be invalid."
            ) from e
Esempio n. 7
0
def derive_poly1305_key(ckey: bytes, nonce: bytes) -> bytes:
    """Generate a poly1305 key.

    Args:
        ckey (bytes): The key used for the cipher
        nonce (bytes): The nonce used for the cipher. It must be 12 bytes.

    Returns:
        bytes: A Poly1305 key.

    Raises:
        ValueError: If the length of nonce is not equal to 8 or 12 bytes.
    """
    if len(nonce) not in (8, 12):
        raise ValueError("Poly1305 key must be 16 bytes long.")

    if len(nonce) == 8:
        nonce = bytes(4) + nonce

    crp = Cipher(
        algo.ChaCha20(ckey,
                      bytes(4) + nonce),
        None,
        defb(),
    ).encryptor()
    return crp.update(bytes(32))
Esempio n. 8
0
def derive_hkdf_key(
    master_key: bytes,
    dklen: int,
    hashalgo: typing.Union[str, BaseHash],
    salt: bytes,
    cipher_ctx: bytes = b"enc-key",
    auth_ctx: bytes = b"auth-key",
) -> typing.Tuple[bytes, bytes]:
    """Derive key materials for HMAC from given master key.

    Args:
        master_key (bytes): The key used to derive the keys from.
        dklen (int): Desired lenth of the derived key.
        hashalgo (str, BaseHash): The name of the hash algorithm.
        salt (bytes): The salt to use.
        cipher_ctx (bytes): Context for cipher.
        auth_ctx (bytes): Context for HMAC.

    Returns:
        tuple[bytes, bytes]: A pair of *cipher key* and *MAC key*.
    """
    if isinstance(hashalgo, str):
        hash_ = _hashes[hashalgo]()
    elif isinstance(hashalgo, BaseHash):
        hash_ = _get_hash_algorithm(hashalgo)
    else:
        raise TypeError(
            "hashalgo must be a str or an object implementing BaseHash.")

    key = HKDF(
        hash_,
        dklen,
        salt,
        cipher_ctx,
        defb(),
    ).derive(master_key)

    hkey = HKDF(
        hash_,
        hash_.digest_size,
        salt,
        auth_ctx,
        defb(),
    ).derive(master_key)
    return key, hkey
Esempio n. 9
0
    def __init__(self, encrypting, key, mode, iv_or_nonce):
        cipher = Cipher(
            algo.Camellia(key),
            SUPPORTED[mode](iv_or_nonce),
            defb(),
        )

        self._ctx = cipher.encryptor() if encrypting else cipher.decryptor()
        self._encrypting = encrypting
Esempio n. 10
0
def _aes_cipher(key, mode, nonce_or_iv):
    if mode == _m.MODE_EAX:
        return _EAX(key, nonce_or_iv)
    if mode in modes_.special:
        if mode == _m.MODE_CCM:
            if not 7 <= len(nonce_or_iv) <= 13:
                raise ValueError(
                    "Length of nonce must be between 7 and 13 bytes.")
        return SUPPORTED[mode](key)

    return CrCipher(algo.AES(key), SUPPORTED[mode](nonce_or_iv), defb())
Esempio n. 11
0
 def __init__(self, curve: str, **kwargs):
     if kwargs:
         self._key = kwargs.pop("key")
         return
     try:
         if curve not in SPECIAL_CURVES:
             self._key = ec.generate_private_key(CURVES[curve], defb())
             return
         self._key = SPECIAL_CURVES[curve].generate()
     except KeyError as e:
         raise ValueError(f"Invalid curve: {curve}") from e
Esempio n. 12
0
    def __init__(self, n: int, e: int = 65537, **kwargs):
        if kwargs:
            self._key = kwargs.pop("key")
        else:
            self._key = rsa.generate_private_key(e, n, defb())

        # numbers
        nos = self._key.private_numbers()
        self._p = nos.p
        self._q = nos.q
        self._d = nos.d
Esempio n. 13
0
 def __init__(self, key_size: int, generator: int = 2, **kwargs):
     if kwargs:
         params = kwargs.pop("parameter")
         if not isinstance(params, dh.DHParameters):
             raise ValueError("The parameter is not a DH parameter object.")
         self._params = params
     else:
         self._params = dh.generate_parameters(
             generator,
             key_size,
             defb(),
         )
Esempio n. 14
0
    def load(
        cls,
        data: bytes,
        passphrase: typing.Optional[bytes] = None,
    ) -> RSAPrivateKey:
        """Loads the private key as ``bytes`` object and returns
        the Key interface.

        Args:
            data (bytes, bytearray):
                The key as bytes object.
            passphrase (bytes, bytearray):
                The passphrase that deserializes the private key.
                ``passphrase`` must be a ``bytes-like`` object if the key was
                encrypted while serialization, otherwise ``None``.

        Returns:
            RSAPrivateKey: RSA private key.

        Raises:
            ValueError: if the key could not be deserialized.
        """
        fmts = {
            b"-----BEGIN OPENSSH PRIVATE KEY": ser.load_ssh_private_key,
            b"-----": ser.load_pem_private_key,
            b"0": ser.load_der_private_key,
        }

        try:
            loader = fmts[[*filter(data.startswith, fmts)][0]]
        except IndexError:
            raise ValueError("Invalid format.") from None

        # type check
        if passphrase is not None:
            passphrase = memoryview(passphrase)

        try:
            key = loader(memoryview(data), passphrase, defb())
            if not isinstance(key, rsa.RSAPrivateKey):
                raise ValueError("The key is not an RSA private key.")
            return cls(None, key=key)
        except ValueError as e:
            raise ValueError(
                "Cannot deserialize key. Either Key format is invalid or "
                "passphrase is incorrect.") from e
        except TypeError as e:
            raise ValueError(
                "The key is encrypted but the passphrase is not given or the"
                " key is not encrypted but the passphrase is given."
                " Cannot deserialize the key.") from e
Esempio n. 15
0
    def load(
        cls,
        data: bytes,
        passphrase: typing.Optional[bytes] = None,
    ) -> DHPrivateKey:
        """Deserialize and load the the private key.

        Args:
            data (bytes): The serialized private key as ``bytes-like`` object.
            passphrase (bytes, bytearray):
                The passphrase that was used to protect the private key.
                If key is not protected, passphrase is ``None``.

        Returns:
            DHPrivateKey: A private key.

        Raises:
            ValueError: If the key could not be deserialized.
            TypeError: If passphrase is not a bytes-like object.
        """
        fmts = {
            b"-----": ser.load_pem_private_key,
            b"0": ser.load_der_private_key,
        }

        try:
            loader = fmts[[*filter(data.startswith, fmts)][0]]
        except IndexError:
            raise ValueError("Invalid format.") from None

        # type check
        if passphrase is not None:
            if not isinstance(passphrase, (bytes, bytearray, memoryview)):
                raise TypeError("passphrase must be a bytes-like object.")

        try:
            key = loader(
                memoryview(data),
                passphrase,
                defb(),
            )
            return cls(key)
        except ValueError as e:
            raise ValueError(
                "Cannot deserialize key. Either Key format is invalid or "
                "passphrase is incorrect.") from e
        except TypeError as e:
            raise ValueError(
                "The key is encrypted but the passphrase is not given or the"
                " key is not encrypted but the passphrase is given."
                " Cannot deserialize the key.") from e
Esempio n. 16
0
    def __init__(self, encrypt, key, nonce):
        self._encrypt = encrypt
        self._dataLength = 0
        self._aadLength = 0
        self._nonceCounter = (0).to_bytes(4, byteorder='little') + nonce
        self._nonceEncrypt = (1).to_bytes(4, byteorder='little') + nonce

        cipher = Cipher(algo.ChaCha20(key, self._nonceEncrypt), None, defb())

        if encrypt:
            self._cipher = cipher.encryptor()
        else:
            self._cipher = cipher.decryptor()

        polyKey = self.__getPolyKey(key)
        self._auth = Poly1305(polyKey)
Esempio n. 17
0
    def __init__(self, encrypting, key, nonce):
        if not len(nonce) in (8, 12):
            raise ValueError("A 8 or 12 byte nonce is required")
        if len(nonce) == 8:
            nonce = bytes(4) + nonce

        cipher = Cipher(
            algo.ChaCha20(
                key,
                bytes(4) + nonce,
            ),
            None,
            defb(),
        )

        self._ctx = cipher.encryptor() if encrypting else cipher.decryptor()
        self._encrypting = encrypting
Esempio n. 18
0
    def load_from_parameters(
        cls,
        p: int,
        g: int = 2,
        q: typing.Optional[int] = None,
    ) -> DHParameters:
        """Generates a DH parameter group from the parameters.

        Args:
            p (int): The prime modulus value.
            g (int): The generator value. Must be 2 or 5. Default is 2.
            q (int): p subgroup order value. Defaults to ``None``.

        Returns:
            DHParameters: DHParameters object.
        """
        param_nos = dh.DHParameterNumbers(p, g, q)
        return cls(None, parameter=param_nos.parameters(defb()))
Esempio n. 19
0
    def load(cls, data: bytes, *, edwards: bool = True) -> ECCPublicKey:
        """Loads the public key as ``bytes`` object and returns
        the Key interface.

        Args:
            data (bytes, bytearray):
                The key as bytes object.

        Keyword Arguments:
            edwards (bool):
                Whether the ``Raw`` encoded key of length 32 bytes
                must be imported as an ``Ed25519`` key or ``X25519`` key.

                If ``True``, the key will be imported as an ``Ed25519`` key,
                otherwise an ``X25519`` key.

                This argument is ignored for all other serialized key types.

        Returns:
            ECCPublicKey: The ECC public key.

        Raises:
            ValueError: if the key could not be deserialized.
        """
        fmts = {
            b"ecdsa-": ser.load_ssh_public_key,
            b"-----": ser.load_pem_public_key,
            b"0": ser.load_der_public_key,
        }

        try:
            loader = fmts[[*filter(data.startswith, fmts)][0]]
        except IndexError:
            loader = cls._get_raw_ecc_loader(data, edwards)

        try:
            key = loader(memoryview(data), defb())
            return cls(key=key)
        except ValueError as e:
            raise ValueError(
                "Cannot deserialize key. Incorrect key format.", ) from e
Esempio n. 20
0
    def __init__(self, encrypting, key, nonce):
        if not len(nonce) in (8, 12):
            raise ValueError("A 8 or 12 byte nonce is required")
        if len(nonce) == 8:
            nonce = bytes(4) + nonce

        cipher = Cipher(
            algo.ChaCha20(
                key,
                (1).to_bytes(4, "little") + nonce,
            ),
            None,
            defb(),
        )

        ctx = cipher.encryptor() if encrypting else cipher.decryptor()

        self._encrypting = encrypting
        self._auth = Poly1305(derive_poly1305_key(key, nonce))
        self._ctx = self._get_auth_ctx(encrypting, ctx, self._auth)
        self._len_aad, self._len_ct = 0, 0
        self._updated = False
        self._tag = None
Esempio n. 21
0
    def load(
        cls,
        data: bytes,
        passphrase: typing.Optional[bytes] = None,
        *,
        edwards: bool = True,
    ) -> ECCPrivateKey:
        """Loads the private key as `bytes` object and returns a key object.

        Args:
            data (bytes, bytearray):
                The key as a ``bytes-like`` object.
            passphrase (bytes, bytearray, memoryview, None):
                The passphrase that deserializes the private key.
                ``passphrase`` must be a ``bytes-like`` object if the key
                was encrypted while serialization, otherwise ``None``.

        Keyword Arguments:
            edwards (bool):
                Whether the ``Raw`` encoded key of length 32 bytes
                must be imported as an ``Ed25519`` key or ``X25519`` key.

                If ``True``, the key will be imported as an ``Ed25519`` key,
                otherwise an ``X25519`` key.

                This argument is ignored for all other serialized key types.

        Returns:
            ECCPrivateKey: A private key.

        Raises:
            ValueError: if the key could not be deserialized.
            TypeError: if passphrase is not a bytes object.
        """
        # type check
        if passphrase is not None:
            if not isinstance(passphrase, (bytes, bytearray, memoryview)):
                raise TypeError("passphrase must be a bytes object.")

        fmts = {
            b"-----BEGIN OPENSSH PRIVATE KEY": ser.load_ssh_private_key,
            b"-----": ser.load_pem_private_key,
            b"0": ser.load_der_private_key,
        }

        try:
            loader = fmts[[*filter(data.startswith, fmts)][0]]
        except IndexError:
            loader = cls._get_raw_ecc_loader(data, edwards)

        # type check
        if passphrase is not None:
            if not isinstance(passphrase, (bytes, bytearray, memoryview)):
                raise TypeError("passphrase must be a bytes-like object.")

        try:
            key = loader(memoryview(data), passphrase, defb())
            if not isinstance(
                    key,
                (ec.EllipticCurvePrivateKey, *SPECIAL_CURVES.values())):
                raise ValueError("The key is not an EC private key.")
            return cls(None, key=key)
        except ValueError as e:
            raise ValueError(
                "Cannot deserialize key. Either Key format is invalid or "
                "passphrase is incorrect.") from e
        except TypeError as e:
            raise ValueError(
                "The key is encrypted but the passphrase is not given or the"
                " key is not encrypted but the passphrase is given."
                " Cannot deserialize the key.") from e