예제 #1
0
    def __init__(self, key, nonce):
        """Initialize a Salsa20 cipher object

        See also `new()` at the module level."""

        if len(key) not in key_size:
            raise ValueError("Incorrect key length for Salsa20 (%d bytes)" % len(key))

        if len(nonce) != 8:
            raise ValueError("Incorrect nonce length for Salsa20 (%d bytes)" %
                             len(nonce))

        self.nonce = _copy_bytes(None, None, nonce)

        self._state = VoidPointer()
        result = _raw_salsa20_lib.Salsa20_stream_init(
                        c_uint8_ptr(key),
                        c_size_t(len(key)),
                        c_uint8_ptr(nonce),
                        c_size_t(len(nonce)),
                        self._state.address_of())
        if result:
            raise ValueError("Error %d instantiating a Salsa20 cipher")
        self._state = SmartPointer(self._state.get(),
                                   _raw_salsa20_lib.Salsa20_stream_destroy)

        self.block_size = 1
        self.key_size = len(key)
예제 #2
0
    def _encrypt(self, plaintext, output):
        """Encrypt without FSM checks"""

        if output is None:
            ciphertext = create_string_buffer(len(plaintext))
        else:
            ciphertext = output

            if not is_writeable_buffer(output):
                raise TypeError("output must be a bytearray or a writeable memoryview")

            if len(plaintext) != len(output):
                raise ValueError("output must have the same length as the input"
                                 "  (%d bytes)" % len(plaintext))

        result = _raw_chacha20_lib.chacha20_encrypt(
                                         self._state.get(),
                                         c_uint8_ptr(plaintext),
                                         c_uint8_ptr(ciphertext),
                                         c_size_t(len(plaintext)))
        if result:
            raise ValueError("Error %d while encrypting with %s" % (result, self._name))

        if output is None:
            return get_raw_buffer(ciphertext)
        else:
            return None
def _create_base_cipher(dict_parameters):
    """This method instantiates and returns a smart pointer to
    a low-level base cipher. It will absorb named parameters in
    the process."""

    try:
        key = dict_parameters.pop("key")
        salt = dict_parameters.pop("salt")
        cost = dict_parameters.pop("cost")
    except KeyError as e:
        raise TypeError("Missing EKSBlowfish parameter: " + str(e))
    invert = dict_parameters.pop("invert", True)

    if len(key) not in key_size:
        raise ValueError("Incorrect EKSBlowfish key length (%d bytes)" %
                         len(key))

    start_operation = _raw_blowfish_lib.EKSBlowfish_start_operation
    stop_operation = _raw_blowfish_lib.EKSBlowfish_stop_operation

    void_p = VoidPointer()
    result = start_operation(c_uint8_ptr(key), c_size_t(len(key)),
                             c_uint8_ptr(salt), c_size_t(len(salt)),
                             c_uint(cost), c_uint(int(invert)),
                             void_p.address_of())
    if result:
        raise ValueError(
            "Error %X while instantiating the EKSBlowfish cipher" % result)
    return SmartPointer(void_p.get(), stop_operation)
예제 #4
0
    def decrypt(self, ciphertext, output=None):
        """Decrypt data with the key and the parameters set at initialization.

        A cipher object is stateful: once you have decrypted a message
        you cannot decrypt (or encrypt) another message with the same
        object.

        The data to decrypt can be broken up in two or
        more pieces and `decrypt` can be called multiple times.

        That is, the statement:

            >>> c.decrypt(a) + c.decrypt(b)

        is equivalent to:

             >>> c.decrypt(a+b)

        This function does not remove any padding from the plaintext.

        :Parameters:
          ciphertext : bytes/bytearray/memoryview
            The piece of data to decrypt.
            It can be of any length.
        :Keywords:
          output : bytearray/memoryview
            The location where the plaintext is written to.
            If ``None``, the plaintext is returned.
        :Return:
          If ``output`` is ``None``, the plaintext is returned as ``bytes``.
          Otherwise, ``None``.
        """

        if self.decrypt not in self._next:
            raise TypeError("decrypt() cannot be called after encrypt()")
        self._next = [ self.decrypt ]
        
        if output is None:
            plaintext = create_string_buffer(len(ciphertext))
        else:
            plaintext = output

            if not is_writeable_buffer(output):
                raise TypeError("output must be a bytearray or a writeable memoryview")
            
            if len(ciphertext) != len(output):
                raise ValueError("output must have the same length as the input"
                                 "  (%d bytes)" % len(plaintext))

        result = raw_ofb_lib.OFB_decrypt(self._state.get(),
                                         c_uint8_ptr(ciphertext),
                                         c_uint8_ptr(plaintext),
                                         c_size_t(len(ciphertext)))
        if result:
            raise ValueError("Error %d while decrypting in OFB mode" % result)

        if output is None:
            return get_raw_buffer(plaintext)
        else:
            return None
예제 #5
0
    def decrypt(self, ciphertext,  output=None):
        """Decrypt data with the key and the parameters set at initialization.

        A cipher object is stateful: once you have decrypted a message
        you cannot decrypt (or encrypt) another message with the same
        object.

        The data to decrypt can be broken up in two or
        more pieces and `decrypt` can be called multiple times.

        That is, the statement:

            >>> c.decrypt(a) + c.decrypt(b)

        is equivalent to:

             >>> c.decrypt(a+b)

        This function does not remove any padding from the plaintext.

        :Parameters:
          ciphertext : bytes/bytearray/memoryview
            The piece of data to decrypt.
            It can be of any length.
        :Keywords:
          output : bytearray/memoryview
            The location where the plaintext must be written to.
            If ``None``, the plaintext is returned.
        :Return:
          If ``output`` is ``None``, the plaintext is returned as ``bytes``.
          Otherwise, ``None``.
        """

        if self.decrypt not in self._next:
            raise TypeError("decrypt() cannot be called after encrypt()")
        self._next = [ self.decrypt ]
        
        if output is None:
            plaintext = create_string_buffer(len(ciphertext))
        else:
            plaintext = output

            if not is_writeable_buffer(output):
                raise TypeError("output must be a bytearray or a writeable memoryview")
            
            if len(ciphertext) != len(output):
                raise ValueError("output must have the same length as the input"
                                 "  (%d bytes)" % len(plaintext))
        
        result = raw_cfb_lib.CFB_decrypt(self._state.get(),
                                         c_uint8_ptr(ciphertext),
                                         c_uint8_ptr(plaintext),
                                         c_size_t(len(ciphertext)))
        if result:
            raise ValueError("Error %d while decrypting in CFB mode" % result)

        if output is None:
            return get_raw_buffer(plaintext)
        else:
            return None
