Exemplo n.º 1
0
def _get_ghash_clmul():
    """Return None if CLMUL implementation is not available"""

    if not _cpu_features.have_clmul():
        return None
    try:
        api = _ghash_api_template.replace("%imp%", "clmul")
        lib = load_pycryptodome_raw_lib("Cryptodome.Hash._ghash_clmul", api)
        result = _build_impl(lib, "clmul")
    except OSError:
        result = None
    return result
Exemplo n.º 2
0
:var MODE_CCM: Counter with CBC-MAC (CCM) Mode
:var MODE_EAX: EAX Mode
:var MODE_SIV: Syntethic Initialization Vector (SIV)
:var MODE_GCM: Galois Counter Mode (GCM)
:var MODE_OCB: Offset Code Book (OCB)
"""

import sys

from Cryptodome.Cipher import _create_cipher
from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
                                  VoidPointer, SmartPointer,
                                  c_size_t, c_uint8_ptr)


_raw_cpuid_lib = load_pycryptodome_raw_lib("Cryptodome.Util._cpuid",
                                           "int have_aes_ni(void);")

_cproto = """
        int AES_start_operation(const uint8_t key[],
                                size_t key_len,
                                void **pResult);
        int AES_encrypt(const void *state,
                        const uint8_t *in,
                        uint8_t *out,
                        size_t data_len);
        int AES_decrypt(const void *state,
                        const uint8_t *in,
                        uint8_t *out,
                        size_t data_len);
        int AES_stop_operation(void *state);
        """
Exemplo n.º 3
0
"""

from Cryptodome.Util.py3compat import bord

from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
                                  VoidPointer, SmartPointer,
                                  create_string_buffer,
                                  get_raw_buffer, c_size_t,
                                  expect_byte_string)

_raw_md2_lib = load_pycryptodome_raw_lib(
                        "Cryptodome.Hash._MD2",
                        """
                        int md2_init(void **shaState);
                        int md2_destroy(void *shaState);
                        int md2_update(void *hs,
                                          const uint8_t *buf,
                                          size_t len);
                        int md2_digest(const void *shaState,
                                          uint8_t digest[20]);
                        int md2_copy(const void *src, void *dst);
                        """)


class MD2Hash(object):
    """Class that implements an MD2 hash
    """

    #: The size of the resulting hash in bytes.
    digest_size = 16
    #: The internal block size of the hash algorithm in bytes.
    block_size = 64
Exemplo n.º 4
0
import struct

from Cryptodome.Util.py3compat import *

from Cryptodome.Hash import SHA1, SHA256, HMAC, CMAC
from Cryptodome.Util.strxor import strxor
from Cryptodome.Util.number import size as bit_size, long_to_bytes, bytes_to_long

from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
                                      create_string_buffer, get_raw_buffer,
                                      c_size_t)
from functools import reduce

_raw_salsa20_lib = load_pycryptodome_raw_lib(
    "Cryptodome.Cipher._Salsa20", """
                    int Salsa20_8_core(const uint8_t *x, const uint8_t *y,
                                       uint8_t *out);
                    """)

_raw_scrypt_lib = load_pycryptodome_raw_lib(
    "Cryptodome.Protocol._scrypt", """
                    typedef int (core_t)(const uint8_t [64], const uint8_t [64], uint8_t [64]);
                    int scryptROMix(const uint8_t *data_in, uint8_t *data_out,
                           size_t data_len, unsigned N, core_t *core);
                    """)


def PBKDF1(password, salt, dkLen, count=1000, hashAlgo=None):
    """Derive one key from a password (or passphrase).

    This function performs key derivation according to an old version of
Exemplo n.º 5
0
__all__ = [ 'EcbMode' ]

from Cryptodome.Util.py3compat import _is_immutable
from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
                                  VoidPointer, create_string_buffer,
                                  get_raw_buffer, SmartPointer,
                                  c_size_t, c_uint8_ptr)

raw_ecb_lib = load_pycryptodome_raw_lib("Cryptodome.Cipher._raw_ecb", """
                    int ECB_start_operation(void *cipher,
                                            void **pResult);
                    int ECB_encrypt(void *ecbState,
                                    const uint8_t *in,
                                    uint8_t *out,
                                    size_t data_len);
                    int ECB_decrypt(void *ecbState,
                                    const uint8_t *in,
                                    uint8_t *out,
                                    size_t data_len);
                    int ECB_stop_operation(void *state);
                    """
                                        )


class EcbMode(object):
    """*Electronic Code Book (ECB)*.

    This is the simplest encryption mode. Each of the plaintext blocks
    is directly encrypted into a ciphertext block, independently of
    any other block.
Exemplo n.º 6
0
import sys

from Cryptodome.Cipher import _create_cipher
from Cryptodome.Util.py3compat import byte_string
from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer,
                                      SmartPointer, c_size_t, c_uint8_ptr)

_raw_arc2_lib = load_pycryptodome_raw_lib(
    "Cryptodome.Cipher._raw_arc2", """
                        int ARC2_start_operation(const uint8_t key[],
                                                 size_t key_len,
                                                 size_t effective_key_len,
                                                 void **pResult);
                        int ARC2_encrypt(const void *state,
                                         const uint8_t *in,
                                         uint8_t *out,
                                         size_t data_len);
                        int ARC2_decrypt(const void *state,
                                         const uint8_t *in,
                                         uint8_t *out,
                                         size_t data_len);
                        int ARC2_stop_operation(void *state);
                        """)


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")
Exemplo n.º 7
0
                                  c_ulonglong)


from Cryptodome.Random.random import getrandbits

c_defs = """
int monty_pow(const uint8_t *base,
               const uint8_t *exp,
               const uint8_t *modulus,
               uint8_t       *out,
               size_t len,
               uint64_t seed);
"""


_raw_montgomery = load_pycryptodome_raw_lib("Cryptodome.Math._montgomery", c_defs)
implementation = { "library":"custom", "api":backend }

class Integer(IntegerBase):

    @staticmethod
    def from_bytes(byte_string):
        return Integer(bytes_to_long(byte_string))

    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:
Exemplo n.º 8
0
from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
                                  VoidPointer, SmartPointer,
                                  create_string_buffer,
                                  get_raw_buffer, c_size_t,
                                  c_uint8_ptr)

_raw_sha256_lib = load_pycryptodome_raw_lib("Cryptodome.Hash._SHA256",
                        """
                        int SHA256_init(void **shaState);
                        int SHA256_destroy(void *shaState);
                        int SHA256_update(void *hs,
                                          const uint8_t *buf,
                                          size_t len);
                        int SHA256_digest(const void *shaState,
                                          uint8_t *digest,
                                          size_t digest_size);
                        int SHA256_copy(const void *src, void *dst);

                        int SHA256_pbkdf2_hmac_assist(const void *inner,
                                            const void *outer,
                                            const uint8_t *first_digest,
                                            uint8_t *final_digest,
                                            size_t iterations,
                                            size_t digest_size);
                        """)

