Esempio n. 1
0
    def __init__(self, factory, key, nonce, kwargs):
        self.block_size = factory.block_size
        self._factory = factory

        self._nonce = nonce
        self._cipher_params = kwargs

        if len(key) not in (32, 48, 64):
            raise ValueError("Incorrect key length (%d bytes)" % len(key))

        if nonce is not None:
            if not byte_string(nonce):
                raise TypeError("When provided, the nonce must be a byte string")

            if len(nonce) == 0:
                raise ValueError("When provided, the nonce must be non-empty")

            #: Public attribute is only available in case of non-deterministic
            #: encryption
            self.nonce = nonce

        subkey_size = len(key) // 2

        self._mac_tag = None  # Cache for MAC tag
        self._kdf = _S2V(key[:subkey_size],
                         ciphermod=factory,
                         cipher_params=self._cipher_params)
        self._subkey_cipher = key[subkey_size:]

        # Purely for the purpose of verifying that cipher_params are OK
        factory.new(key[:subkey_size], factory.MODE_ECB, **kwargs)

        # Allowed transitions after initialization
        self._next = [self.update, self.encrypt, self.decrypt,
                      self.digest, self.verify]
Esempio n. 2
0
 def _start_siv(self, factory, key, *args, **kwargs):
     subkey_size, rem = divmod(len(key), 2)
     if rem:
         raise ValueError('MODE_SIV requires a key twice as long as for the underlying cipher')
     self.nonce = _getParameter('nonce', 1, args, kwargs)
     self._cipherMAC = _S2V(key[:subkey_size], ciphermod=factory)
     self._subkey_ctr = key[subkey_size:]
     self._mac_len = factory.block_size
     self._cipherMAC = self._cipherMAC
     self._next = [self.update,
      self.encrypt,
      self.decrypt,
      self.digest,
      self.verify]
Esempio n. 3
0
 def _start_siv(self, factory, key, *args, **kwargs):
     subkey_size, rem = divmod(len(key), 2)
     if rem:
         raise ValueError('MODE_SIV requires a key twice as long as for the underlying cipher')
     self.nonce = _getParameter('nonce', 1, args, kwargs)
     self._cipherMAC = _S2V(key[:subkey_size], ciphermod=factory)
     self._subkey_ctr = key[subkey_size:]
     self._mac_len = factory.block_size
     self._cipherMAC = self._cipherMAC
     self._next = [self.update,
      self.encrypt,
      self.decrypt,
      self.digest,
      self.verify]
Esempio n. 4
0
    def __init__(self, factory, **kwargs):
        """Create a new block cipher, configured in
        Synthetic Initializaton Vector (SIV) mode.

        :Parameters:
          factory : object
            A symmetric cipher module from `Crypto.Cipher`
            (like `Crypto.Cipher.AES`).
        :Keywords:
          key : byte string
            The secret key to use in the symmetric cipher.
            It must be 32, 48 or 64 bytes long.
            If AES is the chosen cipher, the variants *AES-128*,
            *AES-192* and or *AES-256* will be used internally.
          nonce : byte string
            A mandatory value that must never be reused for any other encryption.
            There are no restrictions on its length,
            but it is recommended to use at least 16 bytes.

            The nonce shall never repeat for two different messages encrypted
            with the same key, but it does not need to be random.
        """

        self.block_size = factory.block_size
        self._factory = factory

        try:
            self._key = key = kwargs.pop("key")
        except KeyError as e:
            raise TypeError("Missing parameter: " + str(e))

        self._nonce = kwargs.pop("nonce", None)

        self._cipher_params = dict(kwargs)

        subkey_size = len(key) // 2
        if len(key) & 1:
            raise ValueError("MODE_SIV requires a key twice as long as"
                             " for the underlying cipher")

        self._mac_tag = None  # Cache for MAC tag
        self._kdf = _S2V(key[:subkey_size],
                         ciphermod=factory,
                         cipher_params=self._cipher_params)
        self._subkey_cipher = key[subkey_size:]

        # Allowed transitions after initialization
        self._next = [
            self.update, self.encrypt, self.decrypt, self.digest, self.verify
        ]
Esempio n. 5
0
    def _start_siv(self, factory, key, *args, **kwargs):

        subkey_size, rem = divmod(len(key), 2)
        if rem:
            raise ValueError("MODE_SIV requires a key twice as long as for the underlying cipher")

        # IV is optional
        self.nonce = _getParameter("nonce", 1, args, kwargs)

        self._cipherMAC = _S2V(key[:subkey_size], ciphermod=factory)
        self._subkey_ctr = key[subkey_size:]
        self._mac_len = factory.block_size

        self._cipherMAC = self._cipherMAC

        # Allowed transitions after initialization
        self._next = [self.update, self.encrypt, self.decrypt, self.digest, self.verify]