예제 #6
0
    def __init__(self, x, y, curve="p256"):

        try:
            self._curve = _curves[curve]
        except KeyError:
            raise ValueError("Unknown curve name %s" % str(curve))
        self._curve_name = curve

        modulus_bytes = self.size_in_bytes()
        context = self._curve.context

        xb = long_to_bytes(x, modulus_bytes)
        yb = long_to_bytes(y, modulus_bytes)
        if len(xb) != modulus_bytes or len(yb) != modulus_bytes:
            raise ValueError("Incorrect coordinate length")

        self._point = VoidPointer()
        result = _ec_lib.ec_ws_new_point(self._point.address_of(),
                                         c_uint8_ptr(xb),
                                         c_uint8_ptr(yb),
                                         c_size_t(modulus_bytes),
                                         context.get())
        if result:
            if result == 15:
                raise ValueError("The EC point does not belong to the curve")
            raise ValueError("Error %d while instantiating an EC point" % result)

        # Ensure that object disposal of this Python object will (eventually)
        # free the memory allocated by the raw library for the EC point
        self._point = SmartPointer(self._point.get(),
                                   _ec_lib.ec_free_point)
예제 #7
0
    def __init__(self, key, nonce):
        """Initialize a Salsa20 cipher object

        See also `new()` at the module level."""

        if len(key) not in key_size:
            raise ValueError("Incorrect key length for Salsa20 (%d bytes)" %
                             len(key))

        if len(nonce) != 8:
            raise ValueError("Incorrect nonce length for Salsa20 (%d bytes)" %
                             len(nonce))

        self.nonce = _copy_bytes(None, None, nonce)

        self._state = VoidPointer()
        result = _raw_salsa20_lib.Salsa20_stream_init(c_uint8_ptr(key),
                                                      c_size_t(len(key)),
                                                      c_uint8_ptr(nonce),
                                                      c_size_t(len(nonce)),
                                                      self._state.address_of())
        if result:
            raise ValueError("Error %d instantiating a Salsa20 cipher")
        self._state = SmartPointer(self._state.get(),
                                   _raw_salsa20_lib.Salsa20_stream_destroy)

        self.block_size = 1
        self.key_size = len(key)
예제 #8
0
    def encrypt(self, plaintext, output=None):
        """Encrypt data with the key set at initialization.

        The data to encrypt can be broken up in two or
        more pieces and `encrypt` can be called multiple times.

        That is, the statement:

            >>> c.encrypt(a) + c.encrypt(b)

        is equivalent to:

             >>> c.encrypt(a+b)

        This function does not add any padding to the plaintext.

        :Parameters:
          plaintext : bytes/bytearray/memoryview
            The piece of data to encrypt.
            The length must be multiple of the cipher block length.
        :Keywords:
          output : bytearray/memoryview
            The location where the ciphertext must be written to.
            If ``None``, the ciphertext is returned.
        :Return:
          If ``output`` is ``None``, the ciphertext is returned as ``bytes``.
          Otherwise, ``None``.
        """

        if output is None:
            ciphertext = create_string_buffer(len(plaintext))
        else:
            ciphertext = output

            if not is_writeable_buffer(output):
                raise TypeError(
                    "output must be a bytearray or a writeable memoryview")

            if len(plaintext) != len(output):
                raise ValueError(
                    "output must have the same length as the input"
                    "  (%d bytes)" % len(plaintext))

        result = raw_ecb_lib.ECB_encrypt(self._state.get(),
                                         c_uint8_ptr(plaintext),
                                         c_uint8_ptr(ciphertext),
                                         c_size_t(len(plaintext)))
        if result:
            if result == 3:
                raise ValueError(
                    "Data must be aligned to block boundary in ECB mode")
            raise ValueError("Error %d while encrypting in ECB mode" % result)

        if output is None:
            return get_raw_buffer(ciphertext)
        else:
            return None
예제 #9
0
    def encrypt(self, plaintext, output=None):
        """Encrypt data with the key set at initialization.

        The data to encrypt can be broken up in two or
        more pieces and `encrypt` can be called multiple times.

        That is, the statement:

            >>> c.encrypt(a) + c.encrypt(b)

        is equivalent to:

             >>> c.encrypt(a+b)

        This function does not add any padding to the plaintext.

        :Parameters:
          plaintext : bytes/bytearray/memoryview
            The piece of data to encrypt.
            The length must be multiple of the cipher block length.
        :Keywords:
          output : bytearray/memoryview
            The location where the ciphertext must be written to.
            If ``None``, the ciphertext is returned.
        :Return:
          If ``output`` is ``None``, the ciphertext is returned as ``bytes``.
          Otherwise, ``None``.
        """

        if output is None:
            ciphertext = create_string_buffer(len(plaintext))
        else:
            ciphertext = output
            
            if not is_writeable_buffer(output):
                raise TypeError("output must be a bytearray or a writeable memoryview")
        
            if len(plaintext) != len(output):
                raise ValueError("output must have the same length as the input"
                                 "  (%d bytes)" % len(plaintext))

        result = raw_ecb_lib.ECB_encrypt(self._state.get(),
                                         c_uint8_ptr(plaintext),
                                         c_uint8_ptr(ciphertext),
                                         c_size_t(len(plaintext)))
        if result:
            if result == 3:
                raise ValueError("Data must be aligned to block boundary in ECB mode")
            raise ValueError("Error %d while encrypting in ECB mode" % result)
        
        if output is None:
            return get_raw_buffer(ciphertext)
        else:
            return None
예제 #10
0
def _pkcs1_decode(em, sentinel, expected_pt_len, output):
    if len(em) != len(output):
        raise ValueError("Incorrect output length")

    ret = _raw_pkcs1_decode.pkcs1_decode(c_uint8_ptr(em),
                                         c_size_t(len(em)),
                                         c_uint8_ptr(sentinel),
                                         c_size_t(len(sentinel)),
                                         c_size_t(expected_pt_len),
                                         c_uint8_ptr(output))
    return ret
예제 #11
0
    def xy(self):
        modulus_bytes = self.size_in_bytes()
        xb = bytearray(modulus_bytes)
        yb = bytearray(modulus_bytes)
        result = _ec_lib.ec_ws_get_xy(c_uint8_ptr(xb), c_uint8_ptr(yb),
                                      c_size_t(modulus_bytes),
                                      self._point.get())
        if result:
            raise ValueError("Error %d while encoding an EC point" % result)

        return (Integer(bytes_to_long(xb)), Integer(bytes_to_long(yb)))
예제 #12
0
def _HChaCha20(key, nonce):

    assert (len(key) == 32)
    assert (len(nonce) == 16)

    subkey = bytearray(32)
    result = _raw_chacha20_lib.hchacha20(c_uint8_ptr(key), c_uint8_ptr(nonce),
                                         c_uint8_ptr(subkey))
    if result:
        raise ValueError("Error %d when deriving subkey with HChaCha20" %
                         result)

    return subkey