class SHA256Hash(object):
    """A SHA-256 hash object.
    Do not instantiate directly. Use the :func:`new` function.

    :ivar oid: ASN.1 Object ID
Exemplo n.º 9
0
                                  c_size_t, c_ulonglong)


from Cryptodome.Random.random import getrandbits

c_defs = """
int monty_pow(const uint8_t *base,
               const uint8_t *exp,
               const uint8_t *modulus,
               uint8_t       *out,
               size_t len,
               uint64_t seed);
"""


_raw_montgomery = load_pycryptodome_raw_lib("Cryptodome.Math._montgomery", c_defs)
implementation = {"library": "custom", "api": backend}


class IntegerCustom(IntegerNative):

    @staticmethod
    def from_bytes(byte_string):
        return IntegerCustom(bytes_to_long(byte_string))

    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
Exemplo n.º 10
0
                                size_t key_len,
                                void **pResult);
        int AES_encrypt(const void *state,
                        const uint8_t *in,
                        uint8_t *out,
                        size_t data_len);
        int AES_decrypt(const void *state,
                        const uint8_t *in,
                        uint8_t *out,
                        size_t data_len);
        int AES_stop_operation(void *state);
        """


# Load portable AES
_raw_aes_lib = load_pycryptodome_raw_lib("Cryptodome.Cipher._raw_aes",
                                         _cproto)

# Try to load AES with AES NI instructions
try:
    _raw_aesni_lib = None
    if _cpu_features.have_aes_ni():
        _raw_aesni_lib = load_pycryptodome_raw_lib("Cryptodome.Cipher._raw_aesni",
                                                   _cproto.replace("AES",
                                                                   "AESNI"))
# _raw_aesni may not have been compiled in
except OSError:
    pass


def _create_base_cipher(dict_parameters):
    """This method instantiates and returns a handle to a low-level
Exemplo n.º 11
0
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ===================================================================

from Cryptodome.Util._raw_api import load_pycryptodome_raw_lib


_raw_cpuid_lib = load_pycryptodome_raw_lib("Cryptodome.Util._cpuid_c",
                                           """
                                           int have_aes_ni(void);
                                           int have_clmul(void);
                                           """)


def have_aes_ni():
    return _raw_cpuid_lib.have_aes_ni()


def have_clmul():
    return _raw_cpuid_lib.have_clmul()
Exemplo n.º 12
0
.. __: http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
.. _NIST: http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf
.. _AEAD: http://blog.cryptographyengineering.com/2012/05/how-to-choose-authenticated-encryption.html

:undocumented: __package__
"""

import sys

from Cryptodome.Cipher import _create_cipher
from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
                                  VoidPointer, SmartPointer,
                                  c_size_t, expect_byte_string)


_raw_cpuid_lib = load_pycryptodome_raw_lib("Cryptodome.Util._cpuid",
                                           "int have_aes_ni(void);")

_cproto = """
        int AES_start_operation(const uint8_t key[],
                                size_t key_len,
                                void **pResult);
        int AES_encrypt(const void *state,
                        const uint8_t *in,
                        uint8_t *out,
                        size_t data_len);
        int AES_decrypt(const void *state,
                        const uint8_t *in,
                        uint8_t *out,
                        size_t data_len);
        int AES_stop_operation(void *state);
        """
Exemplo n.º 13
0
from Cryptodome.Util.py3compat import _copy_bytes
from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer,
                                  create_string_buffer, get_raw_buffer,
                                  SmartPointer, c_size_t, c_uint8_ptr)

from Cryptodome.Random import get_random_bytes

raw_cfb_lib = load_pycryptodome_raw_lib("Cryptodome.Cipher._raw_cfb","""
                    int CFB_start_operation(void *cipher,
                                            const uint8_t iv[],
                                            size_t iv_len,
                                            size_t segment_len, /* In bytes */
                                            void **pResult);
                    int CFB_encrypt(void *cfbState,
                                    const uint8_t *in,
                                    uint8_t *out,
                                    size_t data_len);
                    int CFB_decrypt(void *cfbState,
                                    const uint8_t *in,
                                    uint8_t *out,
                                    size_t data_len);
                    int CFB_stop_operation(void *state);"""
                    )


class CfbMode(object):
    """*Cipher FeedBack (CFB)*.

    This mode is similar to CFB, but it transforms
    the underlying block cipher into a stream cipher.
Exemplo n.º 14
0
import struct
from struct import unpack

from Cryptodome.Util.py3compat import *

from Cryptodome.Hash import SHA1, SHA256, HMAC, CMAC
from Cryptodome.Util.strxor import strxor
from Cryptodome.Util.number import size as bit_size, long_to_bytes, bytes_to_long

from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
                                  create_string_buffer,
                                  get_raw_buffer)

_raw_salsa20_lib = load_pycryptodome_raw_lib("Cryptodome.Cipher._Salsa20",
                    """
                    int Salsa20_8_core(const uint8_t *x, const uint8_t *y,
                                       uint8_t *out);
                    uint32_t load_le_uint32(const uint8_t *in);
                    """)

def PBKDF1(password, salt, dkLen, count=1000, hashAlgo=None):
    """Derive one key from a password (or passphrase).

    This function performs key derivation according an old version of
    the PKCS#5 standard (v1.5).

    This algorithm is called ``PBKDF1``. Even though it is still described
    in the latest version of the PKCS#5 standard (version 2, or RFC2898),
    newer applications should use the more secure and versatile `PBKDF2` instead.

    :Parameters:
     password : string
Exemplo n.º 15
0
from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
                                  VoidPointer, SmartPointer,
                                  create_string_buffer,
                                  get_raw_buffer, c_size_t,
                                  c_uint8_ptr)

_raw_md5_lib = load_pycryptodome_raw_lib("Cryptodome.Hash._MD5",
                        """
                        #define MD5_DIGEST_SIZE 16

                        int MD5_init(void **shaState);
                        int MD5_destroy(void *shaState);
                        int MD5_update(void *hs,
                                          const uint8_t *buf,
                                          size_t len);
                        int MD5_digest(const void *shaState,
                                          uint8_t digest[MD5_DIGEST_SIZE]);
                        int MD5_copy(const void *src, void *dst);

                        int MD5_pbkdf2_hmac_assist(const void *inner,
                                            const void *outer,
                                            const uint8_t first_digest[MD5_DIGEST_SIZE],
                                            uint8_t final_digest[MD5_DIGEST_SIZE],
                                            size_t iterations);
                        """)

