コード例 #1
0
    def read(self, length):
        """
        Compute the next piece of XOF output.

        .. note::
            You cannot use :meth:`update` anymore after the first call to
            :meth:`read`.

        Args:
            length (integer): the amount of bytes this method must return

        :return: the next piece of XOF output (of the given length)
        :rtype: byte string
        """

        self._is_squeezing = True
        bfr = create_string_buffer(length)
        result = _raw_keccak_lib.keccak_squeeze(self._state.get(),
                                                bfr,
                                                c_size_t(length),
                                                c_ubyte(self._padding))
        if result:
            raise ValueError("Error %d while extracting from SHAKE128"
                             % result)

        return get_raw_buffer(bfr)
コード例 #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
コード例 #3
0
ファイル: SHAKE128.py プロジェクト: chevah/python-package
    def read(self, length):
        """
        Compute the next piece of XOF output.

        .. note::
            You cannot use :meth:`update` anymore after the first call to
            :meth:`read`.

        Args:
            length (integer): the amount of bytes this method must return

        :return: the next piece of XOF output (of the given length)
        :rtype: byte string
        """

        self._is_squeezing = True
        bfr = create_string_buffer(length)
        result = _raw_keccak_lib.keccak_squeeze(self._state.get(),
                                                bfr,
                                                c_size_t(length))
        if result:
            raise ValueError("Error %d while extracting from SHAKE128"
                             % result)

        return get_raw_buffer(bfr)
コード例 #4
0
ファイル: _mode_ecb.py プロジェクト: chevah/python-package
    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)
