Ejemplo n.º 1
0
    def __init__(self, algorithm, length, info, backend=None):
        backend = _get_backend(backend)
        if not isinstance(backend, HMACBackend):
            raise UnsupportedAlgorithm(
                "Backend object does not implement HMACBackend.",
                _Reasons.BACKEND_MISSING_INTERFACE,
            )

        self._algorithm = algorithm

        self._backend = backend

        max_length = 255 * algorithm.digest_size

        if length > max_length:
            raise ValueError(
                "Can not derive keys larger than {} octets.".format(
                    max_length))

        self._length = length

        if info is None:
            info = b""
        else:
            utils._check_bytes("info", info)

        self._info = info

        self._used = False
Ejemplo n.º 2
0
    def __init__(self, salt, length, n, r, p, backend=None):
        backend = _get_backend(backend)
        if not isinstance(backend, ScryptBackend):
            raise UnsupportedAlgorithm(
                "Backend object does not implement ScryptBackend.",
                _Reasons.BACKEND_MISSING_INTERFACE,
            )

        self._length = length
        utils._check_bytes("salt", salt)
        if n < 2 or (n & (n - 1)) != 0:
            raise ValueError("n must be greater than 1 and be a power of 2.")

        if r < 1:
            raise ValueError("r must be greater than or equal to 1.")

        if p < 1:
            raise ValueError("p must be greater than or equal to 1.")

        self._used = False
        self._salt = salt
        self._n = n
        self._r = r
        self._p = p
        self._backend = backend
Ejemplo n.º 3
0
    def __init__(self,
                 key,
                 length,
                 algorithm,
                 backend=None,
                 enforce_key_length=True):
        backend = _get_backend(backend)
        if not isinstance(backend, HMACBackend):
            raise UnsupportedAlgorithm(
                "Backend object does not implement HMACBackend.",
                _Reasons.BACKEND_MISSING_INTERFACE,
            )

        if len(key) < 16 and enforce_key_length is True:
            raise ValueError("Key length has to be at least 128 bits.")

        if not isinstance(length, six.integer_types):
            raise TypeError("Length parameter must be an integer type.")

        if length < 6 or length > 8:
            raise ValueError("Length of HOTP has to be between 6 to 8.")

        if not isinstance(algorithm, (SHA1, SHA256, SHA512)):
            raise TypeError("Algorithm must be SHA1, SHA256 or SHA512.")

        self._key = key
        self._length = length
        self._algorithm = algorithm
        self._backend = backend
Ejemplo n.º 4
0
def serialize_key_and_certificates(name, key, cert, cas, encryption_algorithm):
    if key is not None and not isinstance(
            key,
        (
            rsa.RSAPrivateKeyWithSerialization,
            dsa.DSAPrivateKeyWithSerialization,
            ec.EllipticCurvePrivateKeyWithSerialization,
        ),
    ):
        raise TypeError("Key must be RSA, DSA, or EllipticCurve private key.")
    if cert is not None and not isinstance(cert, x509.Certificate):
        raise TypeError("cert must be a certificate")

    if cas is not None:
        cas = list(cas)
        if not all(isinstance(val, x509.Certificate) for val in cas):
            raise TypeError("all values in cas must be certificates")

    if not isinstance(encryption_algorithm,
                      serialization.KeySerializationEncryption):
        raise TypeError("Key encryption algorithm must be a "
                        "KeySerializationEncryption instance")

    if key is None and cert is None and not cas:
        raise ValueError("You must supply at least one of key, cert, or cas")

    backend = _get_backend(None)
    return backend.serialize_key_and_certificates_to_pkcs12(
        name, key, cert, cas, encryption_algorithm)
Ejemplo n.º 5
0
 def sign(self, private_key, algorithm, backend=None):
     """
     Signs the request using the requestor's private key.
     """
     backend = _get_backend(backend)
     if self._subject_name is None:
         raise ValueError("A CertificateSigningRequest must have a subject")
     return backend.create_x509_csr(self, private_key, algorithm)