class MD5Hash(object):
    """A MD5 hash object.
    Do not instantiate directly.
    Use the :func:`new` function.
Exemplo n.º 16
0
from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer,
                                      create_string_buffer, get_raw_buffer,
                                      SmartPointer, c_size_t, c_uint8_ptr,
                                      is_buffer)

_raw_ocb_lib = load_pycryptodome_raw_lib(
    "Cryptodome.Cipher._raw_ocb", """
                                    int OCB_start_operation(void *cipher,
                                        const uint8_t *offset_0,
                                        size_t offset_0_len,
                                        void **pState);
                                    int OCB_encrypt(void *state,
                                        const uint8_t *in,
                                        uint8_t *out,
                                        size_t data_len);
                                    int OCB_decrypt(void *state,
                                        const uint8_t *in,
                                        uint8_t *out,
                                        size_t data_len);
                                    int OCB_update(void *state,
                                        const uint8_t *in,
                                        size_t data_len);
                                    int OCB_digest(void *state,
                                        uint8_t *tag,
                                        size_t tag_len);
                                    int OCB_stop_operation(void *state);
                                    """)


class OcbMode(object):
    """Offset Codebook (OCB) mode.
Exemplo n.º 17
0
        int AES_start_operation(const uint8_t key[],
                                size_t key_len,
                                void **pResult);
        int AES_encrypt(const void *state,
                        const uint8_t *in,
                        uint8_t *out,
                        size_t data_len);
        int AES_decrypt(const void *state,
                        const uint8_t *in,
                        uint8_t *out,
                        size_t data_len);
        int AES_stop_operation(void *state);
        """

# Load portable AES
_raw_aes_lib = load_pycryptodome_raw_lib("Cryptodome.Cipher._raw_aes", _cproto)

# Try to load AES with AES NI instructions
try:
    _raw_aesni_lib = None
    if _cpu_features.have_aes_ni():
        _raw_aesni_lib = load_pycryptodome_raw_lib(
            "Cryptodome.Cipher._raw_aesni", _cproto.replace("AES", "AESNI"))
# _raw_aesni may not have been compiled in
except OSError:
    pass


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."""
Exemplo n.º 18
0
"""

from Cryptodome.Util.py3compat import *

from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
                                  VoidPointer, SmartPointer,
                                  create_string_buffer,
                                  get_raw_buffer, c_size_t,
                                  expect_byte_string)

_raw_sha256_lib = load_pycryptodome_raw_lib("Cryptodome.Hash._SHA256",
                        """
                        int SHA256_init(void **shaState);
                        int SHA256_destroy(void *shaState);
                        int SHA256_update(void *hs,
                                          const uint8_t *buf,
                                          size_t len);
                        int SHA256_digest(const void *shaState,
                                          uint8_t digest[32]);
                        int SHA256_copy(const void *src, void *dst);
                        """)

class SHA256Hash(object):
    """Class that implements a SHA-256 hash
    """

    #: The size of the resulting hash in bytes.
    digest_size = 32
    #: The internal block size of the hash algorithm in bytes.
    block_size = 64
    #: ASN.1 Object ID
Exemplo n.º 19
0
import sys

from Cryptodome.Cipher import _create_cipher
from Cryptodome.Util.py3compat import byte_string
from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
                                  VoidPointer, SmartPointer,
                                  c_size_t, c_uint8_ptr)

_raw_cast_lib = load_pycryptodome_raw_lib(
                    "Cryptodome.Cipher._raw_cast",
                    """
                    int CAST_start_operation(const uint8_t key[],
                                             size_t key_len,
                                             void **pResult);
                    int CAST_encrypt(const void *state,
                                     const uint8_t *in,
                                     uint8_t *out,
                                     size_t data_len);
                    int CAST_decrypt(const void *state,
                                     const uint8_t *in,
                                     uint8_t *out,
                                     size_t data_len);
                    int CAST_stop_operation(void *state);
                    """)


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")
Exemplo n.º 20
0
:undocumented: __package__
"""

from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
                                  create_string_buffer,
                                  get_raw_buffer, VoidPointer,
                                  SmartPointer, c_size_t,
                                  expect_byte_string)

from Cryptodome.Random import get_random_bytes

_raw_salsa20_lib = load_pycryptodome_raw_lib("Cryptodome.Cipher._Salsa20",
                    """
                    int Salsa20_stream_init(uint8_t *key, size_t keylen,
                                            uint8_t *nonce, size_t nonce_len,
                                            void **pSalsaState);
                    int Salsa20_stream_destroy(void *salsaState);
                    int Salsa20_stream_encrypt(void *salsaState,
                                               const uint8_t in[],
                                               uint8_t out[], size_t len);
                    """)


class Salsa20Cipher:
    """Salsa20 cipher object"""

    def __init__(self, key, nonce):
        """Initialize a Salsa20 cipher object

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

        if len(key) not in key_size:
Exemplo n.º 21
0
from binascii import unhexlify

from Cryptodome.Util.py3compat import b, bord, tobytes

from Cryptodome.Random import get_random_bytes
from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer,
                                      SmartPointer, create_string_buffer,
                                      get_raw_buffer, c_size_t, c_uint8_ptr)

_raw_blake2b_lib = load_pycryptodome_raw_lib(
    "Cryptodome.Hash._BLAKE2b", """
                        int blake2b_init(void **state,
                                         const uint8_t *key,
                                         size_t key_size,
                                         size_t digest_size);
                        int blake2b_destroy(void *state);
                        int blake2b_update(void *state,
                                           const uint8_t *buf,
                                           size_t len);
                        int blake2b_digest(const void *state,
                                           uint8_t digest[64]);
                        int blake2b_copy(const void *src, void *dst);
                        """)


class BLAKE2b_Hash(object):
    """A BLAKE2b hash object.
    Do not instantiate directly. Use the :func:`new` function.

    :ivar oid: ASN.1 Object ID
    :vartype oid: string
Exemplo n.º 22
0
from Cryptodome.Util.py3compat import *

from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer,
                                      SmartPointer, create_string_buffer,
                                      get_raw_buffer, c_size_t, c_uint8_ptr)

_raw_md5_lib = load_pycryptodome_raw_lib(
    "Cryptodome.Hash._MD5", """
                        #define MD5_DIGEST_SIZE 16

                        int MD5_init(void **shaState);
                        int MD5_destroy(void *shaState);
                        int MD5_update(void *hs,
                                          const uint8_t *buf,
                                          size_t len);
                        int MD5_digest(const void *shaState,
                                          uint8_t digest[MD5_DIGEST_SIZE]);
                        int MD5_copy(const void *src, void *dst);

                        int MD5_pbkdf2_hmac_assist(const void *inner,
                                            const void *outer,
                                            const uint8_t first_digest[MD5_DIGEST_SIZE],
                                            uint8_t final_digest[MD5_DIGEST_SIZE],
                                            size_t iterations);
                        """)