コード例 #5
0
ファイル: _mode_cfb.py プロジェクト: fhl2546374141/dailyfresh
    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 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 : byte string
            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*.
        """

        expect_byte_string(plaintext)
        ciphertext = create_string_buffer(len(plaintext))
        result = raw_ecb_lib.ECB_encrypt(self._state.get(), plaintext,
                                         ciphertext, c_size_t(len(plaintext)))
        if result:
            raise ValueError("Error %d while encrypting in ECB mode" % result)
        return get_raw_buffer(ciphertext)
コード例 #7
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
コード例 #8
0
    def decrypt(self, ciphertext):
        """Decrypt data with the key set at initialization.

        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 : byte string
            The piece of data to decrypt.
            The length must be multiple of the cipher block length.

        :Return:
            the decrypted data (byte string).
            It is as long as *ciphertext*.
        """

        expect_byte_string(ciphertext)
        plaintext = create_string_buffer(len(ciphertext))
        result = raw_ecb_lib.ECB_decrypt(self._state.get(),
                                         ciphertext,
                                         plaintext,
                                         c_size_t(len(ciphertext)))
        if result:
            raise ValueError("Error %d while decrypting in ECB mode" % result)
        return get_raw_buffer(plaintext)
コード例 #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 strxor_c(term, c):
    """Return term xored with a sequence of characters c."""

    expect_byte_string(term)
    if not 0 <= c < 256:
        raise ValueError("c must be in range(256)")
    result = create_string_buffer(len(term))
    _raw_strxor.strxor_c(term, c, result, c_size_t(len(term)))
    return get_raw_buffer(result)
コード例 #11
0
    def _transcrypt_aligned(self, in_data, in_data_len, trans_func,
                            trans_desc):

        out_data = create_string_buffer(in_data_len)
        result = trans_func(self._state.get(), in_data, out_data,
                            c_size_t(in_data_len))
        if result:
            raise ValueError("Error %d while %sing in OCB mode" %
                             (result, trans_desc))
        return get_raw_buffer(out_data)
コード例 #12
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
コード例 #13
0
    def _squeeze(self, hash_obj, length, padding):
        bfr = create_string_buffer(length)
        result = _raw_keccak_lib.keccak_squeeze(hash_obj.get(),
                                                bfr,
                                                c_size_t(length),
                                                c_ubyte(padding))
        if result:
            raise ValueError("Error %d while extracting from KangarooTwelve"
                             % result)

        return get_raw_buffer(bfr)
コード例 #14
0
def strxor(term1, term2):
    """Return term1 xored with term2.
    The two byte strings must have equal length."""

    expect_byte_string(term1)
    expect_byte_string(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(term1, term2, result, c_size_t(len(term1)))
    return get_raw_buffer(result)
コード例 #15
0
ファイル: ChaCha20.py プロジェクト: chevah/python-package
    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)
コード例 #16
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)
コード例 #17
0
ファイル: strxor.py プロジェクト: hhao020/interface-test
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)
コード例 #18
0
    def _transcrypt_aligned(self, in_data, in_data_len,
                            trans_func, trans_desc):

        out_data = create_string_buffer(in_data_len)
        result = trans_func(self._state.get(),
                            in_data,
                            out_data,
                            c_size_t(in_data_len))
        if result:
            raise ValueError("Error %d while %sing in OCB mode"
                             % (result, trans_desc))
        return get_raw_buffer(out_data)
コード例 #19
0
ファイル: strxor.py プロジェクト: chevah/python-package
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)
コード例 #20
0
ファイル: Poly1305.py プロジェクト: 2216288075/meiduo_project
    def digest(self):

        if self._mac_tag:
            return self._mac_tag
        
        bfr = create_string_buffer(16)
        result = _raw_poly1305.poly1305_digest(self._state.get(),
                                               bfr,
                                               c_size_t(len(bfr)))
        if result:
            raise ValueError("Error %d while creating Poly1305 digest" % result)

        self._mac_tag = get_raw_buffer(bfr)
        return self._mac_tag
コード例 #21
0
    def digest(self):
        """Return the **binary** (non-printable) digest of the message that has been hashed so far.

        :return: The hash digest, computed over the data processed so far.
                 Binary form.
        :rtype: byte string
        """

        bfr = create_string_buffer(self.digest_size)
        result = _raw_ripemd160_lib.ripemd160_digest(self._state.get(), bfr)
        if result:
            raise ValueError("Error %d while instantiating ripemd160" % result)

        return get_raw_buffer(bfr)
コード例 #22
0
ファイル: Poly1305.py プロジェクト: fhl2546374141/dailyfresh
    def digest(self):

        if self._mac_tag:
            return self._mac_tag

        bfr = create_string_buffer(16)
        result = _raw_poly1305.poly1305_digest(self._state.get(), bfr,
                                               c_size_t(len(bfr)))
        if result:
            raise ValueError("Error %d while creating Poly1305 digest" %
                             result)

        self._mac_tag = get_raw_buffer(bfr)
        return self._mac_tag
コード例 #23
0
def _scryptROMix(blocks, n):
    """Sequential memory-hard function for scrypt."""

    x = [blocks[i:i + 64] for i in xrange(0, len(blocks), 64)]
    len_x = len(x)
    v = [None] * n
    load_le_uint32 = _raw_salsa20_lib.load_le_uint32
    for i in xrange(n):
        v[i] = x
        x = _scryptBlockMix(x, len_x)
    for i in xrange(n):
        j = load_le_uint32(x[-1]) & (n - 1)
        t = [strxor(x[idx], v[j][idx]) for idx in xrange(len_x)]
        x = _scryptBlockMix(t, len_x)
    return b("").join([get_raw_buffer(y) for y in x])
コード例 #24
0
ファイル: strxor.py プロジェクト: hhao020/interface-test
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)
コード例 #25
0
def _pbkdf2_hmac_assist(inner, outer, first_digest, iterations):
    """Compute the expensive inner loop in PBKDF-HMAC."""

    assert iterations > 0

    bfr = create_string_buffer(len(first_digest))
    result = _raw_sha384_lib.SHA384_pbkdf2_hmac_assist(
        inner._state.get(), outer._state.get(), first_digest, bfr,
        c_size_t(iterations), c_size_t(len(first_digest)))

    if result:
        raise ValueError("Error %d with PBKDF2-HMAC assist for SHA384" %
                         result)

    return get_raw_buffer(bfr)
コード例 #26
0
def _scryptROMix(blocks, n):
    """Sequential memory-hard function for scrypt."""

    x = [blocks[i:i + 64] for i in xrange(0, len(blocks), 64)]
    len_x = len(x)
    v = [None]*n
    load_le_uint32 = _raw_salsa20_lib.load_le_uint32
    for i in xrange(n):
        v[i] = x
        x = _scryptBlockMix(x, len_x)
    for i in xrange(n):
        j = load_le_uint32(x[-1]) & (n - 1)
        t = [strxor(x[idx], v[j][idx]) for idx in xrange(len_x)]
        x = _scryptBlockMix(t, len_x)
    return b("").join([get_raw_buffer(y) for y in x])
コード例 #27
0
    def digest(self):
        """Return the **binary** (non-printable) digest of the message that has been hashed so far.

        :return: The hash digest, computed over the data processed so far.
                 Binary form.
        :rtype: byte string
        """

        bfr = create_string_buffer(self.digest_size)
        result = _raw_sha384_lib.SHA384_digest(self._state.get(), bfr,
                                               c_size_t(self.digest_size))
        if result:
            raise ValueError("Error %d while making SHA384 digest" % result)

        return get_raw_buffer(bfr)
コード例 #28
0
    def encrypt(self, plaintext):
        """Encrypt a piece of data.

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

        ciphertext = create_string_buffer(len(plaintext))
        result = _raw_salsa20_lib.Salsa20_stream_encrypt(
            self._state.get(), c_uint8_ptr(plaintext), ciphertext,
            c_size_t(len(plaintext)))
        if result:
            raise ValueError("Error %d while encrypting with Salsa20" % result)
        return get_raw_buffer(ciphertext)
