How to use the cryptography.utils.register_interface function in cryptography

To help you get started, we’ve selected a few cryptography examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github aws / lumberyard / dev / Gems / CloudGemFramework / v1 / AWS / common-code / Crypto / cryptography / hazmat / primitives / ciphers / modes.py View on Github external
self._nonce = nonce

    nonce = utils.read_only_property("_nonce")

    def validate_for_algorithm(self, algorithm):
        _check_aes_key_length(self, algorithm)
        if len(self.nonce) * 8 != algorithm.block_size:
            raise ValueError("Invalid nonce size ({0}) for {1}.".format(
                len(self.nonce), self.name
            ))


@utils.register_interface(Mode)
@utils.register_interface(ModeWithInitializationVector)
@utils.register_interface(ModeWithAuthenticationTag)
class GCM(object):
    name = "GCM"
    _MAX_ENCRYPTED_BYTES = (2 ** 39 - 256) // 8
    _MAX_AAD_BYTES = (2 ** 64) // 8

    def __init__(self, initialization_vector, tag=None, min_tag_length=16):
        # len(initialization_vector) must in [1, 2 ** 64), but it's impossible
        # to actually construct a bytes object that large, so we don't check
        # for it
        if not isinstance(initialization_vector, bytes):
            raise TypeError("initialization_vector must be bytes")
        self._initialization_vector = initialization_vector
        if tag is not None:
            if not isinstance(tag, bytes):
                raise TypeError("tag must be bytes or None")
            if min_tag_length < 4:
github pyca / cryptography / src / cryptography / hazmat / backends / openssl / ciphers.py View on Github external
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.

from __future__ import absolute_import, division, print_function

from cryptography import utils
from cryptography.exceptions import InvalidTag, UnsupportedAlgorithm, _Reasons
from cryptography.hazmat.primitives import ciphers
from cryptography.hazmat.primitives.ciphers import modes


@utils.register_interface(ciphers.CipherContext)
@utils.register_interface(ciphers.AEADCipherContext)
@utils.register_interface(ciphers.AEADEncryptionContext)
@utils.register_interface(ciphers.AEADDecryptionContext)
class _CipherContext(object):
    _ENCRYPT = 1
    _DECRYPT = 0

    def __init__(self, backend, cipher, mode, operation):
        self._backend = backend
        self._cipher = cipher
        self._mode = mode
        self._operation = operation
        self._tag = None

        if isinstance(self._cipher, ciphers.BlockCipherAlgorithm):
            self._block_size_bytes = self._cipher.block_size // 8
github aws / lumberyard / dev / Gems / CloudGemFramework / v1 / AWS / common-code / Crypto / cryptography / hazmat / primitives / kdf / x963kdf.py View on Github external
import struct

from cryptography import utils
from cryptography.exceptions import (
    AlreadyFinalized, InvalidKey, UnsupportedAlgorithm, _Reasons
)
from cryptography.hazmat.backends.interfaces import HashBackend
from cryptography.hazmat.primitives import constant_time, hashes
from cryptography.hazmat.primitives.kdf import KeyDerivationFunction


def _int_to_u32be(n):
    return struct.pack('>I', n)