class MD5Hash(object):
    """A MD5 hash object.
    Do not instantiate directly.
    Use the :func:`new` function.
Exemplo n.º 23
0
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ===================================================================

from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib, c_size_t,
                                  create_string_buffer, get_raw_buffer,
                                  c_uint8_ptr)

_raw_strxor = load_pycryptodome_raw_lib("Cryptodome.Util._strxor",
                    """
                    void strxor(const uint8_t *in1,
                                const uint8_t *in2,
                                uint8_t *out, size_t len);
                    void strxor_c(const uint8_t *in,
                                  uint8_t c,
                                  uint8_t *out,
                                  size_t len);
                    """)


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):
Exemplo n.º 24
0
__all__ = ['CbcMode']

from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer,
                                  create_string_buffer, get_raw_buffer,
                                  SmartPointer, c_size_t, expect_byte_string)

from Cryptodome.Random import get_random_bytes

raw_cbc_lib = load_pycryptodome_raw_lib("Cryptodome.Cipher._raw_cbc", """
                int CBC_start_operation(void *cipher,
                                        const uint8_t iv[],
                                        size_t iv_len,
                                        void **pResult);
                int CBC_encrypt(void *cbcState,
                                const uint8_t *in,
                                uint8_t *out,
                                size_t data_len);
                int CBC_decrypt(void *cbcState,
                                const uint8_t *in,
                                uint8_t *out,
                                size_t data_len);
                int CBC_stop_operation(void *state);
                """
                )


class CbcMode(object):
    """*Cipher-Block Chaining (CBC)*.

    Each of the ciphertext blocks depends on the current
    and all previous plaintext blocks.
Exemplo n.º 25
0
.. _RFC1320: http://tools.ietf.org/html/rfc1320
"""

from Cryptodome.Util.py3compat import bord

from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer,
                                      SmartPointer, create_string_buffer,
                                      get_raw_buffer, c_size_t,
                                      expect_byte_string)

_raw_md4_lib = load_pycryptodome_raw_lib(
    "Cryptodome.Hash._MD4", """
                        int md4_init(void **shaState);
                        int md4_destroy(void *shaState);
                        int md4_update(void *hs,
                                          const uint8_t *buf,
                                          size_t len);
                        int md4_digest(const void *shaState,
                                          uint8_t digest[20]);
                        int md4_copy(const void *src, void *dst);
                        """)


class MD4Hash(object):
    """Class that implements an MD4 hash
    """

    #: The size of the resulting hash in bytes.
    digest_size = 16
    #: The internal block size of the hash algorithm in bytes.
    block_size = 64
Exemplo n.º 26
0
import struct
from struct import unpack

from Cryptodome.Util.py3compat import *

from Cryptodome.Hash import SHA1, SHA256, HMAC, CMAC
from Cryptodome.Util.strxor import strxor
from Cryptodome.Util.number import size as bit_size, long_to_bytes, bytes_to_long

from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
                                      create_string_buffer, get_raw_buffer)

_raw_salsa20_lib = load_pycryptodome_raw_lib(
    "Cryptodome.Cipher._Salsa20", """
                    int Salsa20_8_core(const uint8_t *x, const uint8_t *y,
                                       uint8_t *out);
                    uint32_t load_le_uint32(const uint8_t *in);
                    """)


def PBKDF1(password, salt, dkLen, count=1000, hashAlgo=None):
    """Derive one key from a password (or passphrase).

    This function performs key derivation according an old version of
    the PKCS#5 standard (v1.5).

    This algorithm is called ``PBKDF1``. Even though it is still described
    in the latest version of the PKCS#5 standard (version 2, or RFC2898),
    newer applications should use the more secure and versatile `PBKDF2` instead.

    :Parameters:
Exemplo n.º 27
0
from Cryptodome.Util.py3compat import _copy_bytes
from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer,
                                      create_string_buffer, get_raw_buffer,
                                      SmartPointer, c_size_t, c_uint8_ptr)

from Cryptodome.Random import get_random_bytes

raw_cfb_lib = load_pycryptodome_raw_lib(
    "Cryptodome.Cipher._raw_cfb", """
                    int CFB_start_operation(void *cipher,
                                            const uint8_t iv[],
                                            size_t iv_len,
                                            size_t segment_len, /* In bytes */
                                            void **pResult);
                    int CFB_encrypt(void *cfbState,
                                    const uint8_t *in,
                                    uint8_t *out,
                                    size_t data_len);
                    int CFB_decrypt(void *cfbState,
                                    const uint8_t *in,
                                    uint8_t *out,
                                    size_t data_len);
                    int CFB_stop_operation(void *state);""")


class CfbMode(object):
    """*Cipher FeedBack (CFB)*.

    This mode is similar to CFB, but it transforms
    the underlying block cipher into a stream cipher.
Exemplo n.º 28
0
from Cryptodome.Cipher import _create_cipher
from Cryptodome.Util.py3compat import byte_string
from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
                                  VoidPointer, SmartPointer,
                                  c_size_t, expect_byte_string)

_raw_arc2_lib = load_pycryptodome_raw_lib(
                        "Cryptodome.Cipher._raw_arc2",
                        """
                        int ARC2_start_operation(const uint8_t key[],
                                                 size_t key_len,
                                                 size_t effective_key_len,
                                                 void **pResult);
                        int ARC2_encrypt(const void *state,
                                         const uint8_t *in,
                                         uint8_t *out,
                                         size_t data_len);
                        int ARC2_decrypt(const void *state,
                                         const uint8_t *in,
                                         uint8_t *out,
                                         size_t data_len);
                        int ARC2_stop_operation(void *state);
                        """
                        )


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:
Exemplo n.º 29
0
__all__ = [ 'EcbMode' ]

from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
                                  VoidPointer, create_string_buffer,
                                  get_raw_buffer, SmartPointer,
                                  c_size_t, c_uint8_ptr,
                                  is_writeable_buffer)

raw_ecb_lib = load_pycryptodome_raw_lib("Cryptodome.Cipher._raw_ecb", """
                    int ECB_start_operation(void *cipher,
                                            void **pResult);
                    int ECB_encrypt(void *ecbState,
                                    const uint8_t *in,
                                    uint8_t *out,
                                    size_t data_len);
                    int ECB_decrypt(void *ecbState,
                                    const uint8_t *in,
                                    uint8_t *out,
                                    size_t data_len);
                    int ECB_stop_operation(void *state);
                    """
                                        )


class EcbMode(object):
    """*Electronic Code Book (ECB)*.

    This is the simplest encryption mode. Each of the plaintext blocks
    is directly encrypted into a ciphertext block, independently of
    any other block.