Esempio n. 6
0
    def __init__(self, factory, key, nonce, kwargs):

        self.block_size = factory.block_size
        """The block size of the underlying cipher, in bytes."""

        self._factory = factory

        self._cipher_params = kwargs

        if len(key) not in (32, 48, 64):
            raise ValueError("Incorrect key length (%d bytes)" % len(key))

        if nonce is not None:
            if not is_buffer(nonce):
                raise TypeError(
                    "When provided, the nonce must be bytes, bytearray or memoryview"
                )

            if len(nonce) == 0:
                raise ValueError("When provided, the nonce must be non-empty")

            self.nonce = _copy_bytes(None, None, nonce)
            """Public attribute is only available in case of non-deterministic
            encryption."""

        subkey_size = len(key) // 2

        self._mac_tag = None  # Cache for MAC tag
        self._kdf = _S2V(key[:subkey_size],
                         ciphermod=factory,
                         cipher_params=self._cipher_params)
        self._subkey_cipher = key[subkey_size:]

        # Purely for the purpose of verifying that cipher_params are OK
        factory.new(key[:subkey_size], factory.MODE_ECB, **kwargs)

        # Allowed transitions after initialization
        self._next = [
            self.update, self.encrypt, self.decrypt, self.digest, self.verify
        ]
Esempio n. 7
0
    def __init__(self, factory, key, nonce, kwargs):

        self.block_size = factory.block_size
        """The block size of the underlying cipher, in bytes."""

        self._factory = factory

        self._cipher_params = kwargs

        if len(key) not in (32, 48, 64):
            raise ValueError("Incorrect key length (%d bytes)" % len(key))

        if nonce is not None:
            if not is_buffer(nonce):
                raise TypeError("When provided, the nonce must be bytes, bytearray or memoryview")

            if len(nonce) == 0:
                raise ValueError("When provided, the nonce must be non-empty")

            self.nonce = _copy_bytes(None, None, nonce)
            """Public attribute is only available in case of non-deterministic
            encryption."""

        subkey_size = len(key) // 2

        self._mac_tag = None  # Cache for MAC tag
        self._kdf = _S2V(key[:subkey_size],
                         ciphermod=factory,
                         cipher_params=self._cipher_params)
        self._subkey_cipher = key[subkey_size:]

        # Purely for the purpose of verifying that cipher_params are OK
        factory.new(key[:subkey_size], factory.MODE_ECB, **kwargs)

        # Allowed transitions after initialization
        self._next = [self.update, self.encrypt, self.decrypt,
                      self.digest, self.verify]
class SivMode(object):
    """Synthetic Initialization Vector (SIV).

    This is an Authenticated Encryption with Associated Data (`AEAD`_) mode.
    It provides both confidentiality and authenticity.

    The header of the message may be left in the clear, if needed, and it will
    still be subject to authentication. The decryption step tells the receiver
    if the message comes from a source that really knowns the secret key.
    Additionally, decryption detects if any part of the message - including the
    header - has been modified or corrupted.

    If the data being encrypted is completely unpredictable to an adversary
    (e.g. a secret key, for key wrapping purposes) a nonce is not strictly
    required.

    Otherwise, a *nonce* has to be provided.

    Unlike other AEAD modes such as CCM, EAX or GCM, accidental reuse of a
    nonce is not catastrophic for the confidentiality of the message. The only
    effect is that an attacker can tell when the same plaintext (and same
    associated data) is protected with the same key.

    The length of the MAC is fixed to the block size of the underlying cipher.
    The key size is twice the length of the key of the underlying cipher.

    This mode is only available for AES ciphers.

    +--------------------+---------------+-------------------+
    |      Cipher        | SIV MAC size  |   SIV key length  |
    |                    |    (bytes)    |     (bytes)       |
    +====================+===============+===================+
    |    AES-128         |      16       |        32         |
    +--------------------+---------------+-------------------+
    |    AES-192         |      16       |        48         |
    +--------------------+---------------+-------------------+
    |    AES-256         |      16       |        64         |
    +--------------------+---------------+-------------------+

    See `RFC5297`_ and the `original paper`__.

    .. _RFC5297: https://tools.ietf.org/html/rfc5297
    .. _AEAD: http://blog.cryptographyengineering.com/2012/05/how-to-choose-authenticated-encryption.html
    .. __: http://www.cs.ucdavis.edu/~rogaway/papers/keywrap.pdf
    """
    def __init__(self, factory, **kwargs):
        """Create a new block cipher, configured in
        Synthetic Initializaton Vector (SIV) mode.

        :Parameters:
          factory : object
            A symmetric cipher module from `Crypto.Cipher`
            (like `Crypto.Cipher.AES`).
        :Keywords:
          key : byte string
            The secret key to use in the symmetric cipher.
            It must be 32, 48 or 64 bytes long.
            If AES is the chosen cipher, the variants *AES-128*,
            *AES-192* and or *AES-256* will be used internally.
          nonce : byte string
            A mandatory value that must never be reused for any other encryption.
            There are no restrictions on its length,
            but it is recommended to use at least 16 bytes.

            The nonce shall never repeat for two different messages encrypted
            with the same key, but it does not need to be random.
        """

        self.block_size = factory.block_size
        self._factory = factory

        try:
            self._key = key = kwargs.pop("key")
        except KeyError, e:
            raise TypeError("Missing parameter: " + str(e))

        self._nonce = kwargs.pop("nonce", None)

        self._cipher_params = dict(kwargs)

        subkey_size = len(key) // 2
        if len(key) & 1:
            raise ValueError("MODE_SIV requires a key twice as long as"
                             " for the underlying cipher")

        self._mac_tag = None  # Cache for MAC tag
        self._kdf = _S2V(key[:subkey_size],
                         ciphermod=factory,
                         cipher_params=self._cipher_params)
        self._subkey_cipher = key[subkey_size:]

        # Allowed transitions after initialization
        self._next = [
            self.update, self.encrypt, self.decrypt, self.digest, self.verify
        ]