예제 #13
0
def strxor(term1, term2):
    """XOR of two byte strings.
    They must have equal length.

    Return:
        A new byte string, :data:`term1` xored with :data:`term2`.
    """

    if len(term1) != len(term2):
        raise ValueError("Only byte strings of equal length can be xored")

    result = create_string_buffer(len(term1))
    _raw_strxor.strxor(c_uint8_ptr(term1), c_uint8_ptr(term2), result,
                       c_size_t(len(term1)))
    return get_raw_buffer(result)
예제 #14
0
 def _update(self, assoc_data, assoc_data_len):
     result = _raw_ocb_lib.OCB_update(self._state.get(),
                                      c_uint8_ptr(assoc_data),
                                      c_size_t(assoc_data_len))
     if result:
         raise ValueError("Error %d while computing MAC in OCB mode" %
                          result)
예제 #15
0
def _create_base_cipher(dict_parameters):
    """This method instantiates and returns a handle to a low-level
    base cipher. It will absorb named parameters in the process."""

    try:
        key = dict_parameters.pop("key")
    except KeyError:
        raise TypeError("Missing 'key' parameter")

    effective_keylen = dict_parameters.pop("effective_keylen", 1024)

    if len(key) not in key_size:
        raise ValueError("Incorrect ARC2 key length (%d bytes)" % len(key))

    if not (40 <= effective_keylen <= 1024):
        raise ValueError(
            "'effective_key_len' must be at least 40 and no larger than 1024 "
            "(not %d)" % effective_keylen)

    start_operation = _raw_arc2_lib.ARC2_start_operation
    stop_operation = _raw_arc2_lib.ARC2_stop_operation

    cipher = VoidPointer()
    result = start_operation(c_uint8_ptr(key), c_size_t(len(key)),
                             c_size_t(effective_keylen), cipher.address_of())
    if result:
        raise ValueError("Error %X while instantiating the ARC2 cipher" %
                         result)

    return SmartPointer(cipher.get(), stop_operation)
예제 #16
0
def _create_base_cipher(dict_parameters):
    """This method instantiates and returns a handle to a low-level
    base cipher. It will absorb named parameters in the process."""

    use_aesni = dict_parameters.pop("use_aesni", True)

    try:
        key = dict_parameters.pop("key")
    except KeyError:
        raise TypeError("Missing 'key' parameter")

    if len(key) not in key_size:
        raise ValueError("Incorrect AES key length (%d bytes)" % len(key))

    if use_aesni and _raw_aesni_lib:
        start_operation = _raw_aesni_lib.AESNI_start_operation
        stop_operation = _raw_aesni_lib.AESNI_stop_operation
    else:
        start_operation = _raw_aes_lib.AES_start_operation
        stop_operation = _raw_aes_lib.AES_stop_operation

    cipher = VoidPointer()
    result = start_operation(c_uint8_ptr(key), c_size_t(len(key)),
                             cipher.address_of())
    if result:
        raise ValueError("Error %X while instantiating the AES cipher" %
                         result)
    return SmartPointer(cipher.get(), stop_operation)
예제 #17
0
    def __init__(self, key, *args, **kwargs):
        """Initialize an ARC4 cipher object

        See also `new()` at the module level."""

        if len(args) > 0:
            ndrop = args[0]
            args = args[1:]
        else:
            ndrop = kwargs.pop('drop', 0)

        if len(key) not in key_size:
            raise ValueError("Incorrect ARC4 key length (%d bytes)" %
                             len(key))

        self._state = VoidPointer()
        result = _raw_arc4_lib.ARC4_stream_init(c_uint8_ptr(key),
                                                c_size_t(len(key)),
                                                self._state.address_of())
        if result != 0:
            raise ValueError("Error %d while creating the ARC4 cipher"
                             % result)
        self._state = SmartPointer(self._state.get(),
                                   _raw_arc4_lib.ARC4_stream_destroy)

        if ndrop > 0:
            # This is OK even if the cipher is used for decryption,
            # since encrypt and decrypt are actually the same thing
            # with ARC4.
            self.encrypt(b'\x00' * ndrop)

        self.block_size = 1
        self.key_size = len(key)
예제 #18
0
    def encrypt(self, plaintext):
        """Encrypt data with the key set at initialization.

        The data to encrypt can be broken up in two or
        more pieces and `encrypt` can be called multiple times.

        That is, the statement:

            >>> c.encrypt(a) + c.encrypt(b)

        is equivalent to:

             >>> c.encrypt(a+b)

        This function does not add any padding to the plaintext.

        :Parameters:
          plaintext : bytes/bytearray/memoryview
            The piece of data to encrypt.
            The length must be multiple of the cipher block length.
        :Return:
            the encrypted data, as a byte string.
            It is as long as *plaintext*.
        """

        ciphertext = create_string_buffer(len(plaintext))
        result = raw_ecb_lib.ECB_encrypt(self._state.get(),
                                         c_uint8_ptr(plaintext), ciphertext,
                                         c_size_t(len(plaintext)))
        if result:
            if result == 3:
                raise ValueError(
                    "Data must be aligned to block boundary in ECB mode")
            raise ValueError("Error %d while encrypting in ECB mode" % result)
        return get_raw_buffer(ciphertext)
예제 #19
0
    def encrypt(self, plaintext):
        """Encrypt data with the key set at initialization.

        The data to encrypt can be broken up in two or
        more pieces and `encrypt` can be called multiple times.

        That is, the statement:

            >>> c.encrypt(a) + c.encrypt(b)

        is equivalent to:

             >>> c.encrypt(a+b)

        This function does not add any padding to the plaintext.

        :Parameters:
          plaintext : bytes/bytearray/memoryview
            The piece of data to encrypt.
            The length must be multiple of the cipher block length.
        :Return:
            the encrypted data, as a byte string.
            It is as long as *plaintext*.
        """

        ciphertext = create_string_buffer(len(plaintext))
        result = raw_ecb_lib.ECB_encrypt(self._state.get(),
                                         c_uint8_ptr(plaintext),
                                         ciphertext,
                                         c_size_t(len(plaintext)))
        if result:
            if result == 3:
                raise ValueError("Data must be aligned to block boundary in ECB mode")
            raise ValueError("Error %d while encrypting in ECB mode" % result)
        return get_raw_buffer(ciphertext)
예제 #20
0
 def _update(self, data, hash_obj):
     result = _raw_keccak_lib.keccak_absorb(hash_obj.get(),
                                            c_uint8_ptr(data),
                                            c_size_t(len(data)))
     if result:
         raise ValueError("Error %d while updating KangarooTwelve state"
                          % result)