コード例 #29
0
    def digest(self):
        """Return the **binary** (non-printable) digest of the message that has been hashed so far.

        :return: The hash digest, computed over the data processed so far.
                 Binary form.
        :rtype: byte string
        """

        bfr = create_string_buffer(32)
        result = _raw_blake2s_lib.blake2s_digest(self._state.get(), bfr)
        if result:
            raise ValueError("Error %d while creating BLAKE2s digest" % result)

        self._digest_done = True

        return get_raw_buffer(bfr)[:self.digest_size]
コード例 #30
0
ファイル: MD2.py プロジェクト: chevah/python-package
    def digest(self):
        """Return the **binary** (non-printable) digest of the message that has been hashed so far.

        :return: The hash digest, computed over the data processed so far.
                 Binary form.
        :rtype: byte string
        """

        bfr = create_string_buffer(self.digest_size)
        result = _raw_md2_lib.md2_digest(self._state.get(),
                                         bfr)
        if result:
            raise ValueError("Error %d while instantiating MD2"
                             % result)

        return get_raw_buffer(bfr)
コード例 #31
0
    def _compute_mac_tag(self):

        if self._mac_tag is not None:
            return

        if self._cache_A:
            self._update(self._cache_A, len(self._cache_A))
            self._cache_A = b""

        mac_tag = create_string_buffer(16)
        result = _raw_ocb_lib.OCB_digest(self._state.get(), mac_tag,
                                         c_size_t(len(mac_tag)))
        if result:
            raise ValueError("Error %d while computing digest in OCB mode" %
                             result)
        self._mac_tag = get_raw_buffer(mac_tag)[:self._mac_len]
