Esempio n. 1
0
class DHPublicNumbers(object):
    def __init__(self, y, parameter_numbers):
        if not isinstance(y, six.integer_types):
            raise TypeError("y must be an integer.")

        if not isinstance(parameter_numbers, DHParameterNumbers):
            raise TypeError(
                "parameters must be an instance of DHParameterNumbers."
            )

        self._y = y
        self._parameter_numbers = parameter_numbers

    def __eq__(self, other):
        if not isinstance(other, DHPublicNumbers):
            return NotImplemented

        return (
            self._y == other._y
            and self._parameter_numbers == other._parameter_numbers
        )

    def __ne__(self, other):
        return not self == other

    def public_key(self, backend=None):
        backend = _get_backend(backend)
        return backend.load_dh_public_numbers(self)

    y = utils.read_only_property("_y")
    parameter_numbers = utils.read_only_property("_parameter_numbers")
Esempio n. 2
0
class DHParameterNumbers(object):
    def __init__(self, p, g, q=None):
        if not isinstance(p, six.integer_types) or not isinstance(
            g, six.integer_types
        ):
            raise TypeError("p and g must be integers")
        if q is not None and not isinstance(q, six.integer_types):
            raise TypeError("q must be integer or None")

        if g < 2:
            raise ValueError("DH generator must be 2 or greater")

        self._p = p
        self._g = g
        self._q = q

    def __eq__(self, other):
        if not isinstance(other, DHParameterNumbers):
            return NotImplemented

        return (
            self._p == other._p and self._g == other._g and self._q == other._q
        )

    def __ne__(self, other):
        return not self == other

    def parameters(self, backend=None):
        backend = _get_backend(backend)
        return backend.load_dh_parameter_numbers(self)

    p = utils.read_only_property("_p")
    g = utils.read_only_property("_g")
    q = utils.read_only_property("_q")
Esempio n. 3
0
File: ec.py Progetto: zhzyker/vulmap
class EllipticCurvePrivateNumbers(object):
    def __init__(self, private_value, public_numbers):
        if not isinstance(private_value, six.integer_types):
            raise TypeError("private_value must be an integer.")

        if not isinstance(public_numbers, EllipticCurvePublicNumbers):
            raise TypeError(
                "public_numbers must be an EllipticCurvePublicNumbers "
                "instance.")

        self._private_value = private_value
        self._public_numbers = public_numbers

    def private_key(self, backend=None):
        backend = _get_backend(backend)
        return backend.load_elliptic_curve_private_numbers(self)

    private_value = utils.read_only_property("_private_value")
    public_numbers = utils.read_only_property("_public_numbers")

    def __eq__(self, other):
        if not isinstance(other, EllipticCurvePrivateNumbers):
            return NotImplemented

        return (self.private_value == other.private_value
                and self.public_numbers == other.public_numbers)

    def __ne__(self, other):
        return not self == other

    def __hash__(self):
        return hash((self.private_value, self.public_numbers))
Esempio n. 4
0
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
        utils._check_byteslike("initialization_vector", initialization_vector)
        if len(initialization_vector) == 0:
            raise ValueError("initialization_vector must be at least 1 byte")
        self._initialization_vector = initialization_vector
        if tag is not None:
            utils._check_bytes("tag", tag)
            if min_tag_length < 4:
                raise ValueError("min_tag_length must be >= 4")
            if len(tag) < min_tag_length:
                raise ValueError(
                    "Authentication tag must be {} bytes or longer.".format(
                        min_tag_length))
        self._tag = tag
        self._min_tag_length = min_tag_length

    tag = utils.read_only_property("_tag")
    initialization_vector = utils.read_only_property("_initialization_vector")

    def validate_for_algorithm(self, algorithm):
        _check_aes_key_length(self, algorithm)
Esempio n. 5
0
class OtherName(object):
    def __init__(self, type_id, value):
        if not isinstance(type_id, ObjectIdentifier):
            raise TypeError("type_id must be an ObjectIdentifier")
        if not isinstance(value, bytes):
            raise TypeError("value must be a binary string")

        self._type_id = type_id
        self._value = value

    type_id = utils.read_only_property("_type_id")
    value = utils.read_only_property("_value")

    def __repr__(self):
        return "<OtherName(type_id={}, value={!r})>".format(
            self.type_id, self.value)

    def __eq__(self, other):
        if not isinstance(other, OtherName):
            return NotImplemented

        return self.type_id == other.type_id and self.value == other.value

    def __ne__(self, other):
        return not self == other

    def __hash__(self):
        return hash((self.type_id, self.value))