예제 #21
0
def _create_base_cipher(dict_parameters):
    """This method instantiates and returns a handle to a low-level
    base cipher. It will absorb named parameters in the process."""

    use_aesni = dict_parameters.pop("use_aesni", True)

    try:
        key = dict_parameters.pop("key")
    except KeyError:
        raise TypeError("Missing 'key' parameter")

    if len(key) not in key_size:
        raise ValueError("Incorrect AES key length (%d bytes)" % len(key))

    if use_aesni and _raw_aesni_lib:
        start_operation = _raw_aesni_lib.AESNI_start_operation
        stop_operation = _raw_aesni_lib.AESNI_stop_operation
    else:
        start_operation = _raw_aes_lib.AES_start_operation
        stop_operation = _raw_aes_lib.AES_stop_operation

    cipher = VoidPointer()
    result = start_operation(c_uint8_ptr(key),
                             c_size_t(len(key)),
                             cipher.address_of())
    if result:
        raise ValueError("Error %X while instantiating the AES cipher"
                         % result)
    return SmartPointer(cipher.get(), stop_operation)
예제 #22
0
def _create_base_cipher(dict_parameters):
    """This method instantiates and returns a handle to a low-level
    base cipher. It will absorb named parameters in the process."""

    try:
        key = dict_parameters.pop("key")
    except KeyError:
        raise TypeError("Missing 'key' parameter")

    effective_keylen = dict_parameters.pop("effective_keylen", 1024)

    if len(key) not in key_size:
        raise ValueError("Incorrect ARC2 key length (%d bytes)" % len(key))

    if not (40 < effective_keylen <= 1024):
        raise ValueError("'effective_key_len' must be no larger than 1024 "
                         "(not %d)" % effective_keylen)

    start_operation = _raw_arc2_lib.ARC2_start_operation
    stop_operation = _raw_arc2_lib.ARC2_stop_operation

    cipher = VoidPointer()
    result = start_operation(c_uint8_ptr(key),
                             c_size_t(len(key)),
                             c_size_t(effective_keylen),
                             cipher.address_of())
    if result:
        raise ValueError("Error %X while instantiating the ARC2 cipher"
                         % result)

    return SmartPointer(cipher.get(), stop_operation)
예제 #23
0
    def __init__(self, key, nonce):
        """Initialize a ChaCha20/XChaCha20 cipher object

        See also `new()` at the module level."""

        self.nonce = _copy_bytes(None, None, nonce)

        # XChaCha20 requires a key derivation with HChaCha20
        # See 2.3 in https://tools.ietf.org/html/draft-arciszewski-xchacha-03
        if len(nonce) == 24:
            key = _HChaCha20(key, nonce[:16])
            nonce = b'\x00' * 4 + nonce[16:]
            self._name = "XChaCha20"
        else:
            self._name = "ChaCha20"
            nonce = self.nonce

        self._next = ( self.encrypt, self.decrypt )

        self._state = VoidPointer()
        result = _raw_chacha20_lib.chacha20_init(
                        self._state.address_of(),
                        c_uint8_ptr(key),
                        c_size_t(len(key)),
                        nonce,
                        c_size_t(len(nonce)))
        if result:
            raise ValueError("Error %d instantiating a %s cipher" % (result,
                                                                     self._name))
        self._state = SmartPointer(self._state.get(),
                                   _raw_chacha20_lib.chacha20_destroy)
예제 #24
0
    def __init__(self, key, *args, **kwargs):
        """Initialize an ARC4 cipher object

        See also `new()` at the module level."""

        if len(args) > 0:
            ndrop = args[0]
            args = args[1:]
        else:
            ndrop = kwargs.pop('drop', 0)

        if len(key) not in key_size:
            raise ValueError("Incorrect ARC4 key length (%d bytes)" % len(key))

        self._state = VoidPointer()
        result = _raw_arc4_lib.ARC4_stream_init(c_uint8_ptr(key),
                                                c_size_t(len(key)),
                                                self._state.address_of())
        if result != 0:
            raise ValueError("Error %d while creating the ARC4 cipher" %
                             result)
        self._state = SmartPointer(self._state.get(),
                                   _raw_arc4_lib.ARC4_stream_destroy)

        if ndrop > 0:
            # This is OK even if the cipher is used for decryption,
            # since encrypt and decrypt are actually the same thing
            # with ARC4.
            self.encrypt(b'\x00' * ndrop)

        self.block_size = 1
        self.key_size = len(key)
예제 #25
0
def strxor(term1, term2):
    """XOR of two byte strings.
    They must have equal length.

    Return:
        A new byte string, :data:`term1` xored with :data:`term2`.
    """

    if len(term1) != len(term2):
        raise ValueError("Only byte strings of equal length can be xored")
    
    result = create_string_buffer(len(term1))
    _raw_strxor.strxor(c_uint8_ptr(term1),
                       c_uint8_ptr(term2),
                       result,
                       c_size_t(len(term1)))
    return get_raw_buffer(result)
예제 #26
0
    def __init__(self, block_cipher, initial_counter_block, prefix_len,
                 counter_len, little_endian):
        """Create a new block cipher, configured in CTR mode.

        :Parameters:
          block_cipher : C pointer
            A smart pointer to the low-level block cipher instance.

          initial_counter_block : bytes/bytearray/memoryview
            The initial plaintext to use to generate the key stream.

            It is as large as the cipher block, and it embeds
            the initial value of the counter.

            This value must not be reused.
            It shall contain a nonce or a random component.
            Reusing the *initial counter block* for encryptions
            performed with the same key compromises confidentiality.

          prefix_len : integer
            The amount of bytes at the beginning of the counter block
            that never change.

          counter_len : integer
            The length in bytes of the counter embedded in the counter
            block.

          little_endian : boolean
            True if the counter in the counter block is an integer encoded
            in little endian mode. If False, it is big endian.
        """

        if len(initial_counter_block) == prefix_len + counter_len:
            self.nonce = _copy_bytes(None, prefix_len, initial_counter_block)
            """Nonce; not available if there is a fixed suffix"""

        self._state = VoidPointer()
        result = raw_ctr_lib.CTR_start_operation(
            block_cipher.get(), c_uint8_ptr(initial_counter_block),
            c_size_t(len(initial_counter_block)), c_size_t(prefix_len),
            counter_len, little_endian, self._state.address_of())
        if result:
            raise ValueError("Error %X while instatiating the CTR mode" %
                             result)

        # Ensure that object disposal of this Python object will (eventually)
        # free the memory allocated by the raw library for the cipher mode
        self._state = SmartPointer(self._state.get(),
                                   raw_ctr_lib.CTR_stop_operation)

        # Memory allocated for the underlying block cipher is now owed
        # by the cipher mode
        block_cipher.release()

        self.block_size = len(initial_counter_block)
        """The block size of the underlying cipher, in bytes."""

        self._next = [self.encrypt, self.decrypt]
    def __init__(self, r, s, data):

        if len(r) != 16:
            raise ValueError("Parameter r is not 16 bytes long")
        if len(s) != 16:
            raise ValueError("Parameter s is not 16 bytes long")

        self._mac_tag = None

        state = VoidPointer()
        result = _raw_poly1305.poly1305_init(state.address_of(),
                                             c_uint8_ptr(r), c_size_t(len(r)),
                                             c_uint8_ptr(s), c_size_t(len(s)))
        if result:
            raise ValueError("Error %d while instantiating Poly1305" % result)
        self._state = SmartPointer(state.get(), _raw_poly1305.poly1305_destroy)
        if data:
            self.update(data)