Exemplo n.º 30
0
"""

from Cryptodome.Util.py3compat import bord

from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
                                  VoidPointer, SmartPointer,
                                  create_string_buffer,
                                  get_raw_buffer, c_size_t,
                                  expect_byte_string)

_raw_ripemd160_lib = load_pycryptodome_raw_lib(
                        "Cryptodome.Hash._RIPEMD160",
                        """
                        int ripemd160_init(void **shaState);
                        int ripemd160_destroy(void *shaState);
                        int ripemd160_update(void *hs,
                                          const uint8_t *buf,
                                          size_t len);
                        int ripemd160_digest(const void *shaState,
                                          uint8_t digest[20]);
                        int ripemd160_copy(const void *src, void *dst);
                        """)


class RIPEMD160Hash(object):
    """Class that implements a RIPEMD-160 hash
    """

    #: The size of the resulting hash in bytes.
    digest_size = 20
    #: The internal block size of the hash algorithm in bytes.
    block_size = 64
Exemplo n.º 31
0
from Cryptodome.Util.py3compat import b, bchr, byte_string, bord, unhexlify

from Cryptodome.Util.number import long_to_bytes, bytes_to_long
from Cryptodome.Hash import BLAKE2s
from Cryptodome.Random import get_random_bytes

from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer,
                                  create_string_buffer, get_raw_buffer,
                                  SmartPointer, c_size_t, expect_byte_string)

_raw_galois_lib = load_pycryptodome_raw_lib("Cryptodome.Util._galois",
                    """
                    int ghash(  uint8_t y_out[16],
                                const uint8_t block_data[],
                                size_t len,
                                const uint8_t y_in[16],
                                const void *exp_key);
                    int ghash_expand(const uint8_t h[16],
                                     void **ghash_tables);
                    int ghash_destroy(void *ghash_tables);
                    """)


class _GHASH(object):
    """GHASH function defined in NIST SP 800-38D, Algorithm 2.

    If X_1, X_2, .. X_m are the blocks of input data, the function
    computes:

       X_1*H^{m} + X_2*H^{m-1} + ... + X_m*H
Exemplo n.º 32
0
import struct

from Cryptodome.Util.py3compat import tobytes, bord, _copy_bytes

from Cryptodome.Hash import SHA1, SHA256, HMAC, CMAC
from Cryptodome.Util.strxor import strxor
from Cryptodome.Util.number import size as bit_size, long_to_bytes, bytes_to_long

from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
                                  create_string_buffer,
                                  get_raw_buffer, c_size_t)

_raw_salsa20_lib = load_pycryptodome_raw_lib("Cryptodome.Cipher._Salsa20",
                    """
                    int Salsa20_8_core(const uint8_t *x, const uint8_t *y,
                                       uint8_t *out);
                    """)

_raw_scrypt_lib = load_pycryptodome_raw_lib("Cryptodome.Protocol._scrypt",
                    """
                    typedef int (core_t)(const uint8_t [64], const uint8_t [64], uint8_t [64]);
                    int scryptROMix(const uint8_t *data_in, uint8_t *data_out,
                           size_t data_len, unsigned N, core_t *core);
                    """)


def PBKDF1(password, salt, dkLen, count=1000, hashAlgo=None):
    """Derive one key from a password (or passphrase).

    This function performs key derivation according to an old version of
Exemplo n.º 33
0
from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
                                  VoidPointer, SmartPointer,
                                  create_string_buffer,
                                  get_raw_buffer, c_size_t,
                                  c_uint8_ptr, c_ubyte)

_raw_keccak_lib = load_pycryptodome_raw_lib("Cryptodome.Hash._keccak",
                        """
                        int keccak_init(void **state,
                                        size_t capacity_bytes,
                                        uint8_t rounds);
                        int keccak_destroy(void *state);
                        int keccak_absorb(void *state,
                                          const uint8_t *in,
                                          size_t len);
                        int keccak_squeeze(const void *state,
                                           uint8_t *out,
                                           size_t len,
                                           uint8_t padding);
                        int keccak_digest(void *state,
                                          uint8_t *digest,
                                          size_t len,
                                          uint8_t padding);
                        int keccak_copy(const void *src, void *dst);
                        int keccak_reset(void *state);
                        """)

class Keccak_Hash(object):
    """A Keccak hash object.
    Do not instantiate directly.
    Use the :func:`new` function.
Exemplo n.º 34
0
from Cryptodome.Util.py3compat import *

from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer,
                                      SmartPointer, create_string_buffer,
                                      get_raw_buffer, c_size_t, c_uint8_ptr)

_raw_sha1_lib = load_pycryptodome_raw_lib(
    "Cryptodome.Hash._SHA1", """
                        #define SHA1_DIGEST_SIZE 20

                        int SHA1_init(void **shaState);
                        int SHA1_destroy(void *shaState);
                        int SHA1_update(void *hs,
                                          const uint8_t *buf,
                                          size_t len);
                        int SHA1_digest(const void *shaState,
                                          uint8_t digest[SHA1_DIGEST_SIZE]);
                        int SHA1_copy(const void *src, void *dst);

                        int SHA1_pbkdf2_hmac_assist(const void *inner,
                                            const void *outer,
                                            const uint8_t first_digest[SHA1_DIGEST_SIZE],
                                            uint8_t final_digest[SHA1_DIGEST_SIZE],
                                            size_t iterations);
                        """)


class SHA1Hash(object):
    """A SHA-1 hash object.
    Do not instantiate directly.
    Use the :func:`new` function.
Exemplo n.º 35
0
from Cryptodome.Util.py3compat import _copy_bytes
from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer,
                                  create_string_buffer, get_raw_buffer,
                                  SmartPointer, c_size_t, c_uint8_ptr)

from Cryptodome.Random import get_random_bytes

raw_cbc_lib = load_pycryptodome_raw_lib("Cryptodome.Cipher._raw_cbc", """
                int CBC_start_operation(void *cipher,
                                        const uint8_t iv[],
                                        size_t iv_len,
                                        void **pResult);
                int CBC_encrypt(void *cbcState,
                                const uint8_t *in,
                                uint8_t *out,
                                size_t data_len);
                int CBC_decrypt(void *cbcState,
                                const uint8_t *in,
                                uint8_t *out,
                                size_t data_len);
                int CBC_stop_operation(void *state);
                """
                )


class CbcMode(object):
    """*Cipher-Block Chaining (CBC)*.

    Each of the ciphertext blocks depends on the current
    and all previous plaintext blocks.
Exemplo n.º 36
0
from Cryptodome.Random import get_random_bytes
from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
                                  VoidPointer, SmartPointer,
                                  create_string_buffer,
                                  get_raw_buffer, c_size_t,
                                  c_uint8_ptr)


_raw_poly1305 = load_pycryptodome_raw_lib("Cryptodome.Hash._poly1305",
                        """
                        int poly1305_init(void **state,
                                          const uint8_t *r,
                                          size_t r_len,
                                          const uint8_t *s,
                                          size_t s_len);
                        int poly1305_destroy(void *state);
                        int poly1305_update(void *state,
                                            const uint8_t *in,
                                            size_t len);
                        int poly1305_digest(const void *state,
                                            uint8_t *digest,
                                            size_t len);
                        """)