@utils.register_interface(KeyDerivationFunction)
class X963KDF(object):
    def __init__(self, algorithm, length, sharedinfo, backend):

        max_len = algorithm.digest_size * (2 ** 32 - 1)
        if length > max_len:
            raise ValueError(
                "Can not derive keys larger than {0} bits.".format(max_len))
        if not (sharedinfo is None or isinstance(sharedinfo, bytes)):
            raise TypeError("sharedinfo must be bytes.")
        self._algorithm = algorithm
        self._length = length
        self._sharedinfo = sharedinfo

        if not isinstance(backend, HashBackend):
            raise UnsupportedAlgorithm(
                "Backend object does not implement HashBackend.",
github holzschu / Carnets / Library / lib / python3.7 / site-packages / cryptography-2.7-py3.7-macosx-10.9-x86_64.egg / cryptography / hazmat / backends / openssl / rsa.py View on Github external
self._hash_ctx = hashes.Hash(self._algorithm, self._backend)

    def update(self, data):
        self._hash_ctx.update(data)

    def finalize(self):
        return _rsa_sig_sign(
            self._backend,
            self._padding,
            self._algorithm,
            self._private_key,
            self._hash_ctx.finalize()
        )


@utils.register_interface(AsymmetricVerificationContext)
class _RSAVerificationContext(object):
    def __init__(self, backend, public_key, signature, padding, algorithm):
        self._backend = backend
        self._public_key = public_key
        self._signature = signature
        self._padding = padding
        # We now call _rsa_sig_determine_padding in _rsa_sig_setup. However
        # we need to make a pointless call to it here so we maintain the
        # API of erroring on init with this context if the values are invalid.
        _rsa_sig_determine_padding(backend, public_key, padding, algorithm)

        padding = padding
        self._algorithm = algorithm
        self._hash_ctx = hashes.Hash(self._algorithm, self._backend)

    def update(self, data):
github tp4a / teleport / server / www / packages / packages-linux / x64 / cryptography / hazmat / backends / openssl / dsa.py View on Github external
return backend._ffi.buffer(sig_buf)[:buflen[0]]


def _dsa_sig_verify(backend, public_key, signature, data):
    # The first parameter passed to DSA_verify is unused by OpenSSL but
    # must be an integer.
    res = backend._lib.DSA_verify(
        0, data, len(data), signature, len(signature), public_key._dsa_cdata
    )

    if res != 1:
        backend._consume_errors()
        raise InvalidSignature


@utils.register_interface(AsymmetricVerificationContext)
class _DSAVerificationContext(object):
    def __init__(self, backend, public_key, signature, algorithm):
        self._backend = backend
        self._public_key = public_key
        self._signature = signature
        self._algorithm = algorithm

        self._hash_ctx = hashes.Hash(self._algorithm, self._backend)

    def update(self, data):
        self._hash_ctx.update(data)

    def verify(self):
        data_to_verify = self._hash_ctx.finalize()

        _dsa_sig_verify(
github cloudera / hue / desktop / core / ext-py / cryptography-2.1.4 / src / cryptography / hazmat / primitives / asymmetric / ec.py View on Github external
key_size = 384


@utils.register_interface(EllipticCurve)
class SECP256R1(object):
    name = "secp256r1"
    key_size = 256


@utils.register_interface(EllipticCurve)
class SECP256K1(object):
    name = "secp256k1"
    key_size = 256


@utils.register_interface(EllipticCurve)
class SECP224R1(object):
    name = "secp224r1"
    key_size = 224


@utils.register_interface(EllipticCurve)
class SECP192R1(object):
    name = "secp192r1"
    key_size = 192


_CURVE_TYPES = {
    "prime192v1": SECP192R1,
    "prime256v1": SECP256R1,

    "secp192r1": SECP192R1,
github cloudera / hue / desktop / core / ext-py / cryptography-1.1.1 / src / cryptography / hazmat / backends / openssl / backend.py View on Github external
ExtensionOID.CERTIFICATE_POLICIES: _encode_certificate_policies,
    ExtensionOID.AUTHORITY_INFORMATION_ACCESS: (
        _encode_authority_information_access
    ),
    ExtensionOID.CRL_DISTRIBUTION_POINTS: _encode_crl_distribution_points,
    ExtensionOID.INHIBIT_ANY_POLICY: _encode_inhibit_any_policy,
    ExtensionOID.OCSP_NO_CHECK: _encode_ocsp_nocheck,
}


@utils.register_interface(CipherBackend)
@utils.register_interface(CMACBackend)
@utils.register_interface(DERSerializationBackend)
@utils.register_interface(DSABackend)
@utils.register_interface(EllipticCurveBackend)
@utils.register_interface(HashBackend)
@utils.register_interface(HMACBackend)
@utils.register_interface(PBKDF2HMACBackend)
@utils.register_interface(RSABackend)
@utils.register_interface(PEMSerializationBackend)
@utils.register_interface(X509Backend)
class Backend(object):
    """
    OpenSSL API binding interfaces.
    """
    name = "openssl"

    def __init__(self):
        self._binding = binding.Binding()
        self._ffi = self._binding.ffi
        self._lib = self._binding.lib
github pyca / cryptography / src / cryptography / hazmat / backends / commoncrypto / ciphers.py View on Github external
# for complete details.

from __future__ import absolute_import, division, print_function

from cryptography import utils
from cryptography.exceptions import (
    InvalidTag, UnsupportedAlgorithm, _Reasons
)
from cryptography.hazmat.primitives import ciphers, constant_time
from cryptography.hazmat.primitives.ciphers import modes
from cryptography.hazmat.primitives.ciphers.modes import (
    CFB, CFB8, CTR, OFB
)


@utils.register_interface(ciphers.CipherContext)
class _CipherContext(object):
    def __init__(self, backend, cipher, mode, operation):
        self._backend = backend
        self._cipher = cipher
        self._mode = mode
        self._operation = operation
        # There is a bug in CommonCrypto where block ciphers do not raise
        # kCCAlignmentError when finalizing if you supply non-block aligned
        # data. To work around this we need to keep track of the block
        # alignment ourselves, but only for alg+mode combos that require
        # block alignment. OFB, CFB, and CTR make a block cipher algorithm
        # into a stream cipher so we don't need to track them (and thus their
        # block size is effectively 1 byte just like OpenSSL/CommonCrypto
        # treat RC4 and other stream cipher block sizes).
        # This bug has been filed as rdar://15589470
        self._bytes_processed = 0
github holzschu / Carnets / Library / lib / python3.7 / site-packages / cryptography-2.7-py3.7-macosx-10.9-x86_64.egg / cryptography / hazmat / primitives / padding.py View on Github external
return result


class ANSIX923(object):
    def __init__(self, block_size):
        _byte_padding_check(block_size)
        self.block_size = block_size

    def padder(self):
        return _ANSIX923PaddingContext(self.block_size)

    def unpadder(self):
        return _ANSIX923UnpaddingContext(self.block_size)


@utils.register_interface(PaddingContext)
class _ANSIX923PaddingContext(object):
    def __init__(self, block_size):
        self.block_size = block_size
        # TODO: more copies than necessary, we should use zero-buffer (#193)
        self._buffer = b""

    def update(self, data):
        self._buffer, result = _byte_padding_update(
            self._buffer, data, self.block_size)
        return result

    def _padding(self, size):
        return six.int2byte(0) * (size - 1) + six.int2byte(size)

    def finalize(self):
        result = _byte_padding_pad(
github tp4a / teleport / server / www / packages / packages-linux / x64 / cryptography / hazmat / backends / openssl / x25519.py View on Github external
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.

from __future__ import absolute_import, division, print_function

from cryptography import utils
from cryptography.hazmat.primitives.asymmetric.x25519 import (
    X25519PrivateKey, X25519PublicKey
)


@utils.register_interface(X25519PublicKey)
class _X25519PublicKey(object):
    def __init__(self, backend, evp_pkey):
        self._backend = backend
        self._evp_pkey = evp_pkey

    def public_bytes(self):
        ucharpp = self._backend._ffi.new("unsigned char **")
        res = self._backend._lib.EVP_PKEY_get1_tls_encodedpoint(
            self._evp_pkey, ucharpp
        )
        self._backend.openssl_assert(res == 32)
        self._backend.openssl_assert(ucharpp[0] != self._backend._ffi.NULL)
        data = self._backend._ffi.gc(
            ucharpp[0], self._backend._lib.OPENSSL_free
        )
        return self._backend._ffi.buffer(data, res)[:]