Ejemplo n.º 6
0
    def build(self, backend=None):
        backend = _get_backend(backend)
        if self._serial_number is None:
            raise ValueError("A revoked certificate must have a serial number")
        if self._revocation_date is None:
            raise ValueError(
                "A revoked certificate must have a revocation date")

        return backend.create_x509_revoked_certificate(self)
Ejemplo n.º 7
0
def generate_private_key(public_exponent, key_size, backend=None):
    backend = _get_backend(backend)
    if not isinstance(backend, RSABackend):
        raise UnsupportedAlgorithm(
            "Backend object does not implement RSABackend.",
            _Reasons.BACKEND_MISSING_INTERFACE,
        )

    _verify_rsa_parameters(public_exponent, key_size)
    return backend.generate_rsa_private_key(public_exponent, key_size)
Ejemplo n.º 8
0
    def __init__(self, key, backend=None):
        backend = _get_backend(backend)

        key = base64.urlsafe_b64decode(key)
        if len(key) != 32:
            raise ValueError(
                "Fernet key must be 32 url-safe base64-encoded bytes.")

        self._signing_key = key[:16]
        self._encryption_key = key[16:]
        self._backend = backend
Ejemplo n.º 9
0
Archivo: ec.py Proyecto: zhzyker/vulmap
def derive_private_key(private_value, curve, backend=None):
    backend = _get_backend(backend)
    if not isinstance(private_value, six.integer_types):
        raise TypeError("private_value must be an integer type.")

    if private_value <= 0:
        raise ValueError("private_value must be a positive integer.")

    if not isinstance(curve, EllipticCurve):
        raise TypeError("curve must provide the EllipticCurve interface.")

    return backend.derive_elliptic_curve_private_key(private_value, curve)
Ejemplo n.º 10
0
    def sign(self, private_key, algorithm, backend=None):
        backend = _get_backend(backend)
        if self._issuer_name is None:
            raise ValueError("A CRL must have an issuer name")

        if self._last_update is None:
            raise ValueError("A CRL must have a last update time")

        if self._next_update is None:
            raise ValueError("A CRL must have a next update time")

        return backend.create_x509_crl(self, private_key, algorithm)
Ejemplo n.º 11
0
def aes_key_wrap(wrapping_key, key_to_wrap, backend=None):
    backend = _get_backend(backend)
    if len(wrapping_key) not in [16, 24, 32]:
        raise ValueError("The wrapping key must be a valid AES key length")

    if len(key_to_wrap) < 16:
        raise ValueError("The key to wrap must be at least 16 bytes")

    if len(key_to_wrap) % 8 != 0:
        raise ValueError("The key to wrap must be a multiple of 8 bytes")

    a = b"\xa6\xa6\xa6\xa6\xa6\xa6\xa6\xa6"
    r = [key_to_wrap[i:i + 8] for i in range(0, len(key_to_wrap), 8)]
    return _wrap_core(wrapping_key, a, r, backend)
Ejemplo n.º 12
0
    def __init__(self, algorithm, mode, backend=None):
        backend = _get_backend(backend)
        if not isinstance(backend, CipherBackend):
            raise UnsupportedAlgorithm(
                "Backend object does not implement CipherBackend.",
                _Reasons.BACKEND_MISSING_INTERFACE,
            )

        if not isinstance(algorithm, CipherAlgorithm):
            raise TypeError("Expected interface of CipherAlgorithm.")

        if mode is not None:
            mode.validate_for_algorithm(algorithm)

        self.algorithm = algorithm
        self.mode = mode
        self._backend = backend
Ejemplo n.º 13
0
    def __init__(self, algorithm, length, otherinfo, backend=None):
        backend = _get_backend(backend)

        _common_args_checks(algorithm, length, otherinfo)
        self._algorithm = algorithm
        self._length = length
        self._otherinfo = otherinfo
        if self._otherinfo is None:
            self._otherinfo = b""

        if not isinstance(backend, HashBackend):
            raise UnsupportedAlgorithm(
                "Backend object does not implement HashBackend.",
                _Reasons.BACKEND_MISSING_INTERFACE,
            )
        self._backend = backend
        self._used = False