class Poly1305_MAC(object):
    """An Poly1305 MAC object.
    Do not instantiate directly. Use the :func:`new` function.

    :ivar digest_size: the size in bytes of the resulting MAC tag
    :vartype digest_size: integer
Exemplo n.º 37
0
# ===================================================================

from Cryptodome.Util.py3compat import bord

from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
                                  VoidPointer, SmartPointer,
                                  create_string_buffer,
                                  get_raw_buffer, c_size_t,
                                  c_uint8_ptr)

_raw_ripemd160_lib = load_pycryptodome_raw_lib(
                        "Cryptodome.Hash._RIPEMD160",
                        """
                        int ripemd160_init(void **shaState);
                        int ripemd160_destroy(void *shaState);
                        int ripemd160_update(void *hs,
                                          const uint8_t *buf,
                                          size_t len);
                        int ripemd160_digest(const void *shaState,
                                          uint8_t digest[20]);
                        int ripemd160_copy(const void *src, void *dst);
                        """)


class RIPEMD160Hash(object):
    """A RIPEMD-160 hash object.
    Do not instantiate directly.
    Use the :func:`new` function.

    :ivar oid: ASN.1 Object ID
    :vartype oid: string
Exemplo n.º 38
0
from Cryptodome.Util.py3compat import b, bord, tobytes

from Cryptodome.Random import get_random_bytes
from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
                                  VoidPointer, SmartPointer,
                                  create_string_buffer,
                                  get_raw_buffer, c_size_t,
                                  expect_byte_string)

_raw_blake2b_lib = load_pycryptodome_raw_lib("Cryptodome.Hash._BLAKE2b",
                        """
                        int blake2b_init(void **state,
                                         const uint8_t *key,
                                         size_t key_size,
                                         size_t digest_size);
                        int blake2b_destroy(void *state);
                        int blake2b_update(void *state,
                                           const uint8_t *buf,
                                           size_t len);
                        int blake2b_digest(const void *state,
                                           uint8_t digest[64]);
                        int blake2b_copy(const void *src, void *dst);
                        """)


class BLAKE2b_Hash(object):
    """Class that implements a BLAKE2b hash
    """

    #: The internal block size of the hash algorithm in bytes.
    block_size = 64
Exemplo n.º 39
0
.. _ARC4: http://en.wikipedia.org/wiki/RC4

:undocumented: __package__
"""

from Cryptodome.Util.py3compat import b

from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer,
                                  create_string_buffer, get_raw_buffer,
                                  SmartPointer, c_size_t, expect_byte_string)


_raw_arc4_lib = load_pycryptodome_raw_lib("Cryptodome.Cipher._ARC4", """
                    int ARC4_stream_encrypt(void *rc4State, const uint8_t in[],
                                            uint8_t out[], size_t len);
                    int ARC4_stream_init(uint8_t *key, size_t keylen,
                                         void **pRc4State);
                    int ARC4_stream_destroy(void *rc4State);
                    """)


class ARC4Cipher:
    """ARC4 cipher object"""

    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]
Exemplo n.º 40
0
from Cryptodome.Util.py3compat import b, bchr, byte_string, bord, unhexlify

from Cryptodome.Util.number import long_to_bytes, bytes_to_long
from Cryptodome.Hash import BLAKE2s
from Cryptodome.Random import get_random_bytes

from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer,
                                  create_string_buffer, get_raw_buffer,
                                  SmartPointer, c_size_t, expect_byte_string)

_raw_galois_lib = load_pycryptodome_raw_lib("Cryptodome.Util._galois",
                    """
                    int ghash(  uint8_t y_out[16],
                                const uint8_t block_data[],
                                size_t len,
                                const uint8_t y_in[16],
                                const void *exp_key);
                    int ghash_expand(const uint8_t h[16],
                                     void **ghash_tables);
                    int ghash_destroy(void *ghash_tables);
                    """)


class _GHASH(object):
    """GHASH function defined in NIST SP 800-38D, Algorithm 2.

    If X_1, X_2, .. X_m are the blocks of input data, the function
    computes:

       X_1*H^{m} + X_2*H^{m-1} + ... + X_m*H
Exemplo n.º 41
0
def _get_ghash_portable():
    api = _ghash_api_template.replace("%imp%", "portable")
    lib = load_pycryptodome_raw_lib("Cryptodome.Hash._ghash_portable", api)
    result = _build_impl(lib, "portable")
    return result
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ===================================================================

from Cryptodome.Util._raw_api import load_pycryptodome_raw_lib

_raw_cpuid_lib = load_pycryptodome_raw_lib(
    "Cryptodome.Util._cpuid_c", """
                                           int have_aes_ni(void);
                                           int have_clmul(void);
                                           """)


def have_aes_ni():
    return _raw_cpuid_lib.have_aes_ni()


def have_clmul():
    return _raw_cpuid_lib.have_clmul()
Exemplo n.º 43
0
                                      create_string_buffer, get_raw_buffer,
                                      SmartPointer, c_size_t, c_uint8_ptr)

from Cryptodome.Random import get_random_bytes
from Cryptodome.Util.py3compat import byte_string, _copy_bytes
from Cryptodome.Util.number import long_to_bytes

raw_ctr_lib = load_pycryptodome_raw_lib(
    "Cryptodome.Cipher._raw_ctr", """
                    int CTR_start_operation(void *cipher,
                                            uint8_t   initialCounterBlock[],
                                            size_t    initialCounterBlock_len,
                                            size_t    prefix_len,
                                            unsigned  counter_len,
                                            unsigned  littleEndian,
                                            void **pResult);
                    int CTR_encrypt(void *ctrState,
                                    const uint8_t *in,
                                    uint8_t *out,
                                    size_t data_len);
                    int CTR_decrypt(void *ctrState,
                                    const uint8_t *in,
                                    uint8_t *out,
                                    size_t data_len);
                    int CTR_stop_operation(void *ctrState);""")