Esempio n. 6
0
class DSAPrivateNumbers(object):
    def __init__(self, x, public_numbers):
        if not isinstance(x, six.integer_types):
            raise TypeError("DSAPrivateNumbers x argument must be an integer.")

        if not isinstance(public_numbers, DSAPublicNumbers):
            raise TypeError(
                "public_numbers must be a DSAPublicNumbers instance."
            )
        self._public_numbers = public_numbers
        self._x = x

    x = utils.read_only_property("_x")
    public_numbers = utils.read_only_property("_public_numbers")

    def private_key(self, backend=None):
        backend = _get_backend(backend)
        return backend.load_dsa_private_numbers(self)

    def __eq__(self, other):
        if not isinstance(other, DSAPrivateNumbers):
            return NotImplemented

        return (
            self.x == other.x and self.public_numbers == other.public_numbers
        )

    def __ne__(self, other):
        return not self == other
Esempio n. 7
0
class RSAPublicNumbers(object):
    def __init__(self, e, n):
        if not isinstance(e, six.integer_types) or not isinstance(
                n, six.integer_types):
            raise TypeError("RSAPublicNumbers arguments must be integers.")

        self._e = e
        self._n = n

    e = utils.read_only_property("_e")
    n = utils.read_only_property("_n")

    def public_key(self, backend=None):
        backend = _get_backend(backend)
        return backend.load_rsa_public_numbers(self)

    def __repr__(self):
        return "<RSAPublicNumbers(e={0.e}, n={0.n})>".format(self)

    def __eq__(self, other):
        if not isinstance(other, RSAPublicNumbers):
            return NotImplemented

        return self.e == other.e and self.n == other.n

    def __ne__(self, other):
        return not self == other

    def __hash__(self):
        return hash((self.e, self.n))
Esempio n. 8
0
class NameAttribute(object):
    def __init__(self, oid, value, _type=_SENTINEL):
        if not isinstance(oid, ObjectIdentifier):
            raise TypeError(
                "oid argument must be an ObjectIdentifier instance.")

        if not isinstance(value, six.text_type):
            raise TypeError("value argument must be a text type.")

        if (oid == NameOID.COUNTRY_NAME
                or oid == NameOID.JURISDICTION_COUNTRY_NAME):
            if len(value.encode("utf8")) != 2:
                raise ValueError(
                    "Country name must be a 2 character country code")

        # The appropriate ASN1 string type varies by OID and is defined across
        # multiple RFCs including 2459, 3280, and 5280. In general UTF8String
        # is preferred (2459), but 3280 and 5280 specify several OIDs with
        # alternate types. This means when we see the sentinel value we need
        # to look up whether the OID has a non-UTF8 type. If it does, set it
        # to that. Otherwise, UTF8!
        if _type == _SENTINEL:
            _type = _NAMEOID_DEFAULT_TYPE.get(oid, _ASN1Type.UTF8String)

        if not isinstance(_type, _ASN1Type):
            raise TypeError("_type must be from the _ASN1Type enum")

        self._oid = oid
        self._value = value
        self._type = _type

    oid = utils.read_only_property("_oid")
    value = utils.read_only_property("_value")

    def rfc4514_string(self):
        """
        Format as RFC4514 Distinguished Name string.

        Use short attribute name if available, otherwise fall back to OID
        dotted string.
        """
        key = _NAMEOID_TO_NAME.get(self.oid, self.oid.dotted_string)
        return "%s=%s" % (key, _escape_dn_value(self.value))

    def __eq__(self, other):
        if not isinstance(other, NameAttribute):
            return NotImplemented

        return self.oid == other.oid and self.value == other.value

    def __ne__(self, other):
        return not self == other

    def __hash__(self):
        return hash((self.oid, self.value))

    def __repr__(self):
        return "<NameAttribute(oid={0.oid}, value={0.value!r})>".format(self)
Esempio n. 9
0
class _OpenSSLError(object):
    def __init__(self, code, lib, func, reason):
        self._code = code
        self._lib = lib
        self._func = func
        self._reason = reason

    def _lib_reason_match(self, lib, reason):
        return lib == self.lib and reason == self.reason

    code = utils.read_only_property("_code")
    lib = utils.read_only_property("_lib")
    func = utils.read_only_property("_func")
    reason = utils.read_only_property("_reason")