Ejemplo n.º 14
0
    def __init__(self, algorithm, backend=None, ctx=None):
        backend = _get_backend(backend)
        if not isinstance(backend, CMACBackend):
            raise UnsupportedAlgorithm(
                "Backend object does not implement CMACBackend.",
                _Reasons.BACKEND_MISSING_INTERFACE,
            )

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

        self._backend = backend
        if ctx is None:
            self._ctx = self._backend.create_cmac_ctx(self._algorithm)
        else:
            self._ctx = ctx
Ejemplo n.º 15
0
    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
Ejemplo n.º 16
0
    def __init__(
        self,
        key,
        length,
        algorithm,
        time_step,
        backend=None,
        enforce_key_length=True,
    ):
        backend = _get_backend(backend)
        if not isinstance(backend, HMACBackend):
            raise UnsupportedAlgorithm(
                "Backend object does not implement HMACBackend.",
                _Reasons.BACKEND_MISSING_INTERFACE,
            )

        self._time_step = time_step
        self._hotp = HOTP(key, length, algorithm, backend, enforce_key_length)
Ejemplo n.º 17
0
def aes_key_wrap_with_padding(wrapping_key, key_to_wrap, backend=None):
    backend = _get_backend(backend)
    if len(wrapping_key) not in [16, 24, 32]:
        raise ValueError("The wrapping key must be a valid AES key length")

    aiv = b"\xA6\x59\x59\xA6" + struct.pack(">i", len(key_to_wrap))
    # pad the key to wrap if necessary
    pad = (8 - (len(key_to_wrap) % 8)) % 8
    key_to_wrap = key_to_wrap + b"\x00" * pad
    if len(key_to_wrap) == 8:
        # RFC 5649 - 4.1 - exactly 8 octets after padding
        encryptor = Cipher(AES(wrapping_key), ECB(), backend).encryptor()
        b = encryptor.update(aiv + key_to_wrap)
        assert encryptor.finalize() == b""
        return b
    else:
        r = [key_to_wrap[i:i + 8] for i in range(0, len(key_to_wrap), 8)]
        return _wrap_core(wrapping_key, aiv, r, backend)
Ejemplo n.º 18
0
def aes_key_unwrap(wrapping_key, wrapped_key, backend=None):
    backend = _get_backend(backend)
    if len(wrapped_key) < 24:
        raise InvalidUnwrap("Must be at least 24 bytes")

    if len(wrapped_key) % 8 != 0:
        raise InvalidUnwrap("The wrapped key must be a multiple of 8 bytes")

    if len(wrapping_key) not in [16, 24, 32]:
        raise ValueError("The wrapping key must be a valid AES key length")

    aiv = b"\xa6\xa6\xa6\xa6\xa6\xa6\xa6\xa6"
    r = [wrapped_key[i:i + 8] for i in range(0, len(wrapped_key), 8)]
    a = r.pop(0)
    a, r = _unwrap_core(wrapping_key, a, r, backend)
    if not bytes_eq(a, aiv):
        raise InvalidUnwrap()

    return b"".join(r)
Ejemplo n.º 19
0
    def __init__(self, algorithm, length, salt, info, backend=None):
        backend = _get_backend(backend)
        if not isinstance(backend, HMACBackend):
            raise UnsupportedAlgorithm(
                "Backend object does not implement HMACBackend.",
                _Reasons.BACKEND_MISSING_INTERFACE,
            )

        self._algorithm = algorithm

        if salt is None:
            salt = b"\x00" * self._algorithm.digest_size
        else:
            utils._check_bytes("salt", salt)

        self._salt = salt

        self._backend = backend

        self._hkdf_expand = HKDFExpand(self._algorithm, length, info, backend)