コード例 #32
0
    def digest(self):
        """Return the **binary** (non-printable) digest of the message that has been hashed so far.

        :return: The hash digest, computed over the data processed so far.
                 Binary form.
        :rtype: byte string
        """

        self._digest_done = True
        bfr = create_string_buffer(self.digest_size)
        result = _raw_keccak_lib.keccak_digest(self._state.get(), bfr,
                                               c_size_t(self.digest_size))
        if result:
            raise ValueError("Error %d while squeezing keccak" % result)

        return get_raw_buffer(bfr)
コード例 #33
0
    def digest(self):
        """Return the **binary** (non-printable) digest of the message that has been hashed so far.

        This method does not change the state of the hash object.
        You can continue updating the object after calling this function.

        :Return: A byte string of `digest_size` bytes. It may contain non-ASCII
         characters, including null bytes.
        """

        bfr = create_string_buffer(self.digest_size)
        result = _raw_sha224_lib.SHA224_digest(self._state.get(), bfr)
        if result:
            raise ValueError("Error %d while instantiating SHA224" % result)

        return get_raw_buffer(bfr)
コード例 #34
0
ファイル: _mode_cbc.py プロジェクト: Dariusz1989/PsConnect
    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)

        That also means that you cannot reuse an object for encrypting
        or decrypting other data with the same key.

        This function does not add any padding to the plaintext.

        :Parameters:
          plaintext : bytes/bytearray/memoryview
            The piece of data to encrypt.
            Its lenght must be multiple of the cipher block size.
        :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_cbc_lib.CBC_encrypt(self._state.get(),
                                         c_uint8_ptr(plaintext), ciphertext,
                                         c_size_t(len(plaintext)))
        if result:
            if result == 3:
                raise ValueError(
                    "Data must be padded to %d byte boundary in CBC mode" %
                    self.block_size)
            raise ValueError("Error %d while encrypting in CBC mode" % result)
        return get_raw_buffer(ciphertext)