예제 #28
0
    def update(self, block_data):
        assert len(block_data) % 16 == 0

        result = self.ghash_c.ghash(self._last_y, c_uint8_ptr(block_data),
                                    c_size_t(len(block_data)), self._last_y,
                                    self._exp_key.get())
        if result:
            raise ValueError("Error %d while updating GHASH" % result)

        return self
예제 #29
0
def strxor_c(term, c, output=None):
    """XOR a byte string with a repeated sequence of characters.

    Args:
        term(bytes/bytearray/memoryview):
            The first term of the XOR operation.
        c (bytes):
            The byte that makes up the second term of the XOR operation.
        output (None or bytearray/memoryview):
            If not ``None``, the location where the result is stored into.

    Return:
        If ``output`` is ``None``, a new ``bytes`` string with the result.
        Otherwise ``None``.
    """

    if not 0 <= c < 256:
        raise ValueError("c must be in range(256)")
    
    if output is None:
        result = create_string_buffer(len(term))
    else:
        # Note: output may overlap with either input
        result = output
        
        if _is_immutable(output):
            raise TypeError("output must be a bytearray or a writeable memoryview")
        
        if len(term) != len(output):
            raise ValueError("output must have the same length as the input"
                             "  (%d bytes)" % len(term))

    _raw_strxor.strxor_c(c_uint8_ptr(term),
                         c,
                         c_uint8_ptr(result),
                         c_size_t(len(term))
                         )

    if output is None:
        return get_raw_buffer(result)
    else:
        return None
예제 #30
0
def strxor_c(term, c, output=None):
    """XOR a byte string with a repeated sequence of characters.

    Args:
        term(bytes/bytearray/memoryview):
            The first term of the XOR operation.
        c (bytes):
            The byte that makes up the second term of the XOR operation.
        output (None or bytearray/memoryview):
            If not ``None``, the location where the result is stored into.

    Return:
        If ``output`` is ``None``, a new ``bytes`` string with the result.
        Otherwise ``None``.
    """

    if not 0 <= c < 256:
        raise ValueError("c must be in range(256)")
    
    if output is None:
        result = create_string_buffer(len(term))
    else:
        # Note: output may overlap with either input
        result = output
       
        if not is_writeable_buffer(output):
            raise TypeError("output must be a bytearray or a writeable memoryview")
        
        if len(term) != len(output):
            raise ValueError("output must have the same length as the input"
                             "  (%d bytes)" % len(term))

    _raw_strxor.strxor_c(c_uint8_ptr(term),
                         c,
                         c_uint8_ptr(result),
                         c_size_t(len(term))
                         )

    if output is None:
        return get_raw_buffer(result)
    else:
        return None
예제 #31
0
    def update(self, data):
        """Continue hashing of a message by consuming the next chunk of data.

        Args:
            data (byte string/byte array/memoryview): The next chunk of the message being hashed.
        """

        result = _raw_md5_lib.MD5_update(self._state.get(), c_uint8_ptr(data),
                                         c_size_t(len(data)))
        if result:
            raise ValueError("Error %d while instantiating MD5" % result)
예제 #32
0
    def update(self, data):

        if self._mac_tag:
            raise TypeError("You can only call 'digest' or 'hexdigest' on this object")

        result = _raw_poly1305.poly1305_update(self._state.get(),
                                               c_uint8_ptr(data),
                                               c_size_t(len(data)))
        if result:
            raise ValueError("Error %d while hashing Poly1305 data" % result)
        return self
예제 #33
0
def strxor(term1, term2, output=None):
    """XOR two byte strings.
    
    Args:
      term1 (bytes/bytearray/memoryview):
        The first term of the XOR operation.
      term2 (bytes/bytearray/memoryview):
        The second term of the XOR operation.
      output (bytearray/memoryview):
        The location where the result must be written to.
        If ``None``, the result is returned.
    :Return:
        If ``output`` is ``None``, a new ``bytes`` string with the result.
        Otherwise ``None``.
    """

    if len(term1) != len(term2):
        raise ValueError("Only byte strings of equal length can be xored")
    
    if output is None:
        result = create_string_buffer(len(term1))
    else:
        # Note: output may overlap with either input
        result = output
        
        if _is_immutable(output):
            raise TypeError("output must be a bytearray or a writeable memoryview")
        
        if len(term1) != len(output):
            raise ValueError("output must have the same length as the input"
                             "  (%d bytes)" % len(term1))

    _raw_strxor.strxor(c_uint8_ptr(term1),
                       c_uint8_ptr(term2),
                       c_uint8_ptr(result),
                       c_size_t(len(term1)))

    if output is None:
        return get_raw_buffer(result)
    else:
        return None
예제 #34
0
def strxor(term1, term2, output=None):
    """XOR two byte strings.
    
    Args:
      term1 (bytes/bytearray/memoryview):
        The first term of the XOR operation.
      term2 (bytes/bytearray/memoryview):
        The second term of the XOR operation.
      output (bytearray/memoryview):
        The location where the result must be written to.
        If ``None``, the result is returned.
    :Return:
        If ``output`` is ``None``, a new ``bytes`` string with the result.
        Otherwise ``None``.
    """

    if len(term1) != len(term2):
        raise ValueError("Only byte strings of equal length can be xored")
    
    if output is None:
        result = create_string_buffer(len(term1))
    else:
        # Note: output may overlap with either input
        result = output
        
        if not is_writeable_buffer(output):
            raise TypeError("output must be a bytearray or a writeable memoryview")
        
        if len(term1) != len(output):
            raise ValueError("output must have the same length as the input"
                             "  (%d bytes)" % len(term1))

    _raw_strxor.strxor(c_uint8_ptr(term1),
                       c_uint8_ptr(term2),
                       c_uint8_ptr(result),
                       c_size_t(len(term1)))

    if output is None:
        return get_raw_buffer(result)
    else:
        return None
예제 #35
0
    def _encrypt(self, plaintext):
        """Encrypt without FSM checks"""

        ciphertext = create_string_buffer(len(plaintext))
        result = _raw_chacha20_lib.chacha20_encrypt(
                                         self._state.get(),
                                         c_uint8_ptr(plaintext),
                                         ciphertext,
                                         c_size_t(len(plaintext)))
        if result:
            raise ValueError("Error %d while encrypting with ChaCha20" % result)
        return get_raw_buffer(ciphertext)