class CtrMode(object):
    """*CounTeR (CTR)* mode.

    This mode is very similar to ECB, in that
    encryption of one block is done independently of all other blocks.
Exemplo n.º 44
0
from Cryptodome.Hash import BLAKE2s
from Cryptodome.Random import get_random_bytes
from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
                                  VoidPointer, SmartPointer,
                                  create_string_buffer,
                                  get_raw_buffer, c_size_t,
                                  c_uint8_ptr)

_raw_poly1305 = load_pycryptodome_raw_lib("Cryptodome.Hash._poly1305",
                        """
                        int poly1305_init(void **state,
                                          const uint8_t *r,
                                          size_t r_len,
                                          const uint8_t *s,
                                          size_t s_len);
                        int poly1305_destroy(void *state);
                        int poly1305_update(void *state,
                                            const uint8_t *in,
                                            size_t len);
                        int poly1305_digest(const void *state,
                                            uint8_t *digest,
                                            size_t len);
                        """)


class Poly1305_MAC(object):

    digest_size = 16

    def __init__(self, r, s, data):
Exemplo n.º 45
0
from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
                                  create_string_buffer,
                                  get_raw_buffer, VoidPointer,
                                  SmartPointer, c_size_t,
                                  c_uint8_ptr, c_ulong)

_raw_chacha20_lib = load_pycryptodome_raw_lib("Cryptodome.Cipher._chacha20",
                    """
                    int chacha20_init(void **pState,
                                      const uint8_t *key,
                                      size_t keySize,
                                      const uint8_t *nonce,
                                      size_t nonceSize);

                    int chacha20_destroy(void *state);

                    int chacha20_encrypt(void *state,
                                         const uint8_t in[],
                                         uint8_t out[],
                                         size_t len);

                    int chacha20_seek(void *state,
                                      unsigned long block_high,
                                      unsigned long block_low,
                                      unsigned offset);
                    """)


class ChaCha20Cipher:
    """ChaCha20 cipher object. Do not create it directly. Use :py:func:`new` instead.

    :var nonce: The nonce with length 8 or 12
Exemplo n.º 46
0
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ===================================================================

from Cryptodome.Util.py3compat import b

from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer,
                                      create_string_buffer, get_raw_buffer,
                                      SmartPointer, c_size_t, c_uint8_ptr)

_raw_arc4_lib = load_pycryptodome_raw_lib(
    "Cryptodome.Cipher._ARC4", """
                    int ARC4_stream_encrypt(void *rc4State, const uint8_t in[],
                                            uint8_t out[], size_t len);
                    int ARC4_stream_init(uint8_t *key, size_t keylen,
                                         void **pRc4State);
                    int ARC4_stream_destroy(void *rc4State);
                    """)


class ARC4Cipher:
    """ARC4 cipher object. Do not create it directly. Use
    :func:`Cryptodome.Cipher.ARC4.new` instead.
    """
    def __init__(self, key, *args, **kwargs):
        """Initialize an ARC4 cipher object

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

        if len(args) > 0:
Exemplo n.º 47
0
from Cryptodome.Util.py3compat import bord

from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer,
                                      SmartPointer, create_string_buffer,
                                      get_raw_buffer, c_size_t, c_uint8_ptr)

_raw_sha256_lib = load_pycryptodome_raw_lib(
    "Cryptodome.Hash._SHA256", """
                        int SHA256_init(void **shaState);
                        int SHA256_destroy(void *shaState);
                        int SHA256_update(void *hs,
                                          const uint8_t *buf,
                                          size_t len);
                        int SHA256_digest(const void *shaState,
                                          uint8_t *digest,
                                          size_t digest_size);
                        int SHA256_copy(const void *src, void *dst);

                        int SHA256_pbkdf2_hmac_assist(const void *inner,
                                            const void *outer,
                                            const uint8_t *first_digest,
                                            uint8_t *final_digest,
                                            size_t iterations,
                                            size_t digest_size);
                        """)


class SHA256Hash(object):
    """A SHA-256 hash object.
    Do not instantiate directly. Use the :func:`new` function.
Exemplo n.º 48
0
from Cryptodome.Util.py3compat import bord

from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
                                  VoidPointer, SmartPointer,
                                  create_string_buffer,
                                  get_raw_buffer, c_size_t,
                                  c_uint8_ptr)

_raw_keccak_lib = load_pycryptodome_raw_lib("Cryptodome.Hash._keccak",
                        """
                        int keccak_init(void **state,
                                        size_t capacity_bytes,
                                        uint8_t padding_byte);
                        int keccak_destroy(void *state);
                        int keccak_absorb(void *state,
                                          const uint8_t *in,
                                          size_t len);
                        int keccak_squeeze(const void *state,
                                           uint8_t *out,
                                           size_t len);
                        int keccak_digest(void *state, uint8_t *digest, size_t len);
                        """)

class Keccak_Hash(object):
    """A Keccak hash object.
    Do not instantiate directly.
    Use the :func:`new` function.

    :ivar digest_size: the size in bytes of the resulting hash
    :vartype digest_size: integer
    """
Exemplo n.º 49
0
from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
                                  create_string_buffer,
                                  get_raw_buffer, VoidPointer,
                                  SmartPointer, c_size_t,
                                  c_uint8_ptr, c_ulong)

_raw_chacha20_lib = load_pycryptodome_raw_lib("Cryptodome.Cipher._chacha20",
                    """
                    int chacha20_init(void **pState,
                                      const uint8_t *key,
                                      size_t keySize,
                                      const uint8_t *nonce,
                                      size_t nonceSize);

                    int chacha20_destroy(void *state);

                    int chacha20_encrypt(void *state,
                                         const uint8_t in[],
                                         uint8_t out[],
                                         size_t len);

                    int chacha20_seek(void *state,
                                      unsigned long block_high,
                                      unsigned long block_low,
                                      unsigned offset);
                    """)


class ChaCha20Cipher:
    """ChaCha20 cipher object. Do not create it directly. Use :py:func:`new` instead.

    :var nonce: The nonce with length 8
from Cryptodome.Cipher import _create_cipher
from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer,
                                      SmartPointer, c_size_t, c_uint8_ptr,
                                      c_uint)

_raw_blowfish_lib = load_pycryptodome_raw_lib(
    "Cryptodome.Cipher._raw_eksblowfish", """
        int EKSBlowfish_start_operation(const uint8_t key[],
                                        size_t key_len,
                                        const uint8_t salt[16],
                                        size_t salt_len,
                                        unsigned cost,
                                        unsigned invert,
                                        void **pResult);
        int EKSBlowfish_encrypt(const void *state,
                                const uint8_t *in,
                                uint8_t *out,
                                size_t data_len);
        int EKSBlowfish_decrypt(const void *state,
                                const uint8_t *in,
                                uint8_t *out,
                                size_t data_len);
        int EKSBlowfish_stop_operation(void *state);
        """)


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."""
Exemplo n.º 51
0
# SOFTWARE.
# ===================================================================

from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
                                  create_string_buffer,
                                  get_raw_buffer, VoidPointer,
                                  SmartPointer, c_size_t,
                                  expect_byte_string)

from Cryptodome.Random import get_random_bytes

_raw_salsa20_lib = load_pycryptodome_raw_lib("Cryptodome.Cipher._Salsa20",
                    """
                    int Salsa20_stream_init(uint8_t *key, size_t keylen,
                                            uint8_t *nonce, size_t nonce_len,
                                            void **pSalsaState);
                    int Salsa20_stream_destroy(void *salsaState);
                    int Salsa20_stream_encrypt(void *salsaState,
                                               const uint8_t in[],
                                               uint8_t out[], size_t len);
                    """)