Esempio n. 10
0
class IPAddress(object):
    def __init__(self, value):
        if not isinstance(
                value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network,
            ),
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network")

        self._value = value

    value = utils.read_only_property("_value")

    def __repr__(self):
        return "<IPAddress(value={})>".format(self.value)

    def __eq__(self, other):
        if not isinstance(other, IPAddress):
            return NotImplemented

        return self.value == other.value

    def __ne__(self, other):
        return not self == other

    def __hash__(self):
        return hash(self.value)
Esempio n. 11
0
class ObjectIdentifier(object):
    def __init__(self, dotted_string):
        self._dotted_string = dotted_string

        nodes = self._dotted_string.split(".")
        intnodes = []

        # There must be at least 2 nodes, the first node must be 0..2, and
        # if less than 2, the second node cannot have a value outside the
        # range 0..39.  All nodes must be integers.
        for node in nodes:
            try:
                node_value = int(node, 10)
            except ValueError:
                raise ValueError("Malformed OID: %s (non-integer nodes)" %
                                 (self._dotted_string))
            if node_value < 0:
                raise ValueError("Malformed OID: %s (negative-integer nodes)" %
                                 (self._dotted_string))
            intnodes.append(node_value)

        if len(nodes) < 2:
            raise ValueError(
                "Malformed OID: %s (insufficient number of nodes)" %
                (self._dotted_string))

        if intnodes[0] > 2:
            raise ValueError(
                "Malformed OID: %s (first node outside valid range)" %
                (self._dotted_string))

        if intnodes[0] < 2 and intnodes[1] >= 40:
            raise ValueError(
                "Malformed OID: %s (second node outside valid range)" %
                (self._dotted_string))

    def __eq__(self, other):
        if not isinstance(other, ObjectIdentifier):
            return NotImplemented

        return self.dotted_string == other.dotted_string

    def __ne__(self, other):
        return not self == other

    def __repr__(self):
        return "<ObjectIdentifier(oid={}, name={})>".format(
            self.dotted_string, self._name)

    def __hash__(self):
        return hash(self.dotted_string)

    @property
    def _name(self):
        # Lazy import to avoid an import cycle
        from thirdparty.cryptography.x509.oid import _OID_NAMES

        return _OID_NAMES.get(self, "Unknown OID")

    dotted_string = utils.read_only_property("_dotted_string")
Esempio n. 12
0
class _HashContext(object):
    def __init__(self, backend, algorithm, ctx=None):
        self._algorithm = algorithm

        self._backend = backend

        if ctx is None:
            ctx = self._backend._lib.Cryptography_EVP_MD_CTX_new()
            ctx = self._backend._ffi.gc(
                ctx, self._backend._lib.Cryptography_EVP_MD_CTX_free)
            evp_md = self._backend._evp_md_from_algorithm(algorithm)
            if evp_md == self._backend._ffi.NULL:
                raise UnsupportedAlgorithm(
                    "{} is not a supported hash on this backend.".format(
                        algorithm.name),
                    _Reasons.UNSUPPORTED_HASH,
                )
            res = self._backend._lib.EVP_DigestInit_ex(ctx, evp_md,
                                                       self._backend._ffi.NULL)
            self._backend.openssl_assert(res != 0)

        self._ctx = ctx

    algorithm = utils.read_only_property("_algorithm")

    def copy(self):
        copied_ctx = self._backend._lib.Cryptography_EVP_MD_CTX_new()
        copied_ctx = self._backend._ffi.gc(
            copied_ctx, self._backend._lib.Cryptography_EVP_MD_CTX_free)
        res = self._backend._lib.EVP_MD_CTX_copy_ex(copied_ctx, self._ctx)
        self._backend.openssl_assert(res != 0)
        return _HashContext(self._backend, self.algorithm, ctx=copied_ctx)

    def update(self, data):
        data_ptr = self._backend._ffi.from_buffer(data)
        res = self._backend._lib.EVP_DigestUpdate(self._ctx, data_ptr,
                                                  len(data))
        self._backend.openssl_assert(res != 0)

    def finalize(self):
        if isinstance(self.algorithm, hashes.ExtendableOutputFunction):
            # extendable output functions use a different finalize
            return self._finalize_xof()
        else:
            buf = self._backend._ffi.new("unsigned char[]",
                                         self._backend._lib.EVP_MAX_MD_SIZE)
            outlen = self._backend._ffi.new("unsigned int *")
            res = self._backend._lib.EVP_DigestFinal_ex(self._ctx, buf, outlen)
            self._backend.openssl_assert(res != 0)
            self._backend.openssl_assert(
                outlen[0] == self.algorithm.digest_size)
            return self._backend._ffi.buffer(buf)[:outlen[0]]

    def _finalize_xof(self):
        buf = self._backend._ffi.new("unsigned char[]",
                                     self.algorithm.digest_size)
        res = self._backend._lib.EVP_DigestFinalXOF(self._ctx, buf,
                                                    self.algorithm.digest_size)
        self._backend.openssl_assert(res != 0)
        return self._backend._ffi.buffer(buf)[:self.algorithm.digest_size]