예제 #36
0
    def update(self, block_data):
        assert len(block_data) % 16 == 0

        result = self.ghash_c.ghash(self._last_y,
                                    c_uint8_ptr(block_data),
                                    c_size_t(len(block_data)),
                                    self._last_y,
                                    self._exp_key.get())
        if result:
            raise ValueError("Error %d while updating GHASH" % result)

        return self
예제 #37
0
def strxor_c(term, c):
    """XOR of a byte string with a repeated sequence of characters.

    Return:
        A new byte string, :data:`term` with all its bytes xored with :data:`c`.
    """

    if not 0 <= c < 256:
        raise ValueError("c must be in range(256)")
    result = create_string_buffer(len(term))
    _raw_strxor.strxor_c(c_uint8_ptr(term), c, result, c_size_t(len(term)))
    return get_raw_buffer(result)
예제 #38
0
    def update(self, data):

        if self._mac_tag:
            raise TypeError(
                "You can only call 'digest' or 'hexdigest' on this object")

        result = _raw_poly1305.poly1305_update(self._state.get(),
                                               c_uint8_ptr(data),
                                               c_size_t(len(data)))
        if result:
            raise ValueError("Error %d while hashing Poly1305 data" % result)
        return self
예제 #39
0
    def _encrypt(self, plaintext):
        """Encrypt without FSM checks"""

        ciphertext = create_string_buffer(len(plaintext))
        result = _raw_chacha20_lib.chacha20_encrypt(
                                         self._state.get(),
                                         c_uint8_ptr(plaintext),
                                         ciphertext,
                                         c_size_t(len(plaintext)))
        if result:
            raise ValueError("Error %d while encrypting with ChaCha20" % result)
        return get_raw_buffer(ciphertext)
예제 #40
0
def strxor_c(term, c):
    """XOR of a byte string with a repeated sequence of characters.

    Return:
        A new byte string, :data:`term` with all its bytes xored with :data:`c`.
    """

    if not 0 <= c < 256:
        raise ValueError("c must be in range(256)")
    result = create_string_buffer(len(term))
    _raw_strxor.strxor_c(c_uint8_ptr(term), c, result, c_size_t(len(term)))
    return get_raw_buffer(result)
예제 #41
0
    def update(self, data):
        """Continue hashing of a message by consuming the next chunk of data.

        Args:
            data (byte string/array): The next chunk of the message being hashed.
        """

        result = _raw_sha384_lib.SHA384_update(self._state.get(),
                                               c_uint8_ptr(data),
                                               c_size_t(len(data)))
        if result:
            raise ValueError("Error %d while instantiating SHA384" % result)
예제 #42
0
    def __imul__(self, scalar):
        """Multiply this point by a scalar"""

        if scalar < 0:
            raise ValueError("Scalar multiplication is only defined for non-negative integers")
        sb = long_to_bytes(scalar)
        result = _ec_lib.ec_ws_scalar(self._point.get(),
                                      c_uint8_ptr(sb),
                                      c_size_t(len(sb)),
                                      c_ulonglong(getrandbits(64)))
        if result:
            raise ValueError("Error %d during scalar multiplication" % result)
        return self
예제 #43
0
    def __init__(self, r, s, data):

        if len(r) != 16:
            raise ValueError("Paramater r is not 16 bytes long")
        if len(s) != 16:
            raise ValueError("Parameter s is not 16 bytes long")

        self._mac_tag = None

        state = VoidPointer()
        result = _raw_poly1305.poly1305_init(state.address_of(),
                                             c_uint8_ptr(r),
                                             c_size_t(len(r)),
                                             c_uint8_ptr(s),
                                             c_size_t(len(s))
                                             )
        if result:
            raise ValueError("Error %d while instantiating Poly1305" % result)
        self._state = SmartPointer(state.get(),
                                   _raw_poly1305.poly1305_destroy)
        if data:
            self.update(data)
예제 #44
0
    def update(self, data):
        """Continue hashing of a message by consuming the next chunk of data.

        Args:
            data (byte string/byte array/memoryview): The next chunk of the message being hashed.
        """

        result = _raw_sha256_lib.SHA256_update(self._state.get(),
                                               c_uint8_ptr(data),
                                               c_size_t(len(data)))
        if result:
            raise ValueError("Error %d while hashing data with SHA256"
                             % result)
예제 #45
0
    def __init__(self, subkey):
        assert len(subkey) == 16

        self._exp_key = VoidPointer()
        result = _raw_galois_lib.ghash_expand(c_uint8_ptr(subkey),
                                              self._exp_key.address_of())
        if result:
            raise ValueError("Error %d while expanding the GMAC key" % result)

        self._exp_key = SmartPointer(self._exp_key.get(),
                                     _raw_galois_lib.ghash_destroy)

        # create_string_buffer always returns a string of zeroes
        self._last_y = create_string_buffer(16)
예제 #46
0
    def __init__(self, block_cipher, iv, segment_size):
        """Create a new block cipher, configured in CFB mode.

        :Parameters:
          block_cipher : C pointer
            A smart pointer to the low-level block cipher instance.

          iv : bytes/bytearray/memoryview
            The initialization vector to use for encryption or decryption.
            It is as long as the cipher block.

            **The IV must be unpredictable**. Ideally it is picked randomly.

            Reusing the *IV* for encryptions performed with the same key
            compromises confidentiality.

          segment_size : integer
            The number of bytes the plaintext and ciphertext are segmented in.
        """

        self._state = VoidPointer()
        result = raw_cfb_lib.CFB_start_operation(block_cipher.get(),
                                                 c_uint8_ptr(iv),
                                                 c_size_t(len(iv)),
                                                 c_size_t(segment_size),
                                                 self._state.address_of())
        if result:
            raise ValueError("Error %d while instatiating the CFB mode" %
                             result)

        # Ensure that object disposal of this Python object will (eventually)
        # free the memory allocated by the raw library for the cipher mode
        self._state = SmartPointer(self._state.get(),
                                   raw_cfb_lib.CFB_stop_operation)

        # Memory allocated for the underlying block cipher is now owed
        # by the cipher mode
        block_cipher.release()

        self.block_size = len(iv)
        """The block size of the underlying cipher, in bytes."""

        self.iv = _copy_bytes(None, None, iv)
        """The Initialization Vector originally used to create the object.
        The value does not change."""

        self.IV = self.iv
        """Alias for `iv`"""

        self._next = [self.encrypt, self.decrypt]