class Salsa20Cipher:
    """Salsa20 cipher object. Do not create it directly. Use :py:func:`new`
    instead.

    :var nonce: The nonce with length 8
    :vartype nonce: byte string
    """

    def __init__(self, key, nonce):
Exemplo n.º 52
0
"""

from Cryptodome.Util.py3compat import *

from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
                                  VoidPointer, SmartPointer,
                                  create_string_buffer,
                                  get_raw_buffer, c_size_t,
                                  expect_byte_string)

_raw_sha224_lib = load_pycryptodome_raw_lib("Cryptodome.Hash._SHA224",
                        """
                        int SHA224_init(void **shaState);
                        int SHA224_destroy(void *shaState);
                        int SHA224_update(void *hs,
                                          const uint8_t *buf,
                                          size_t len);
                        int SHA224_digest(const void *shaState,
                                          uint8_t digest[16]);
                        int SHA224_copy(const void *src, void *dst);
                        """)

class SHA224Hash(object):
    """Class that implements a SHA-224 hash
    """

    #: The size of the resulting hash in bytes.
    digest_size = 28
    #: The internal block size of the hash algorithm in bytes.
    block_size = 64
    #: ASN.1 Object ID
Exemplo n.º 53
0
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ===================================================================

from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib, c_size_t,
                                      create_string_buffer, get_raw_buffer,
                                      c_uint8_ptr)

_raw_strxor = load_pycryptodome_raw_lib(
    "Cryptodome.Util._strxor", """
                    void strxor(const uint8_t *in1,
                                const uint8_t *in2,
                                uint8_t *out, size_t len);
                    void strxor_c(const uint8_t *in,
                                  uint8_t c,
                                  uint8_t *out,
                                  size_t len);
                    """)


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):
Exemplo n.º 54
0
_ec_lib = load_pycryptodome_raw_lib(
    "Cryptodome.PublicKey._ec_ws", """
typedef void EcContext;
typedef void EcPoint;
int ec_ws_new_context(EcContext **pec_ctx,
                      const uint8_t *modulus,
                      const uint8_t *b,
                      const uint8_t *order,
                      size_t len,
                      uint64_t seed);
void ec_free_context(EcContext *ec_ctx);
int ec_ws_new_point(EcPoint **pecp,
                    const uint8_t *x,
                    const uint8_t *y,
                    size_t len,
                    const EcContext *ec_ctx);
void ec_free_point(EcPoint *ecp);
int ec_ws_get_xy(uint8_t *x,
                 uint8_t *y,
                 size_t len,
                 const EcPoint *ecp);
int ec_ws_double(EcPoint *p);
int ec_ws_add(EcPoint *ecpa, EcPoint *ecpb);
int ec_ws_scalar(EcPoint *ecp,
                 const uint8_t *k,
                 size_t len,
                 uint64_t seed);
int ec_ws_clone(EcPoint **pecp2, const EcPoint *ecp);
int ec_ws_copy(EcPoint *ecp1, const EcPoint *ecp2);
int ec_ws_cmp(const EcPoint *ecp1, const EcPoint *ecp2);
int ec_ws_neg(EcPoint *p);
int ec_ws_normalize(EcPoint *ecp);
int ec_ws_is_pai(EcPoint *ecp);
""")
Exemplo n.º 55
0
import sys

from Cryptodome.Cipher import _create_cipher
from Cryptodome.Util.py3compat import byte_string, b, bchr, bord
from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer,
                                      SmartPointer, c_size_t,
                                      expect_byte_string)

_raw_des3_lib = load_pycryptodome_raw_lib(
    "Cryptodome.Cipher._raw_des3", """
                    int DES3_start_operation(const uint8_t key[],
                                             size_t key_len,
                                             void **pResult);
                    int DES3_encrypt(const void *state,
                                     const uint8_t *in,
                                     uint8_t *out,
                                     size_t data_len);
                    int DES3_decrypt(const void *state,
                                     const uint8_t *in,
                                     uint8_t *out,
                                     size_t data_len);
                    int DES3_stop_operation(void *state);
                    """)


def adjust_key_parity(key_in):
    """Return the TDES key with parity bits correctly set"""
    def parity_byte(key_byte):
        parity = 1
        for i in range(1, 8):
            parity ^= (key_byte >> i) & 1
Exemplo n.º 56
0
from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer,
                                  create_string_buffer, get_raw_buffer,
                                  SmartPointer, c_size_t, expect_byte_string,
                                  )

_raw_ocb_lib = load_pycryptodome_raw_lib("Cryptodome.Cipher._raw_ocb", """
                                    int OCB_start_operation(void *cipher,
                                        const uint8_t *offset_0,
                                        size_t offset_0_len,
                                        void **pState);
                                    int OCB_encrypt(void *state,
                                        const uint8_t *in,
                                        uint8_t *out,
                                        size_t data_len);
                                    int OCB_decrypt(void *state,
                                        const uint8_t *in,
                                        uint8_t *out,
                                        size_t data_len);
                                    int OCB_update(void *state,
                                        const uint8_t *in,
                                        size_t data_len);
                                    int OCB_digest(void *state,
                                        uint8_t *tag,
                                        size_t tag_len);
                                    int OCB_stop_operation(void *state);
                                    """)


class OcbMode(object):
    """Offset Codebook (OCB) mode.
Exemplo n.º 57
0
                                  create_string_buffer, get_raw_buffer,
                                  SmartPointer, c_size_t, c_uint8_ptr)

from Cryptodome.Random import get_random_bytes
from Cryptodome.Util.py3compat import byte_string, _copy_bytes
from Cryptodome.Util.number import long_to_bytes

raw_ctr_lib = load_pycryptodome_raw_lib("Cryptodome.Cipher._raw_ctr", """
                    int CTR_start_operation(void *cipher,
                                            uint8_t   initialCounterBlock[],
                                            size_t    initialCounterBlock_len,
                                            size_t    prefix_len,
                                            unsigned  counter_len,
                                            unsigned  littleEndian,
                                            void **pResult);
                    int CTR_encrypt(void *ctrState,
                                    const uint8_t *in,
                                    uint8_t *out,
                                    size_t data_len);
                    int CTR_decrypt(void *ctrState,
                                    const uint8_t *in,
                                    uint8_t *out,
                                    size_t data_len);
                    int CTR_stop_operation(void *ctrState);"""
                                        )


class CtrMode(object):
    """*CounTeR (CTR)* mode.

    This mode is very similar to ECB, in that
    encryption of one block is done independently of all other blocks.
Exemplo n.º 58
0
def _get_ghash_portable():
    api = _ghash_api_template.replace("%imp%", "portable")
    lib = load_pycryptodome_raw_lib("Cryptodome.Hash._ghash_portable", api)
    result = _build_impl(lib, "portable")
    return result