Esempio n. 13
0
class _HMACContext(object):
    def __init__(self, backend, key, algorithm, ctx=None):
        self._algorithm = algorithm
        self._backend = backend

        if ctx is None:
            ctx = self._backend._lib.Cryptography_HMAC_CTX_new()
            self._backend.openssl_assert(ctx != self._backend._ffi.NULL)
            ctx = self._backend._ffi.gc(
                ctx, self._backend._lib.Cryptography_HMAC_CTX_free)
            evp_md = self._backend._evp_md_from_algorithm(algorithm)
            if evp_md == self._backend._ffi.NULL:
                raise UnsupportedAlgorithm(
                    "{} is not a supported hash on this backend".format(
                        algorithm.name),
                    _Reasons.UNSUPPORTED_HASH,
                )
            key_ptr = self._backend._ffi.from_buffer(key)
            res = self._backend._lib.HMAC_Init_ex(ctx, key_ptr, len(key),
                                                  evp_md,
                                                  self._backend._ffi.NULL)
            self._backend.openssl_assert(res != 0)

        self._ctx = ctx
        self._key = key

    algorithm = utils.read_only_property("_algorithm")

    def copy(self):
        copied_ctx = self._backend._lib.Cryptography_HMAC_CTX_new()
        self._backend.openssl_assert(copied_ctx != self._backend._ffi.NULL)
        copied_ctx = self._backend._ffi.gc(
            copied_ctx, self._backend._lib.Cryptography_HMAC_CTX_free)
        res = self._backend._lib.HMAC_CTX_copy(copied_ctx, self._ctx)
        self._backend.openssl_assert(res != 0)
        return _HMACContext(self._backend,
                            self._key,
                            self.algorithm,
                            ctx=copied_ctx)

    def update(self, data):
        data_ptr = self._backend._ffi.from_buffer(data)
        res = self._backend._lib.HMAC_Update(self._ctx, data_ptr, len(data))
        self._backend.openssl_assert(res != 0)

    def finalize(self):
        buf = self._backend._ffi.new("unsigned char[]",
                                     self._backend._lib.EVP_MAX_MD_SIZE)
        outlen = self._backend._ffi.new("unsigned int *")
        res = self._backend._lib.HMAC_Final(self._ctx, buf, outlen)
        self._backend.openssl_assert(res != 0)
        self._backend.openssl_assert(outlen[0] == self.algorithm.digest_size)
        return self._backend._ffi.buffer(buf)[:outlen[0]]

    def verify(self, signature):
        digest = self.finalize()
        if not constant_time.bytes_eq(digest, signature):
            raise InvalidSignature("Signature did not match digest.")
Esempio n. 14
0
class Prehashed(object):
    def __init__(self, algorithm):
        if not isinstance(algorithm, hashes.HashAlgorithm):
            raise TypeError("Expected instance of HashAlgorithm.")

        self._algorithm = algorithm
        self._digest_size = algorithm.digest_size

    digest_size = utils.read_only_property("_digest_size")
Esempio n. 15
0
class CBC(object):
    name = "CBC"

    def __init__(self, initialization_vector):
        utils._check_byteslike("initialization_vector", initialization_vector)
        self._initialization_vector = initialization_vector

    initialization_vector = utils.read_only_property("_initialization_vector")
    validate_for_algorithm = _check_iv_and_key_length