예제 #47
0
    def encrypt(self, plaintext, output=None):
        """Encrypt a piece of data.

        Args:
          plaintext(bytes/bytearray/memoryview): The data to encrypt, of any size.
        Keyword Args:
          output(bytes/bytearray/memoryview): The location where the ciphertext
            is written to. If ``None``, the ciphertext is returned.
        Returns:
          If ``output`` is ``None``, the ciphertext is returned as ``bytes``.
          Otherwise, ``None``.
        """
        
        if output is None:
            ciphertext = create_string_buffer(len(plaintext))
        else:
            ciphertext = output
           
            if not is_writeable_buffer(output):
                raise TypeError("output must be a bytearray or a writeable memoryview")
        
            if len(plaintext) != len(output):
                raise ValueError("output must have the same length as the input"
                                 "  (%d bytes)" % len(plaintext))

        result = _raw_salsa20_lib.Salsa20_stream_encrypt(
                                         self._state.get(),
                                         c_uint8_ptr(plaintext),
                                         c_uint8_ptr(ciphertext),
                                         c_size_t(len(plaintext)))
        if result:
            raise ValueError("Error %d while encrypting with Salsa20" % result)

        if output is None:
            return get_raw_buffer(ciphertext)
        else:
            return None
예제 #48
0
    def __init__(self, block_cipher, iv, segment_size):
        """Create a new block cipher, configured in CFB mode.

        :Parameters:
          block_cipher : C pointer
            A smart pointer to the low-level block cipher instance.

          iv : bytes/bytearray/memoryview
            The initialization vector to use for encryption or decryption.
            It is as long as the cipher block.

            **The IV must be unpredictable**. Ideally it is picked randomly.

            Reusing the *IV* for encryptions performed with the same key
            compromises confidentiality.

          segment_size : integer
            The number of bytes the plaintext and ciphertext are segmented in.
        """

        self._state = VoidPointer()
        result = raw_cfb_lib.CFB_start_operation(block_cipher.get(),
                                                 c_uint8_ptr(iv),
                                                 c_size_t(len(iv)),
                                                 c_size_t(segment_size),
                                                 self._state.address_of())
        if result:
            raise ValueError("Error %d while instatiating the CFB mode" % result)

        # Ensure that object disposal of this Python object will (eventually)
        # free the memory allocated by the raw library for the cipher mode
        self._state = SmartPointer(self._state.get(),
                                   raw_cfb_lib.CFB_stop_operation)

        # Memory allocated for the underlying block cipher is now owed
        # by the cipher mode
        block_cipher.release()

        self.block_size = len(iv)
        """The block size of the underlying cipher, in bytes."""

        self.iv = _copy_bytes(None, None, iv)
        """The Initialization Vector originally used to create the object.
        The value does not change."""

        self.IV = self.iv
        """Alias for `iv`"""

        self._next = [ self.encrypt, self.decrypt ]
예제 #49
0
    def update(self, data):
        """Continue hashing of a message by consuming the next chunk of data.

        Args:
            data (byte string/byte array/memoryview): The next chunk of the message being hashed.
        """

        if self._digest_done and not self._update_after_digest:
            raise TypeError("You can only call 'digest' or 'hexdigest' on this object")

        result = _raw_keccak_lib.keccak_absorb(self._state.get(),
                                               c_uint8_ptr(data),
                                               c_size_t(len(data)))
        if result:
            raise ValueError("Error %d while updating keccak" % result)
        return self
예제 #50
0
    def __init__(self, subkey, ghash_c):
        assert len(subkey) == 16

        self.ghash_c = ghash_c

        self._exp_key = VoidPointer()
        result = ghash_c.ghash_expand(c_uint8_ptr(subkey),
                                      self._exp_key.address_of())
        if result:
            raise ValueError("Error %d while expanding the GHASH key" % result)

        self._exp_key = SmartPointer(self._exp_key.get(),
                                     ghash_c.ghash_destroy)

        # create_string_buffer always returns a string of zeroes
        self._last_y = create_string_buffer(16)
예제 #51
0
    def update(self, data):
        """Continue hashing of a message by consuming the next chunk of data.

        Args:
            data (byte string/byte array/memoryview): The next chunk of the message being hashed.
        """

        if self._is_squeezing:
            raise TypeError("You cannot call 'update' after the first 'read'")

        result = _raw_keccak_lib.keccak_absorb(self._state.get(),
                                               c_uint8_ptr(data),
                                               c_size_t(len(data)))
        if result:
            raise ValueError("Error %d while updating SHAKE128 state"
                             % result)
        return self
예제 #52
0
    def encrypt(self, plaintext):
        """Encrypt a piece of data.

        :param plaintext: The data to encrypt, of any size.
        :type plaintext: bytes, bytearray, memoryview
        :returns: the encrypted byte string, of equal length as the
          plaintext.
        """

        ciphertext = create_string_buffer(len(plaintext))
        result = _raw_arc4_lib.ARC4_stream_encrypt(self._state.get(),
                                                   c_uint8_ptr(plaintext),
                                                   ciphertext,
                                                   c_size_t(len(plaintext)))
        if result:
            raise ValueError("Error %d while encrypting with RC4" % result)
        return get_raw_buffer(ciphertext)
예제 #53
0
    def encrypt(self, plaintext):
        """Encrypt data with the key and the parameters set at initialization.

        A cipher object is stateful: once you have encrypted a message
        you cannot encrypt (or decrypt) another message using the same
        object.

        The data to encrypt can be broken up in two or
        more pieces and `encrypt` can be called multiple times.

        That is, the statement:

            >>> c.encrypt(a) + c.encrypt(b)

        is equivalent to:

             >>> c.encrypt(a+b)

        This function does not add any padding to the plaintext.

        :Parameters:
          plaintext : bytes/bytearray/memoryview
            The piece of data to encrypt.
            It can be of any length.
        :Return:
            the encrypted data, as a byte string.
            It is as long as *plaintext*.
        """

        if self.encrypt not in self._next:
            raise TypeError("encrypt() cannot be called after decrypt()")
        self._next = [self.encrypt]

        ciphertext = create_string_buffer(len(plaintext))
        result = raw_ctr_lib.CTR_encrypt(self._state.get(),
                                         c_uint8_ptr(plaintext),
                                         ciphertext,
                                         c_size_t(len(plaintext)))
        if result:
            if result == 0x60002:
                raise OverflowError("The counter has wrapped around in"
                                    " CTR mode")
            raise ValueError("Error %X while encrypting in CTR mode" % result)
        return get_raw_buffer(ciphertext)
예제 #54
0
    def __init__(self, key, nonce):
        """Initialize a ChaCha20 cipher object

        See also `new()` at the module level."""

        self.nonce = _copy_bytes(None, None, nonce)

        self._next = ( self.encrypt, self.decrypt )
        self._state = VoidPointer()
        result = _raw_chacha20_lib.chacha20_init(
                        self._state.address_of(),
                        c_uint8_ptr(key),
                        c_size_t(len(key)),
                        self.nonce,
                        c_size_t(len(nonce)))
        if result:
            raise ValueError("Error %d instantiating a ChaCha20 cipher")
        self._state = SmartPointer(self._state.get(),
                                   _raw_chacha20_lib.chacha20_destroy)
