def __init__( self, algorithm: hashes.HashAlgorithm, length: int, sharedinfo: typing.Optional[bytes], 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
def verify(self, tag: bytes) -> None: utils._check_bytes("tag", tag) if self._ctx is None: raise AlreadyFinalized("Context was already finalized.") ctx, self._ctx = self._ctx, None ctx.verify(tag)
def verify(self, tag): utils._check_bytes("tag", tag) if self._ctx is None: raise AlreadyFinalized("Context was already finalized.") ctx, self._ctx = self._ctx, None ctx.verify(tag)
def __init__( self, algorithm: hashes.HashAlgorithm, length: int, info: typing.Optional[bytes], backend: typing.Any = None, ): self._algorithm = algorithm max_length = 255 * algorithm.digest_size if length > max_length: raise ValueError( "Cannot 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
def __init__( self, salt: bytes, length: int, n: int, r: int, p: int, backend: typing.Any = None, ): from cryptography.hazmat.backends.openssl.backend import ( backend as ossl, ) if not ossl.scrypt_supported(): raise UnsupportedAlgorithm( "This version of OpenSSL does not support scrypt") 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
def _check_params(self, nonce: bytes, data: bytes, associated_data: bytes) -> None: utils._check_byteslike("nonce", nonce) utils._check_bytes("data", data) utils._check_bytes("associated_data", associated_data) if len(nonce) != 12: raise ValueError("Nonce must be 12 bytes")
def __init__( self, algorithm: hashes.HashAlgorithm, length: int, salt: bytes, iterations: int, backend: typing.Any = None, ): from cryptography.hazmat.backends.openssl.backend import ( backend as ossl, ) if not ossl.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
def __init__(self, algorithm, length, info, 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
def __init__( self, salt: bytes, length: int, n: int, r: int, p: int, backend: typing.Optional[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
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)
def _common_args_checks(algorithm, length, otherinfo): max_length = algorithm.digest_size * (2**32 - 1) if length > max_length: raise ValueError( "Can not derive keys larger than {0} bits.".format(max_length)) if otherinfo is not None: utils._check_bytes("otherinfo", otherinfo)
def __init__( self, algorithm: hashes.HashAlgorithm, length: int, salt: typing.Optional[bytes], info: typing.Optional[bytes], 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)
def _check_params(self, nonce: bytes, data: bytes, associated_data: bytes) -> None: utils._check_byteslike("nonce", nonce) utils._check_bytes("data", data) utils._check_bytes("associated_data", associated_data) if len(nonce) < 8 or len(nonce) > 128: raise ValueError("Nonce must be between 8 and 128 bytes")
def __init__( self, algorithm: hashes.HashAlgorithm, length: int, salt: typing.Optional[bytes], otherinfo: typing.Optional[bytes], backend: typing.Any = None, ): _common_args_checks(algorithm, length, otherinfo) self._algorithm = algorithm self._length = length self._otherinfo: bytes = otherinfo if otherinfo is not None else b"" if algorithm.block_size is None: raise TypeError("{} is unsupported for ConcatKDF".format( algorithm.name)) if salt is None: salt = b"\x00" * algorithm.block_size else: utils._check_bytes("salt", salt) self._salt = salt self._used = False
def _check_params(self, nonce: bytes, data: bytes, associated_data: bytes) -> None: utils._check_byteslike("nonce", nonce) utils._check_bytes("data", data) utils._check_bytes("associated_data", associated_data) if not 7 <= len(nonce) <= 13: raise ValueError("Nonce must be between 7 and 13 bytes")
def derive(self, key_material): if self._used: raise AlreadyFinalized utils._check_bytes("key_material", key_material) self._used = True # inverse floor division (equivalent to ceiling) rounds = -(-self._length // self._algorithm.digest_size) output = [b''] # For counter mode, the number of iterations shall not be # larger than 2^r-1, where r <= 32 is the binary length of the counter # This ensures that the counter values used as an input to the # PRF will not repeat during a particular call to the KDF function. r_bin = utils.int_to_bytes(1, self._rlen) if rounds > pow(2, len(r_bin) * 8) - 1: raise ValueError('There are too many iterations.') for i in range(1, rounds + 1): h = hmac.HMAC(key_material, self._algorithm, backend=self._backend) counter = utils.int_to_bytes(i, self._rlen) if self._location == CounterLocation.BeforeFixed: h.update(counter) h.update(self._generate_fixed_input()) if self._location == CounterLocation.AfterFixed: h.update(counter) output.append(h.finalize()) return b''.join(output)[:self._length]
def verifier(self, signature, signature_algorithm): _warn_sign_verify_deprecated() utils._check_bytes("signature", signature) _check_not_prehashed(signature_algorithm) return _DSAVerificationContext(self._backend, self, signature, signature_algorithm)
def __init__( self, algorithm: hashes.HashAlgorithm, length: int, info: typing.Optional[bytes], 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
def __init__( self, algorithm: hashes.HashAlgorithm, length: int, salt: typing.Optional[bytes], otherinfo: typing.Optional[bytes], backend: typing.Optional[Backend] = None, ): backend = _get_backend(backend) _common_args_checks(algorithm, length, otherinfo) self._algorithm = algorithm self._length = length self._otherinfo: bytes = otherinfo if otherinfo is not None else b"" if algorithm.block_size is None: raise TypeError("{} is unsupported for ConcatKDF".format( algorithm.name)) 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
def derive(self, key_material): utils._check_bytes("key_material", key_material) if self._used: raise AlreadyFinalized self._used = True return self._expand(key_material)
def __init__( self, algorithm: hashes.HashAlgorithm, length: int, salt: bytes, iterations: int, backend: typing.Optional[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
def _common_args_checks(algorithm: hashes.HashAlgorithm, length: int, otherinfo: typing.Optional[bytes]): max_length = algorithm.digest_size * (2**32 - 1) if length > max_length: raise ValueError( "Can not derive keys larger than {} bits.".format(max_length)) if otherinfo is not None: utils._check_bytes("otherinfo", otherinfo)
def __init__(self, algorithm, mode, length, rlen, llen, location, label, context, fixed, 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
def derive(self, key_material): if self._used: raise AlreadyFinalized("Scrypt instances can only be used once.") self._used = True utils._check_bytes("key_material", key_material) return self._backend.derive_scrypt( key_material, self._salt, self._length, self._n, self._r, self._p )
def verifier(self, signature, signature_algorithm): _warn_sign_verify_deprecated() utils._check_bytes("signature", signature) _check_signature_algorithm(signature_algorithm) _check_not_prehashed(signature_algorithm.algorithm) return _ECDSAVerificationContext( self._backend, self, signature, signature_algorithm.algorithm )
def _check_params( self, data: bytes, associated_data: typing.List, ) -> None: utils._check_bytes("data", data) if not isinstance(associated_data, list) or not all( isinstance(x, bytes) for x in associated_data): raise TypeError("associated_data must be a list of bytes or None")
def _common_args_checks(algorithm, length, otherinfo): max_length = algorithm.digest_size * (2 ** 32 - 1) if length > max_length: raise ValueError( "Can not derive keys larger than {} bits.".format( max_length )) if otherinfo is not None: utils._check_bytes("otherinfo", otherinfo)
def _verify_key_size(algorithm, key): # Verify that the key is instance of bytes utils._check_bytes("key", key) # Verify that the key size matches the expected key size if len(key) * 8 not in algorithm.key_sizes: raise ValueError("Invalid key size ({0}) for {1}.".format( len(key) * 8, algorithm.name)) return key
def derive(self, key_material): if self._used: raise AlreadyFinalized("PBKDF2 instances can only be used once.") self._used = True utils._check_bytes("key_material", key_material) return self._backend.derive_pbkdf2_hmac(self._algorithm, self._length, self._salt, self._iterations, key_material)
def from_encoded_point(cls, curve, data): utils._check_bytes("data", data) if not isinstance(curve, EllipticCurve): raise TypeError("curve must be an EllipticCurve instance") if six.indexbytes(data, 0) not in [0x02, 0x03, 0x04]: raise ValueError("Unsupported elliptic curve point type") from cryptography.hazmat.backends.openssl.backend import backend return backend.load_elliptic_curve_public_bytes(curve, data)
def __init__(self, key): if not backend.aead_cipher_supported(self): raise exceptions.UnsupportedAlgorithm( "ChaCha20Poly1305 is not supported by this version of OpenSSL", exceptions._Reasons.UNSUPPORTED_CIPHER) utils._check_bytes("key", key) if len(key) != 32: raise ValueError("ChaCha20Poly1305 key must be 32 bytes.") self._key = key
def verifier( self, signature: bytes, signature_algorithm: hashes.HashAlgorithm, ) -> AsymmetricVerificationContext: _warn_sign_verify_deprecated() utils._check_bytes("signature", signature) _check_not_prehashed(signature_algorithm) return _DSAVerificationContext(self._backend, self, signature, signature_algorithm)
def __init__(self, key): if not backend.aead_cipher_supported(self): raise exceptions.UnsupportedAlgorithm( "ChaCha20Poly1305 is not supported by this version of OpenSSL", exceptions._Reasons.UNSUPPORTED_CIPHER ) utils._check_bytes("key", key) if len(key) != 32: raise ValueError("ChaCha20Poly1305 key must be 32 bytes.") self._key = key
def verifier( self, signature: bytes, signature_algorithm: ec.EllipticCurveSignatureAlgorithm ) -> AsymmetricVerificationContext: _warn_sign_verify_deprecated() utils._check_bytes("signature", signature) _check_signature_algorithm(signature_algorithm) _check_not_prehashed(signature_algorithm.algorithm) # This assert is to help mypy realize what type this object holds assert isinstance(signature_algorithm.algorithm, hashes.HashAlgorithm) return _ECDSAVerificationContext(self._backend, self, signature, signature_algorithm.algorithm)
def __init__( self, prf: typing.Callable, mode: Mode, length: int, rlen: int, llen: typing.Optional[int], location: CounterLocation, label: typing.Optional[bytes], context: typing.Optional[bytes], fixed: typing.Optional[bytes], ): assert callable(prf) 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._prf = prf self._mode = mode self._length = length self._rlen = rlen self._llen = llen self._location = location self._label = label self._context = context self._used = False self._fixed_data = fixed
def from_encoded_point(cls, curve, data): utils._check_bytes("data", data) if not isinstance(curve, EllipticCurve): raise TypeError("curve must be an EllipticCurve instance") if len(data) == 0: raise ValueError("data must not be an empty byte string") if six.indexbytes(data, 0) not in [0x02, 0x03, 0x04]: raise ValueError("Unsupported elliptic curve point type") from cryptography.hazmat.backends.openssl.backend import backend return backend.load_elliptic_curve_public_bytes(curve, data)
def _byte_unpadding_update(buffer_, data, block_size): if buffer_ is None: raise AlreadyFinalized("Context was already finalized.") utils._check_bytes("data", data) buffer_ += data finished_blocks = max(len(buffer_) // (block_size // 8) - 1, 0) result = buffer_[:finished_blocks * (block_size // 8)] buffer_ = buffer_[finished_blocks * (block_size // 8):] return buffer_, result
def _get_unverified_token_data(token): utils._check_bytes("token", token) try: data = base64.urlsafe_b64decode(token) except (TypeError, binascii.Error): raise InvalidToken if not data or six.indexbytes(data, 0) != 0x80: raise InvalidToken try: timestamp, = struct.unpack(">Q", data[1:9]) except struct.error: raise InvalidToken return timestamp, data
def _encrypt_from_parts(self, data, current_time, iv): utils._check_bytes("data", data) padder = padding.PKCS7(algorithms.AES.block_size).padder() padded_data = padder.update(data) + padder.finalize() encryptor = Cipher( algorithms.AES(self._encryption_key), modes.CBC(iv), self._backend ).encryptor() ciphertext = encryptor.update(padded_data) + encryptor.finalize() basic_parts = ( b"\x80" + struct.pack(">Q", current_time) + iv + ciphertext ) h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend) h.update(basic_parts) hmac = h.finalize() return base64.urlsafe_b64encode(basic_parts + hmac)
def __init__(self, algorithm, length, salt, info, 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)
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
def __init__(self, key, tag_length=16): utils._check_bytes("key", key) if len(key) not in (16, 24, 32): raise ValueError("AESCCM key must be 128, 192, or 256 bits.") self._key = key if not isinstance(tag_length, int): raise TypeError("tag_length must be an integer") if tag_length not in (4, 6, 8, 12, 14, 16): raise ValueError("Invalid tag_length") self._tag_length = tag_length if not backend.aead_cipher_supported(self): raise exceptions.UnsupportedAlgorithm( "AESCCM is not supported by this version of OpenSSL", exceptions._Reasons.UNSUPPORTED_CIPHER )
def __init__(self, algorithm, length, salt, iterations, 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( "{0} 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
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 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
def __init__(self, algorithm, length, salt, otherinfo, 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
def __init__(self, salt, length, n, r, p, 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
def _check_params(self, nonce, data, associated_data): utils._check_bytes("nonce", nonce) utils._check_bytes("data", data) utils._check_bytes("associated_data", associated_data) if len(nonce) == 0: raise ValueError("Nonce must be at least 1 byte")
def update(self, data): if self._ctx is None: raise AlreadyFinalized("Context was already finalized.") utils._check_bytes("data", data) self._ctx.update(data)
def _check_params(self, nonce, data, associated_data): utils._check_bytes("nonce", nonce) utils._check_bytes("data", data) utils._check_bytes("associated_data", associated_data) if not 7 <= len(nonce) <= 13: raise ValueError("Nonce must be between 7 and 13 bytes")
def __init__(self, key): utils._check_bytes("key", key) if len(key) not in (16, 24, 32): raise ValueError("AESGCM key must be 128, 192, or 256 bits.") self._key = key
def _check_params(self, nonce, data, associated_data): utils._check_bytes("nonce", nonce) utils._check_bytes("data", data) utils._check_bytes("associated_data", associated_data)
def _check_params(self, nonce, data, associated_data): utils._check_bytes("nonce", nonce) utils._check_bytes("data", data) utils._check_bytes("associated_data", associated_data) if len(nonce) != 12: raise ValueError("Nonce must be 12 bytes")