Esempio n. 16
0
class RSAPrivateNumbers(object):
    def __init__(self, p, q, d, dmp1, dmq1, iqmp, public_numbers):
        if (not isinstance(p, six.integer_types)
                or not isinstance(q, six.integer_types)
                or not isinstance(d, six.integer_types)
                or not isinstance(dmp1, six.integer_types)
                or not isinstance(dmq1, six.integer_types)
                or not isinstance(iqmp, six.integer_types)):
            raise TypeError(
                "RSAPrivateNumbers p, q, d, dmp1, dmq1, iqmp arguments must"
                " all be an integers.")

        if not isinstance(public_numbers, RSAPublicNumbers):
            raise TypeError(
                "RSAPrivateNumbers public_numbers must be an RSAPublicNumbers"
                " instance.")

        self._p = p
        self._q = q
        self._d = d
        self._dmp1 = dmp1
        self._dmq1 = dmq1
        self._iqmp = iqmp
        self._public_numbers = public_numbers

    p = utils.read_only_property("_p")
    q = utils.read_only_property("_q")
    d = utils.read_only_property("_d")
    dmp1 = utils.read_only_property("_dmp1")
    dmq1 = utils.read_only_property("_dmq1")
    iqmp = utils.read_only_property("_iqmp")
    public_numbers = utils.read_only_property("_public_numbers")

    def private_key(self, backend=None):
        backend = _get_backend(backend)
        return backend.load_rsa_private_numbers(self)

    def __eq__(self, other):
        if not isinstance(other, RSAPrivateNumbers):
            return NotImplemented

        return (self.p == other.p and self.q == other.q and self.d == other.d
                and self.dmp1 == other.dmp1 and self.dmq1 == other.dmq1
                and self.iqmp == other.iqmp
                and self.public_numbers == other.public_numbers)

    def __ne__(self, other):
        return not self == other

    def __hash__(self):
        return hash((
            self.p,
            self.q,
            self.d,
            self.dmp1,
            self.dmq1,
            self.iqmp,
            self.public_numbers,
        ))
Esempio n. 17
0
class HMAC(object):
    def __init__(self, key, algorithm, backend=None, ctx=None):
        backend = _get_backend(backend)
        if not isinstance(backend, HMACBackend):
            raise UnsupportedAlgorithm(
                "Backend object does not implement HMACBackend.",
                _Reasons.BACKEND_MISSING_INTERFACE,
            )

        if not isinstance(algorithm, hashes.HashAlgorithm):
            raise TypeError("Expected instance of hashes.HashAlgorithm.")
        self._algorithm = algorithm

        self._backend = backend
        self._key = key
        if ctx is None:
            self._ctx = self._backend.create_hmac_ctx(key, self.algorithm)
        else:
            self._ctx = ctx

    algorithm = utils.read_only_property("_algorithm")

    def update(self, data):
        if self._ctx is None:
            raise AlreadyFinalized("Context was already finalized.")
        utils._check_byteslike("data", data)
        self._ctx.update(data)

    def copy(self):
        if self._ctx is None:
            raise AlreadyFinalized("Context was already finalized.")
        return HMAC(
            self._key,
            self.algorithm,
            backend=self._backend,
            ctx=self._ctx.copy(),
        )

    def finalize(self):
        if self._ctx is None:
            raise AlreadyFinalized("Context was already finalized.")
        digest = self._ctx.finalize()
        self._ctx = None
        return digest

    def verify(self, signature):
        utils._check_bytes("signature", signature)
        if self._ctx is None:
            raise AlreadyFinalized("Context was already finalized.")

        ctx, self._ctx = self._ctx, None
        ctx.verify(signature)
Esempio n. 18
0
class SHAKE256(object):
    name = "shake256"

    def __init__(self, digest_size):
        if not isinstance(digest_size, six.integer_types):
            raise TypeError("digest_size must be an integer")

        if digest_size < 1:
            raise ValueError("digest_size must be a positive integer")

        self._digest_size = digest_size

    digest_size = utils.read_only_property("_digest_size")
Esempio n. 19
0
class CTR(object):
    name = "CTR"

    def __init__(self, nonce):
        utils._check_byteslike("nonce", nonce)
        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 ({}) for {}.".format(
                len(self.nonce), self.name))