Ejemplo n.º 20
0
    def __init__(self, algorithm, length, sharedinfo, backend=None):
        backend = _get_backend(backend)

        max_len = algorithm.digest_size * (2**32 - 1)
        if length > max_len:
            raise ValueError(
                "Can not derive keys larger than {} bits.".format(max_len))
        if sharedinfo is not None:
            utils._check_bytes("sharedinfo", sharedinfo)

        self._algorithm = algorithm
        self._length = length
        self._sharedinfo = sharedinfo

        if not isinstance(backend, HashBackend):
            raise UnsupportedAlgorithm(
                "Backend object does not implement HashBackend.",
                _Reasons.BACKEND_MISSING_INTERFACE,
            )
        self._backend = backend
        self._used = False
Ejemplo n.º 21
0
    def __init__(self, algorithm, length, salt, iterations, backend=None):
        backend = _get_backend(backend)
        if not isinstance(backend, PBKDF2HMACBackend):
            raise UnsupportedAlgorithm(
                "Backend object does not implement PBKDF2HMACBackend.",
                _Reasons.BACKEND_MISSING_INTERFACE,
            )

        if not backend.pbkdf2_hmac_supported(algorithm):
            raise UnsupportedAlgorithm(
                "{} is not supported for PBKDF2 by this backend.".format(
                    algorithm.name),
                _Reasons.UNSUPPORTED_HASH,
            )
        self._used = False
        self._algorithm = algorithm
        self._length = length
        utils._check_bytes("salt", salt)
        self._salt = salt
        self._iterations = iterations
        self._backend = backend
Ejemplo n.º 22
0
    def sign(self, encoding, options, backend=None):
        if len(self._signers) == 0:
            raise ValueError("Must have at least one signer")
        if self._data is None:
            raise ValueError("You must add data to sign")
        options = list(options)
        if not all(isinstance(x, PKCS7Options) for x in options):
            raise ValueError("options must be from the PKCS7Options enum")
        if encoding not in (
                serialization.Encoding.PEM,
                serialization.Encoding.DER,
                serialization.Encoding.SMIME,
        ):
            raise ValueError(
                "Must be PEM, DER, or SMIME from the Encoding enum")

        # Text is a meaningless option unless it is accompanied by
        # DetachedSignature
        if (PKCS7Options.Text in options
                and PKCS7Options.DetachedSignature not in options):
            raise ValueError("When passing the Text option you must also pass "
                             "DetachedSignature")

        if PKCS7Options.Text in options and encoding in (
                serialization.Encoding.DER,
                serialization.Encoding.PEM,
        ):
            raise ValueError(
                "The Text option is only available for SMIME serialization")

        # No attributes implies no capabilities so we'll error if you try to
        # pass both.
        if (PKCS7Options.NoAttributes in options
                and PKCS7Options.NoCapabilities in options):
            raise ValueError(
                "NoAttributes is a superset of NoCapabilities. Do not pass "
                "both values.")

        backend = _get_backend(backend)
        return backend.pkcs7_sign(self, encoding, options)
Ejemplo n.º 23
0
def aes_key_unwrap_with_padding(wrapping_key, wrapped_key, backend=None):
    backend = _get_backend(backend)
    if len(wrapped_key) < 16:
        raise InvalidUnwrap("Must be at least 16 bytes")

    if len(wrapping_key) not in [16, 24, 32]:
        raise ValueError("The wrapping key must be a valid AES key length")

    if len(wrapped_key) == 16:
        # RFC 5649 - 4.2 - exactly two 64-bit blocks
        decryptor = Cipher(AES(wrapping_key), ECB(), backend).decryptor()
        b = decryptor.update(wrapped_key)
        assert decryptor.finalize() == b""
        a = b[:8]
        data = b[8:]
        n = 1
    else:
        r = [wrapped_key[i:i + 8] for i in range(0, len(wrapped_key), 8)]
        encrypted_aiv = r.pop(0)
        n = len(r)
        a, r = _unwrap_core(wrapping_key, encrypted_aiv, r, backend)
        data = b"".join(r)

    # 1) Check that MSB(32,A) = A65959A6.
    # 2) Check that 8*(n-1) < LSB(32,A) <= 8*n.  If so, let
    #    MLI = LSB(32,A).
    # 3) Let b = (8*n)-MLI, and then check that the rightmost b octets of
    #    the output data are zero.
    (mli, ) = struct.unpack(">I", a[4:])
    b = (8 * n) - mli
    if (not bytes_eq(a[:4], b"\xa6\x59\x59\xa6")
            or not 8 * (n - 1) < mli <= 8 * n
            or (b != 0 and not bytes_eq(data[-b:], b"\x00" * b))):
        raise InvalidUnwrap()

    if b == 0:
        return data
    else:
        return data[:-b]