예제 #55
0
    def _transcrypt(self, in_data, trans_func, trans_desc):
        # Last piece to encrypt/decrypt
        if in_data is None:
            out_data = self._transcrypt_aligned(self._cache_P,
                                                len(self._cache_P),
                                                trans_func,
                                                trans_desc)
            self._cache_P = b""
            return out_data

        # Try to fill up the cache, if it already contains something
        prefix = b""
        if len(self._cache_P) > 0:
            filler = min(16 - len(self._cache_P), len(in_data))
            self._cache_P += _copy_bytes(None, filler, in_data)
            in_data = in_data[filler:]

            if len(self._cache_P) < 16:
                # We could not manage to fill the cache, so there is certainly
                # no output yet.
                return b""

            # Clear the cache, and proceeding with any other aligned data
            prefix = self._transcrypt_aligned(self._cache_P,
                                              len(self._cache_P),
                                              trans_func,
                                              trans_desc)
            self._cache_P = b""

        # Process data in multiples of the block size
        trans_len = len(in_data) // 16 * 16
        result = self._transcrypt_aligned(c_uint8_ptr(in_data),
                                          trans_len,
                                          trans_func,
                                          trans_desc)
        if prefix:
            result = prefix + result

        # Left-over
        self._cache_P = _copy_bytes(trans_len, None, in_data)

        return result
예제 #56
0
    def decrypt(self, ciphertext):
        """Decrypt data with the key and the parameters set at initialization.

        A cipher object is stateful: once you have decrypted a message
        you cannot decrypt (or encrypt) another message with the same
        object.

        The data to decrypt can be broken up in two or
        more pieces and `decrypt` can be called multiple times.

        That is, the statement:

            >>> c.decrypt(a) + c.decrypt(b)

        is equivalent to:

             >>> c.decrypt(a+b)

        This function does not remove any padding from the plaintext.

        :Parameters:
          ciphertext : bytes/bytearray/memoryview
            The piece of data to decrypt.
            It can be of any length.

        :Return: the decrypted data (byte string).
        """

        if self.decrypt not in self._next:
            raise TypeError("decrypt() cannot be called after encrypt()")
        self._next = [ self.decrypt ]

        plaintext = create_string_buffer(len(ciphertext))
        result = raw_ofb_lib.OFB_decrypt(self._state.get(),
                                         c_uint8_ptr(ciphertext),
                                         plaintext,
                                         c_size_t(len(ciphertext)))
        if result:
            raise ValueError("Error %d while decrypting in OFB mode" % result)
        return get_raw_buffer(plaintext)
예제 #57
0
    def update(self, data):
        """Continue hashing of a message by consuming the next chunk of data.

        Repeated calls are equivalent to a single call with the concatenation
        of all the arguments. In other words:

           >>> m.update(a); m.update(b)

        is equivalent to:

           >>> m.update(a+b)

        :Parameters:
          data : byte string/byte array/memoryview
            The next chunk of the message being hashed.
        """

        result = _raw_md4_lib.md4_update(self._state.get(),
                                         c_uint8_ptr(data),
                                         c_size_t(len(data)))
        if result:
            raise ValueError("Error %d while instantiating MD4"
                             % result)
예제 #58
0
def _create_base_cipher(dict_parameters):
    """This method instantiates and returns a smart pointer to
    a low-level base cipher. It will absorb named parameters in
    the process."""

    try:
        key = dict_parameters.pop("key")
    except KeyError:
        raise TypeError("Missing 'key' parameter")

    if len(key) not in key_size:
        raise ValueError("Incorrect Blowfish key length (%d bytes)" % len(key))

    start_operation = _raw_blowfish_lib.Blowfish_start_operation
    stop_operation = _raw_blowfish_lib.Blowfish_stop_operation

    void_p = VoidPointer()
    result = start_operation(c_uint8_ptr(key),
                             c_size_t(len(key)),
                             void_p.address_of())
    if result:
        raise ValueError("Error %X while instantiating the Blowfish cipher"
                         % result)
    return SmartPointer(void_p.get(), stop_operation)
예제 #59
0
    def __init__(self, data, key, digest_bytes, update_after_digest):

        # The size of the resulting hash in bytes.
        self.digest_size = digest_bytes

        self._update_after_digest = update_after_digest
        self._digest_done = False

        # See https://tools.ietf.org/html/rfc7693
        if digest_bytes in (16, 20, 28, 32) and not key:
            self.oid = "1.3.6.1.4.1.1722.12.2.2." + str(digest_bytes)

        state = VoidPointer()
        result = _raw_blake2s_lib.blake2s_init(state.address_of(),
                                               c_uint8_ptr(key),
                                               c_size_t(len(key)),
                                               c_size_t(digest_bytes)
                                               )
        if result:
            raise ValueError("Error %d while instantiating BLAKE2s" % result)
        self._state = SmartPointer(state.get(),
                                   _raw_blake2s_lib.blake2s_destroy)
        if data:
            self.update(data)
예제 #60
0
    def __init__(self, block_cipher, initial_counter_block,
                 prefix_len, counter_len, little_endian):
        """Create a new block cipher, configured in CTR mode.

        :Parameters:
          block_cipher : C pointer
            A smart pointer to the low-level block cipher instance.

          initial_counter_block : bytes/bytearray/memoryview
            The initial plaintext to use to generate the key stream.

            It is as large as the cipher block, and it embeds
            the initial value of the counter.

            This value must not be reused.
            It shall contain a nonce or a random component.
            Reusing the *initial counter block* for encryptions
            performed with the same key compromises confidentiality.

          prefix_len : integer
            The amount of bytes at the beginning of the counter block
            that never change.

          counter_len : integer
            The length in bytes of the counter embedded in the counter
            block.

          little_endian : boolean
            True if the counter in the counter block is an integer encoded
            in little endian mode. If False, it is big endian.
        """

        if len(initial_counter_block) == prefix_len + counter_len:
            self.nonce = _copy_bytes(None, prefix_len, initial_counter_block)
            """Nonce; not available if there is a fixed suffix"""

        self._state = VoidPointer()
        result = raw_ctr_lib.CTR_start_operation(block_cipher.get(),
                                                 c_uint8_ptr(initial_counter_block),
                                                 c_size_t(len(initial_counter_block)),
                                                 c_size_t(prefix_len),
                                                 counter_len,
                                                 little_endian,
                                                 self._state.address_of())
        if result:
            raise ValueError("Error %X while instatiating the CTR mode"
                             % result)

        # Ensure that object disposal of this Python object will (eventually)
        # free the memory allocated by the raw library for the cipher mode
        self._state = SmartPointer(self._state.get(),
                                   raw_ctr_lib.CTR_stop_operation)

        # Memory allocated for the underlying block cipher is now owed
        # by the cipher mode
        block_cipher.release()

        self.block_size = len(initial_counter_block)
        """The block size of the underlying cipher, in bytes."""

        self._next = [self.encrypt, self.decrypt]