Esempio n. 20
0
class _RSAPublicKey(object):
    def __init__(self, backend, rsa_cdata, evp_pkey):
        self._backend = backend
        self._rsa_cdata = rsa_cdata
        self._evp_pkey = evp_pkey

        n = self._backend._ffi.new("BIGNUM **")
        self._backend._lib.RSA_get0_key(
            self._rsa_cdata,
            n,
            self._backend._ffi.NULL,
            self._backend._ffi.NULL,
        )
        self._backend.openssl_assert(n[0] != self._backend._ffi.NULL)
        self._key_size = self._backend._lib.BN_num_bits(n[0])

    key_size = utils.read_only_property("_key_size")

    def verifier(self, signature, padding, algorithm):
        _warn_sign_verify_deprecated()
        utils._check_bytes("signature", signature)

        _check_not_prehashed(algorithm)
        return _RSAVerificationContext(self._backend, self, signature, padding,
                                       algorithm)

    def encrypt(self, plaintext, padding):
        return _enc_dec_rsa(self._backend, self, plaintext, padding)

    def public_numbers(self):
        n = self._backend._ffi.new("BIGNUM **")
        e = self._backend._ffi.new("BIGNUM **")
        self._backend._lib.RSA_get0_key(self._rsa_cdata, n, e,
                                        self._backend._ffi.NULL)
        self._backend.openssl_assert(n[0] != self._backend._ffi.NULL)
        self._backend.openssl_assert(e[0] != self._backend._ffi.NULL)
        return rsa.RSAPublicNumbers(
            e=self._backend._bn_to_int(e[0]),
            n=self._backend._bn_to_int(n[0]),
        )

    def public_bytes(self, encoding, format):
        return self._backend._public_key_bytes(encoding, format, self,
                                               self._evp_pkey, self._rsa_cdata)

    def verify(self, signature, data, padding, algorithm):
        data, algorithm = _calculate_digest_and_algorithm(
            self._backend, data, algorithm)
        return _rsa_sig_verify(self._backend, padding, algorithm, self,
                               signature, data)
Esempio n. 21
0
class BLAKE2b(object):
    name = "blake2b"
    _max_digest_size = 64
    _min_digest_size = 1
    block_size = 128

    def __init__(self, digest_size):

        if digest_size != 64:
            raise ValueError("Digest size must be 64")

        self._digest_size = digest_size

    digest_size = utils.read_only_property("_digest_size")
Esempio n. 22
0
class BLAKE2s(object):
    name = "blake2s"
    block_size = 64
    _max_digest_size = 32
    _min_digest_size = 1

    def __init__(self, digest_size):

        if digest_size != 32:
            raise ValueError("Digest size must be 32")

        self._digest_size = digest_size

    digest_size = utils.read_only_property("_digest_size")
Esempio n. 23
0
class DSAParameterNumbers(object):
    def __init__(self, p, q, g):
        if (
            not isinstance(p, six.integer_types)
            or not isinstance(q, six.integer_types)
            or not isinstance(g, six.integer_types)
        ):
            raise TypeError(
                "DSAParameterNumbers p, q, and g arguments must be integers."
            )

        self._p = p
        self._q = q
        self._g = g

    p = utils.read_only_property("_p")
    q = utils.read_only_property("_q")
    g = utils.read_only_property("_g")

    def parameters(self, backend=None):
        backend = _get_backend(backend)
        return backend.load_dsa_parameter_numbers(self)

    def __eq__(self, other):
        if not isinstance(other, DSAParameterNumbers):
            return NotImplemented

        return self.p == other.p and self.q == other.q and self.g == other.g

    def __ne__(self, other):
        return not self == other

    def __repr__(self):
        return (
            "<DSAParameterNumbers(p={self.p}, q={self.q}, "
            "g={self.g})>".format(self=self)
        )
Esempio n. 24
0
class DSAPublicNumbers(object):
    def __init__(self, y, parameter_numbers):
        if not isinstance(y, six.integer_types):
            raise TypeError("DSAPublicNumbers y argument must be an integer.")

        if not isinstance(parameter_numbers, DSAParameterNumbers):
            raise TypeError(
                "parameter_numbers must be a DSAParameterNumbers instance."
            )

        self._y = y
        self._parameter_numbers = parameter_numbers

    y = utils.read_only_property("_y")
    parameter_numbers = utils.read_only_property("_parameter_numbers")

    def public_key(self, backend=None):
        backend = _get_backend(backend)
        return backend.load_dsa_public_numbers(self)

    def __eq__(self, other):
        if not isinstance(other, DSAPublicNumbers):
            return NotImplemented

        return (
            self.y == other.y
            and self.parameter_numbers == other.parameter_numbers
        )

    def __ne__(self, other):
        return not self == other

    def __repr__(self):
        return (
            "<DSAPublicNumbers(y={self.y}, "
            "parameter_numbers={self.parameter_numbers})>".format(self=self)
        )