Ejemplo n.º 24
0
    def __init__(self, algorithm, length, salt, otherinfo, backend=None):
        backend = _get_backend(backend)

        _common_args_checks(algorithm, length, otherinfo)
        self._algorithm = algorithm
        self._length = length
        self._otherinfo = otherinfo
        if self._otherinfo is None:
            self._otherinfo = b""

        if salt is None:
            salt = b"\x00" * algorithm.block_size
        else:
            utils._check_bytes("salt", salt)

        self._salt = salt

        if not isinstance(backend, HMACBackend):
            raise UnsupportedAlgorithm(
                "Backend object does not implement HMACBackend.",
                _Reasons.BACKEND_MISSING_INTERFACE,
            )
        self._backend = backend
        self._used = False
Ejemplo n.º 25
0
    def sign(self, private_key, algorithm, backend=None):
        """
        Signs the certificate using the CA's private key.
        """
        backend = _get_backend(backend)
        if self._subject_name is None:
            raise ValueError("A certificate must have a subject name")

        if self._issuer_name is None:
            raise ValueError("A certificate must have an issuer name")

        if self._serial_number is None:
            raise ValueError("A certificate must have a serial number")

        if self._not_valid_before is None:
            raise ValueError("A certificate must have a not valid before time")

        if self._not_valid_after is None:
            raise ValueError("A certificate must have a not valid after time")

        if self._public_key is None:
            raise ValueError("A certificate must have a public key")

        return backend.create_x509_certificate(self, private_key, algorithm)
Ejemplo n.º 26
0
    def __init__(
        self,
        algorithm,
        mode,
        length,
        rlen,
        llen,
        location,
        label,
        context,
        fixed,
        backend=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 UnsupportedAlgorithm(
                "Algorithm supplied is not a supported hash algorithm.",
                _Reasons.UNSUPPORTED_HASH,
            )

        if not backend.hmac_supported(algorithm):
            raise UnsupportedAlgorithm(
                "Algorithm supplied is not a supported hmac algorithm.",
                _Reasons.UNSUPPORTED_HASH,
            )

        if not isinstance(mode, Mode):
            raise TypeError("mode must be of type Mode")

        if not isinstance(location, CounterLocation):
            raise TypeError("location must be of type CounterLocation")

        if (label or context) and fixed:
            raise ValueError("When supplying fixed data, "
                             "label and context are ignored.")

        if rlen is None or not self._valid_byte_length(rlen):
            raise ValueError("rlen must be between 1 and 4")

        if llen is None and fixed is None:
            raise ValueError("Please specify an llen")

        if llen is not None and not isinstance(llen, int):
            raise TypeError("llen must be an integer")

        if label is None:
            label = b""

        if context is None:
            context = b""

        utils._check_bytes("label", label)
        utils._check_bytes("context", context)
        self._algorithm = algorithm
        self._mode = mode
        self._length = length
        self._rlen = rlen
        self._llen = llen
        self._location = location
        self._label = label
        self._context = context
        self._backend = backend
        self._used = False
        self._fixed_data = fixed
Ejemplo n.º 27
0
 def private_key(self, backend=None):
     backend = _get_backend(backend)
     return backend.load_dsa_private_numbers(self)
Ejemplo n.º 28
0
 def public_key(self, backend=None):
     backend = _get_backend(backend)
     return backend.load_dsa_public_numbers(self)
Ejemplo n.º 29
0
 def parameters(self, backend=None):
     backend = _get_backend(backend)
     return backend.load_dsa_parameter_numbers(self)
Ejemplo n.º 30
0
def generate_private_key(key_size, backend=None):
    backend = _get_backend(backend)
    return backend.generate_dsa_private_key_and_parameters(key_size)