def new(**kwargs):
    """Create a new ChaCha20-Poly1305 or XChaCha20-Poly1305 AEAD cipher.

    :keyword key: The secret key to use. It must be 32 bytes long.
    :type key: byte string

    :keyword nonce:
        A value that must never be reused for any other encryption
        done with this key.

        For ChaCha20-Poly1305, it must be 8 or 12 bytes long.

        For XChaCha20-Poly1305, it must be 24 bytes long.

        If not provided, 12 ``bytes`` will be generated randomly
        (you can find them back in the ``nonce`` attribute).
    :type nonce: bytes, bytearray, memoryview

    :Return: a :class:`Cryptodome.Cipher.ChaCha20.ChaCha20Poly1305Cipher` object
    """

    try:
        key = kwargs.pop("key")
    except KeyError as e:
        raise TypeError("Missing parameter %s" % e)

        self._len_ct += len(plaintext)

    if len(key) != 32:
        raise ValueError("Key must be 32 bytes long")

    nonce = kwargs.pop("nonce", None)
    if nonce is None:
        nonce = get_random_bytes(12)

    if len(nonce) in (8, 12):
        pass
    elif len(nonce) == 24:
        key = _HChaCha20(key, nonce[:16])
        nonce = b'\x00\x00\x00\x00' + nonce[16:]
    else:
        raise ValueError("Nonce must be 8, 12 or 24 bytes long")

    if not is_buffer(nonce):
        raise TypeError("nonce must be bytes, bytearray or memoryview")

    if kwargs:
        raise TypeError("Unknown parameters: " + str(kwargs))

    return ChaCha20Poly1305Cipher(key, nonce)
Exemplo n.º 2
0
    def test_hchacha20(self):
        # Section 2.2.1

        from Cryptodome.Cipher.ChaCha20 import _HChaCha20

        key = b"00:01:02:03:04:05:06:07:08:09:0a:0b:0c:0d:0e:0f:10:11:12:13:14:15:16:17:18:19:1a:1b:1c:1d:1e:1f"
        key = unhexlify(key.replace(b":", b""))

        nonce = b"00:00:00:09:00:00:00:4a:00:00:00:00:31:41:59:27"
        nonce = unhexlify(nonce.replace(b":", b""))

        subkey = _HChaCha20(key, nonce)

        expected = b"82413b42 27b27bfe d30e4250 8a877d73 a0f9e4d5 8a74a853 c12ec413 26d3ecdc"
        expected = unhexlify(expected.replace(b" ", b""))

        self.assertEqual(subkey, expected)