Esempio n. 25
0
class ChaCha20(object):
    name = "ChaCha20"
    key_sizes = frozenset([256])

    def __init__(self, key, nonce):
        self.key = _verify_key_size(self, key)
        utils._check_byteslike("nonce", nonce)

        if len(nonce) != 16:
            raise ValueError("nonce must be 128-bits (16 bytes)")

        self._nonce = nonce

    nonce = utils.read_only_property("_nonce")

    @property
    def key_size(self):
        return len(self.key) * 8
Esempio n. 26
0
class XTS(object):
    name = "XTS"

    def __init__(self, tweak):
        utils._check_byteslike("tweak", tweak)

        if len(tweak) != 16:
            raise ValueError("tweak must be 128-bits (16 bytes)")

        self._tweak = tweak

    tweak = utils.read_only_property("_tweak")

    def validate_for_algorithm(self, algorithm):
        if algorithm.key_size not in (256, 512):
            raise ValueError(
                "The XTS specification requires a 256-bit key for AES-128-XTS"
                " and 512-bit key for AES-256-XTS")
Esempio n. 27
0
class RFC822Name(object):
    def __init__(self, value):
        if isinstance(value, six.text_type):
            try:
                value.encode("ascii")
            except UnicodeEncodeError:
                raise ValueError(
                    "RFC822Name values should be passed as an A-label string. "
                    "This means unicode characters should be encoded via "
                    "a library like idna.")
        else:
            raise TypeError("value must be string")

        name, address = parseaddr(value)
        if name or not address:
            # parseaddr has found a name (e.g. Name <email>) or the entire
            # value is an empty string.
            raise ValueError("Invalid rfc822name value")

        self._value = value

    value = utils.read_only_property("_value")

    @classmethod
    def _init_without_validation(cls, value):
        instance = cls.__new__(cls)
        instance._value = value
        return instance

    def __repr__(self):
        return "<RFC822Name(value={0!r})>".format(self.value)

    def __eq__(self, other):
        if not isinstance(other, RFC822Name):
            return NotImplemented

        return self.value == other.value

    def __ne__(self, other):
        return not self == other

    def __hash__(self):
        return hash(self.value)
Esempio n. 28
0
class RegisteredID(object):
    def __init__(self, value):
        if not isinstance(value, ObjectIdentifier):
            raise TypeError("value must be an ObjectIdentifier")

        self._value = value

    value = utils.read_only_property("_value")

    def __repr__(self):
        return "<RegisteredID(value={})>".format(self.value)

    def __eq__(self, other):
        if not isinstance(other, RegisteredID):
            return NotImplemented

        return self.value == other.value

    def __ne__(self, other):
        return not self == other

    def __hash__(self):
        return hash(self.value)
Esempio n. 29
0
class DirectoryName(object):
    def __init__(self, value):
        if not isinstance(value, Name):
            raise TypeError("value must be a Name")

        self._value = value

    value = utils.read_only_property("_value")

    def __repr__(self):
        return "<DirectoryName(value={})>".format(self.value)

    def __eq__(self, other):
        if not isinstance(other, DirectoryName):
            return NotImplemented

        return self.value == other.value

    def __ne__(self, other):
        return not self == other

    def __hash__(self):
        return hash(self.value)
Esempio n. 30
0
class DNSName(object):
    def __init__(self, value):
        if isinstance(value, six.text_type):
            try:
                value.encode("ascii")
            except UnicodeEncodeError:
                raise ValueError(
                    "DNSName values should be passed as an A-label string. "
                    "This means unicode characters should be encoded via "
                    "a library like idna.")
        else:
            raise TypeError("value must be string")

        self._value = value

    value = utils.read_only_property("_value")

    @classmethod
    def _init_without_validation(cls, value):
        instance = cls.__new__(cls)
        instance._value = value
        return instance

    def __repr__(self):
        return "<DNSName(value={0!r})>".format(self.value)

    def __eq__(self, other):
        if not isinstance(other, DNSName):
            return NotImplemented

        return self.value == other.value

    def __ne__(self, other):
        return not self == other

    def __hash__(self):
        return hash(self.value)