コード例 #35
0
    def encrypt(self, plaintext):
        """Encrypt a piece of data.

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

        expect_byte_string(plaintext)
        ciphertext = create_string_buffer(len(plaintext))
        result = _raw_arc4_lib.ARC4_stream_encrypt(self._state.get(),
                                                   plaintext, ciphertext,
                                                   c_size_t(len(plaintext)))
        if result:
            raise ValueError("Error %d while encrypting with RC4" % result)
        return get_raw_buffer(ciphertext)
コード例 #36
0
ファイル: ARC4.py プロジェクト: chevah/python-package
    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)
コード例 #37
0
    def encrypt(self, plaintext):
        """Encrypt a piece of data.

        :Parameters:
          plaintext : byte string
            The piece of data to encrypt. It can be of any size.
        :Return: the encrypted data (byte string, as long as the
          plaintext).
        """

        expect_byte_string(plaintext)
        ciphertext = create_string_buffer(len(plaintext))
        result = _raw_salsa20_lib.Salsa20_stream_encrypt(
            self._state.get(), plaintext, ciphertext, c_size_t(len(plaintext)))
        if result:
            raise ValueError("Error %d while encrypting with Salsa20" % result)
        return get_raw_buffer(ciphertext)
コード例 #38
0
ファイル: BLAKE2s.py プロジェクト: 2216288075/meiduo_project
    def digest(self):
        """Return the **binary** (non-printable) digest of the message that has been hashed so far.

        :return: The hash digest, computed over the data processed so far.
                 Binary form.
        :rtype: byte string
        """

        bfr = create_string_buffer(32)
        result = _raw_blake2s_lib.blake2s_digest(self._state.get(),
                                                 bfr)
        if result:
            raise ValueError("Error %d while creating BLAKE2s digest" % result)

        self._digest_done = True

        return get_raw_buffer(bfr)[:self.digest_size]
コード例 #39
0
ファイル: strxor.py プロジェクト: chevah/python-package
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)
コード例 #40
0
ファイル: keccak.py プロジェクト: chevah/python-package
    def digest(self):
        """Return the **binary** (non-printable) digest of the message that has been hashed so far.

        :return: The hash digest, computed over the data processed so far.
                 Binary form.
        :rtype: byte string
        """

        self._digest_done = True
        bfr = create_string_buffer(self.digest_size)
        result = _raw_keccak_lib.keccak_digest(self._state.get(),
                                               bfr,
                                               c_size_t(self.digest_size))
        if result:
            raise ValueError("Error %d while squeezing keccak" % result)

        return get_raw_buffer(bfr)
コード例 #41
0
ファイル: MD4.py プロジェクト: pablorusso/GoogleMusic.bundle
    def digest(self):
        """Return the **binary** (non-printable) digest of the message that
        has been hashed so far.

        This method does not change the state of the hash object.
        You can continue updating the object after calling this function.

        :Return: A byte string of `digest_size` bytes. It may contain non-ASCII
         characters, including null bytes.
        """

        bfr = create_string_buffer(self.digest_size)
        result = _raw_md4_lib.md4_digest(self._state.get(), bfr)
        if result:
            raise ValueError("Error %d while instantiating MD4" % result)

        return get_raw_buffer(bfr)
コード例 #42
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)

        That also means that you cannot reuse an object for encrypting
        or decrypting other data with the same key.

        This function does not add any padding to the plaintext.

        :Parameters:
          plaintext : byte string
            The piece of data to encrypt.
            Its lenght must be multiple of the cipher block size.
        :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 ]

        expect_byte_string(plaintext)
        ciphertext = create_string_buffer(len(plaintext))
        result = raw_cbc_lib.CBC_encrypt(self._state.get(),
                                         plaintext,
                                         ciphertext,
                                         c_size_t(len(plaintext)))
        if result:
            raise ValueError("Error %d while encrypting in CBC mode" % result)
        return get_raw_buffer(ciphertext)
コード例 #43
0
    def inplace_pow(self, exponent, modulus=None):
        exp_value = int(exponent)
        if exp_value < 0:
            raise ValueError("Exponent must not be negative")

        # No modular reduction
        if modulus is None:
            self._value = pow(self._value, exp_value)
            return self

        # With modular reduction
        mod_value = int(modulus)
        if mod_value < 0:
            raise ValueError("Modulus must be positive")
        if mod_value == 0:
            raise ZeroDivisionError("Modulus cannot be zero")

        # C extension only works with odd moduli
        if (mod_value & 1) == 0:
            self._value = pow(self._value, exp_value, mod_value)
            return self

        max_len = len(long_to_bytes(max(self._value, exp_value, mod_value)))

        base_b    = long_to_bytes(self._value, max_len)
        exp_b     = long_to_bytes(exp_value, max_len)
        modulus_b = long_to_bytes(mod_value, max_len)

        out = create_string_buffer(max_len)

        error = _raw_montgomery.monty_pow(
                    base_b,
                    exp_b,
                    modulus_b,
                    out,
                    c_size_t(max_len),
                    c_ulonglong(getrandbits(64))
                    )

        if error:
            raise ValueError("monty_pow failed with error: %d" % error)

        result = bytes_to_long(get_raw_buffer(out))
        self._value = result
        return self
コード例 #44
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 : byte string
            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]

        expect_byte_string(plaintext)
        ciphertext = create_string_buffer(len(plaintext))
        result = raw_ctr_lib.CTR_encrypt(self._state.get(),
                                         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)
コード例 #45
0
    def inplace_pow(self, exponent, modulus=None):
        exp_value = int(exponent)
        if exp_value < 0:
            raise ValueError("Exponent must not be negative")

        # No modular reduction
        if modulus is None:
            self._value = pow(self._value, exp_value)
            return self

        # With modular reduction
        mod_value = int(modulus)
        if mod_value < 0:
            raise ValueError("Modulus must be positive")
        if mod_value == 0:
            raise ZeroDivisionError("Modulus cannot be zero")

        # C extension only works with odd moduli
        if (mod_value & 1) == 0:
            self._value = pow(self._value, exp_value, mod_value)
            return self

        max_len = len(long_to_bytes(max(self._value, exp_value, mod_value)))

        base_b = long_to_bytes(self._value, max_len)
        exp_b = long_to_bytes(exp_value, max_len)
        modulus_b = long_to_bytes(mod_value, max_len)

        out = create_string_buffer(max_len)

        error = _raw_montgomery.monty_pow(
                    base_b,
                    exp_b,
                    modulus_b,
                    out,
                    c_size_t(max_len),
                    c_ulonglong(getrandbits(64))
                    )

        if error:
            raise ValueError("monty_pow failed with error: %d" % error)

        result = bytes_to_long(get_raw_buffer(out))
        self._value = result
        return self
コード例 #46
0
    def read(self, length):
        """Return the next ``length`` bytes of **binary** (non-printable)
        digest for the message.

        You cannot use ``update`` anymore after the first call to ``read``.

        :Return: A byte string of `length` bytes.
        """

        self._is_squeezing = True
        bfr = create_string_buffer(length)
        result = _raw_keccak_lib.keccak_squeeze(self._state.get(), bfr,
                                                c_size_t(length))
        if result:
            raise ValueError("Error %d while extracting from SHAKE256" %
                             result)

        return get_raw_buffer(bfr)
コード例 #47
0
    def digest(self):
        """Return the **binary** (non-printable) digest of the message that has been hashed so far.

        You cannot update the hash anymore after the first call to ``digest``
        (or ``hexdigest``).

        :Return: A byte string of `digest_size` bytes.
                 It may contain non-ASCII characters, including null bytes.
        """

        self._digest_done = True
        bfr = create_string_buffer(self.digest_size)
        result = _raw_keccak_lib.keccak_digest(self._state.get(), bfr,
                                               c_size_t(self.digest_size))
        if result:
            raise ValueError("Error %d while squeezing keccak" % result)

        return get_raw_buffer(bfr)
コード例 #48
0
ファイル: SHA256.py プロジェクト: 2216288075/meiduo_project
def _pbkdf2_hmac_assist(inner, outer, first_digest, iterations):
    """Compute the expensive inner loop in PBKDF-HMAC."""

    assert iterations > 0

    bfr = create_string_buffer(len(first_digest));
    result = _raw_sha256_lib.SHA256_pbkdf2_hmac_assist(
                    inner._state.get(),
                    outer._state.get(),
                    first_digest,
                    bfr,
                    c_size_t(iterations),
                    c_size_t(len(first_digest)))

    if result:
        raise ValueError("Error %d with PBKDF2-HMAC assist for SHA256" % result)

    return get_raw_buffer(bfr)
コード例 #49
0
    def _compute_mac_tag(self):

        if self._mac_tag is not None:
            return

        if self._cache_A:
            self._update(self._cache_A, len(self._cache_A))
            self._cache_A = b("")

        mac_tag = create_string_buffer(16)
        result = _raw_ocb_lib.OCB_digest(self._state.get(),
                                         mac_tag,
                                         c_size_t(len(mac_tag))
                                         )
        if result:
            raise ValueError("Error %d while computing digest in OCB mode"
                             % result)
        self._mac_tag = get_raw_buffer(mac_tag)[:self._mac_len]
コード例 #50
0
def monty_pow(base, exp, modulus):
    max_len = len(long_to_bytes(max(base, exp, modulus)))

    base_b, exp_b, modulus_b = [
        long_to_bytes(x, max_len) for x in (base, exp, modulus)
    ]

    out = create_string_buffer(max_len)
    error = _raw_montgomery.monty_pow(base_b, exp_b, modulus_b, out,
                                      c_size_t(max_len), c_ulonglong(32))

    if error == 2:
        raise ExceptionModulus()
    if error:
        raise ValueError("monty_pow failed with error: %d" % error)

    result = bytes_to_long(get_raw_buffer(out))
    return result
コード例 #51
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 : byte string/array
            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)
コード例 #52
0
ファイル: _mode_ctr.py プロジェクト: chevah/python-package
    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_ctr_lib.CTR_decrypt(self._state.get(),
                                         c_uint8_ptr(ciphertext),
                                         plaintext,
                                         c_size_t(len(ciphertext)))
        if result:
            if result == 0x60002:
                raise OverflowError("The counter has wrapped around in"
                                    " CTR mode")
            raise ValueError("Error %X while decrypting in CTR mode" % result)
        return get_raw_buffer(plaintext)
コード例 #53
0
    def encrypt(self, plaintext):
        """Encrypt a piece of data.

        :Parameters:
          plaintext : byte string
            The piece of data to encrypt. It can be of any size.
        :Return: the encrypted data (byte string, as long as the
          plaintext).
        """

        expect_byte_string(plaintext)
        ciphertext = create_string_buffer(len(plaintext))
        result = _raw_arc4_lib.ARC4_stream_encrypt(self._state.get(),
                                                   plaintext,
                                                   ciphertext,
                                                   c_size_t(len(plaintext)))
        if result:
            raise ValueError("Error %d while encrypting with RC4" % result)
        return get_raw_buffer(ciphertext)
コード例 #54
0
    def digest(self):
        """Return the **binary** (non-printable) digest of the message that has been hashed so far.

        You cannot update the hash anymore after the first call to ``digest``
        (or ``hexdigest``).

        :Return: A byte string of `digest_size` bytes. It may contain non-ASCII
         characters, including null bytes.
        """

        self._digest_done = True

        bfr = create_string_buffer(self.digest_size)
        result = _raw_keccak_lib.keccak_digest(self._state.get(), bfr, c_size_t(self.digest_size))
        if result:
            raise ValueError("Error %d while instantiating SHA-3/224" % result)

        self._digest_value = get_raw_buffer(bfr)
        return self._digest_value
コード例 #55
0
    def read(self, length):
        """Return the next ``length`` bytes of **binary** (non-printable)
        digest for the message.

        You cannot use ``update`` anymore after the first call to ``read``.

        :Return: A byte string of `length` bytes.
        """

        self._is_squeezing = True
        bfr = create_string_buffer(length)
        result = _raw_keccak_lib.keccak_squeeze(self._state.get(),
                                                bfr,
                                                c_size_t(length))
        if result:
            raise ValueError("Error %d while extracting from SHAKE128"
                             % result)

        return get_raw_buffer(bfr)
コード例 #56
0
ファイル: strxor.py プロジェクト: 2216288075/meiduo_project
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
コード例 #57
0
    def digest(self):
        """Return the **binary** (non-printable) digest of the message that
        has been hashed so far.

        You cannot update the hash anymore after the first call to ``digest``
        (or ``hexdigest``).

        :Return: A byte string of `digest_size` bytes. It may contain non-ASCII
         characters, including null bytes.
        """

        bfr = create_string_buffer(64)
        result = _raw_blake2b_lib.blake2b_digest(self._state.get(),
                                                 bfr)
        if result:
            raise ValueError("Error %d while creating BLAKE2b digest" % result)

        self._digest_done = True

        return get_raw_buffer(bfr)[:self.digest_size]
コード例 #58
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 : byte string
            The piece of data to decrypt.
            Its length must be multiple of the cipher block size.

        :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 ]

        expect_byte_string(ciphertext)
        plaintext = create_string_buffer(len(ciphertext))
        result = raw_cbc_lib.CBC_decrypt(self._state.get(),
                                         ciphertext,
                                         plaintext,
                                         c_size_t(len(ciphertext)))
        if result:
            raise ValueError("Error %d while decrypting in CBC mode" % result)
        return get_raw_buffer(plaintext)