當前位置: 首頁>>代碼示例>>Python>>正文


Python hkdf.HKDF屬性代碼示例

本文整理匯總了Python中cryptography.hazmat.primitives.kdf.hkdf.HKDF屬性的典型用法代碼示例。如果您正苦於以下問題:Python hkdf.HKDF屬性的具體用法?Python hkdf.HKDF怎麽用?Python hkdf.HKDF使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在cryptography.hazmat.primitives.kdf.hkdf的用法示例。


在下文中一共展示了hkdf.HKDF屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: encryption_step_5

# 需要導入模塊: from cryptography.hazmat.primitives.kdf import hkdf [as 別名]
# 或者: from cryptography.hazmat.primitives.kdf.hkdf import HKDF [as 別名]
def encryption_step_5(self, module, message, additional_data, cm):
		client_ephemeral_public = message[len(self.cmh_struct_encryption[4][0]):]

		c = module.lookup_client_pub(additional_data)

		try:
			public_numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(self.curve, "\x04"+client_ephemeral_public)
		except:
			common.internal_print("Erroneous key received from the client. Are you sure you are using the same settings on both sides?", -1)
			return module.cmh_struct[cm][4+module.is_caller_stateless()]

		client_ephemeral_public_key = public_numbers.public_key(default_backend())

		server_ephemeral_private_key = c.get_encryption().get_private_key()
		hkdf = HKDF(algorithm=hashes.SHA256(), length=32, salt="IRatherEatMaldonThanHimalayan", info=None, backend=default_backend())
		c.get_encryption().set_shared_key(hkdf.derive(server_ephemeral_private_key.exchange(ec.ECDH(), client_ephemeral_public_key)))

		module.post_encryption_server(message[len(self.cmh_struct_encryption[4][0]):], additional_data)

		common.internal_print("Encryption key agreed with the client.", 1)

		return module.cmh_struct[cm][3]

	# checking for the key file values in the config 
開發者ID:earthquake,項目名稱:XFLTReaT,代碼行數:26,代碼來源:enc_advanced.py

示例2: _derive_delegated_key

# 需要導入模塊: from cryptography.hazmat.primitives.kdf import hkdf [as 別名]
# 或者: from cryptography.hazmat.primitives.kdf.hkdf import HKDF [as 別名]
def _derive_delegated_key(self, initial_material, key_info, hkdf_info):
        # type: (bytes, KeyInfo, HkdfInfo) -> JceNameLocalDelegatedKey
        """Derive the raw key and use it to build a JceNameLocalDelegatedKey.

        :param bytes initial_material: Initial material to use with KDF
        :param KeyInfo key_info: Key information to use to calculate encryption key
        :param HkdfInfo hkdf_info: Info to use in HKDF calculation
        :returns: Delegated key to use for encryption and decryption
        :rtype: JceNameLocalDelegatedKey
        """
        raw_key = self._hkdf(initial_material, key_info.length // 8, hkdf_info.value)
        return JceNameLocalDelegatedKey(
            key=raw_key,
            algorithm=key_info.algorithm,
            key_type=EncryptionKeyType.SYMMETRIC,
            key_encoding=KeyEncodingType.RAW,
        ) 
開發者ID:aws,項目名稱:aws-dynamodb-encryption-python,代碼行數:19,代碼來源:aws_kms.py

示例3: kdf

# 需要導入模塊: from cryptography.hazmat.primitives.kdf import hkdf [as 別名]
# 或者: from cryptography.hazmat.primitives.kdf.hkdf import HKDF [as 別名]
def kdf(ecpoint: Point,
        key_length: int,
        salt: Optional[bytes] = None,
        info: Optional[bytes] = None,
        ) -> bytes:

    data = ecpoint.to_bytes(is_compressed=True)
    hkdf = HKDF(algorithm=hashes.BLAKE2b(64),
                length=key_length,
                salt=salt,
                info=info,
                backend=default_backend())
    return hkdf.derive(data)


# TODO: Common API for all hash_to_curvebn functions.
# TODO: ^ It should check the correct number and type args, instead of current approach. 
開發者ID:nucypher,項目名稱:pyUmbral,代碼行數:19,代碼來源:random_oracles.py

示例4: derive_privkey_by_label

# 需要導入模塊: from cryptography.hazmat.primitives.kdf import hkdf [as 別名]
# 或者: from cryptography.hazmat.primitives.kdf.hkdf import HKDF [as 別名]
def derive_privkey_by_label(self,
                                label: bytes,
                                salt: Optional[bytes] = None,
                                params: Optional[UmbralParameters] = None) -> UmbralPrivateKey:
        """
        Derives an UmbralPrivateKey using a KDF from this instance of 
        UmbralKeyingMaterial, a label, and an optional salt.
        """
        params = params if params is not None else default_params()

        key_material = HKDF(
            algorithm=hashes.BLAKE2b(64),
            length=64,
            salt=salt,
            info=b"NuCypher/KeyDerivation/"+label,
            backend=default_backend()
        ).derive(self.__keying_material)

        bn_key = hash_to_curvebn(key_material, params=params)
        return UmbralPrivateKey(bn_key, params) 
開發者ID:nucypher,項目名稱:pyUmbral,代碼行數:22,代碼來源:keys.py

示例5: encryption_step_3

# 需要導入模塊: from cryptography.hazmat.primitives.kdf import hkdf [as 別名]
# 或者: from cryptography.hazmat.primitives.kdf.hkdf import HKDF [as 別名]
def encryption_step_3(self, module, message, additional_data, cm):
		client_public_key_stream = message[len(self.cmh_struct_encryption[2][0]):]
		try:
			public_numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(self.curve, "\x04"+client_public_key_stream)
		except:
			common.internal_print("Erroneous key received from the client. Are you sure you are using the same settings on both sides?", -1)
			return module.cmh_struct[cm][4+module.is_caller_stateless()]

		client_public_key = public_numbers.public_key(default_backend())

		c = module.lookup_client_pub(additional_data)

		hkdf = HKDF(algorithm=hashes.SHA256(), length=32, salt="IRatherEatMaldonThanHimalayan", info=None, backend=default_backend())
		c.get_encryption().set_shared_key(hkdf.derive(self.server_private_key.exchange(ec.ECDH(), client_public_key)))

		server_ephemeral_private_key = ec.generate_private_key(self.curve, default_backend())
		server_ephemeral_public_key = server_ephemeral_private_key.public_key()

		# no need to save, but who knows?!
		c.get_encryption().set_private_key(server_ephemeral_private_key)
		c.get_encryption().set_public_key(server_ephemeral_public_key)

		c.get_encryption().set_encrypted(True)

		pbk = server_ephemeral_public_key.public_numbers().encode_point()[1:]
		module.send(common.CONTROL_CHANNEL_BYTE, self.cmh_struct_encryption[3][0]+pbk, module.modify_additional_data(additional_data, 1))

		return module.cmh_struct[cm][3]

	# client side.
	# Server's ephemeral receveid, client generates an ephemeral keypair as
	# well. Client sends its ephemeral's public key to the server.
	# Since this is the last client side function called, we invoke the 
	# next step that is most probably the authentication, defined in the 
	# post_encryption_client() function. 
開發者ID:earthquake,項目名稱:XFLTReaT,代碼行數:37,代碼來源:enc_advanced.py

示例6: encryption_step_4

# 需要導入模塊: from cryptography.hazmat.primitives.kdf import hkdf [as 別名]
# 或者: from cryptography.hazmat.primitives.kdf.hkdf import HKDF [as 別名]
def encryption_step_4(self, module, message, additional_data, cm):
		server_ephemeral_public_key_stream = message[len(self.cmh_struct_encryption[3][0]):]

		try:
			public_numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(self.curve, "\x04"+server_ephemeral_public_key_stream)
		except:
			common.internal_print("Erroneous key received from the server. Are you sure you are using the same settings on both sides?", -1)
			return module.cmh_struct[cm][4+module.is_caller_stateless()]

		server_ephemeral_public_key = public_numbers.public_key(default_backend())

		client_ephemeral_private_key = ec.generate_private_key(self.curve, default_backend())
		client_ephemeral_public_key = client_ephemeral_private_key.public_key()

		module.encryption.set_private_key(client_ephemeral_private_key)
		module.encryption.set_public_key(client_ephemeral_public_key)

		pbk = client_ephemeral_public_key.public_numbers().encode_point()[1:]
		module.send(common.CONTROL_CHANNEL_BYTE, self.cmh_struct_encryption[4][0]+pbk, module.modify_additional_data(additional_data, 0))

		hkdf = HKDF(algorithm=hashes.SHA256(), length=32, salt="IRatherEatMaldonThanHimalayan", info=None, backend=default_backend())
		module.encryption.set_shared_key(hkdf.derive(client_ephemeral_private_key.exchange(ec.ECDH(), server_ephemeral_public_key)))
		module.post_encryption_client(message[len(self.cmh_struct_encryption[3][0]):], additional_data)

		common.internal_print("Encryption key agreed with the server.", 1)

		return module.cmh_struct[cm][3]

	# server side.
	# Client's ephemeral public key received. Key exchanged and saved. 
開發者ID:earthquake,項目名稱:XFLTReaT,代碼行數:32,代碼來源:enc_advanced.py

示例7: extract

# 需要導入模塊: from cryptography.hazmat.primitives.kdf import hkdf [as 別名]
# 或者: from cryptography.hazmat.primitives.kdf.hkdf import HKDF [as 別名]
def extract(self, salt, ikm):
        h = self.hash
        hkdf = HKDF(h, h.digest_size, salt, None, default_backend())
        if ikm is None:
            ikm = b"\x00" * h.digest_size
        return hkdf._extract(ikm) 
開發者ID:secdev,項目名稱:scapy,代碼行數:8,代碼來源:hkdf.py

示例8: _generate_initial_material

# 需要導入模塊: from cryptography.hazmat.primitives.kdf import hkdf [as 別名]
# 或者: from cryptography.hazmat.primitives.kdf.hkdf import HKDF [as 別名]
def _generate_initial_material(self, encryption_context):
        # type: (EncryptionContext) -> Tuple[bytes, bytes]
        """Generate the initial cryptographic material for use with HKDF.

        :param EncryptionContext encryption_context: Encryption context providing information about request
        :returns: Plaintext and ciphertext of initial cryptographic material
        :rtype: bytes and bytes
        """
        key_id = self._select_key_id(encryption_context)
        self._validate_key_id(key_id, encryption_context)
        key_length = 256 // 8
        kms_encryption_context = self._kms_encryption_context(
            encryption_context=encryption_context,
            encryption_description=self._content_key_info.description,
            signing_description=self._signing_key_info.description,
        )
        kms_params = dict(KeyId=key_id, NumberOfBytes=key_length, EncryptionContext=kms_encryption_context)
        if self._grant_tokens:
            kms_params["GrantTokens"] = self._grant_tokens
        # Catch any boto3 errors and normalize to expected WrappingError
        try:
            response = self._client(key_id).generate_data_key(**kms_params)
            return response["Plaintext"], response["CiphertextBlob"]
        except (botocore.exceptions.ClientError, KeyError):
            message = "Failed to generate materials using AWS KMS"
            _LOGGER.exception(message)
            raise WrappingError(message) 
開發者ID:aws,項目名稱:aws-dynamodb-encryption-python,代碼行數:29,代碼來源:aws_kms.py

示例9: _hkdf

# 需要導入模塊: from cryptography.hazmat.primitives.kdf import hkdf [as 別名]
# 或者: from cryptography.hazmat.primitives.kdf.hkdf import HKDF [as 別名]
def _hkdf(self, initial_material, key_length, info):
        # type: (bytes, int, Text) -> bytes
        """Use HKDF to derive a key.

        :param bytes initial_material: Initial material to use with HKDF
        :param int key_length: Length of key to derive
        :param str info: Info value to use in HKDF calculate
        :returns: Derived key material
        :rtype: bytes
        """
        hkdf = HKDF(algorithm=hashes.SHA256(), length=key_length, salt=None, info=info, backend=default_backend())
        return hkdf.derive(initial_material) 
開發者ID:aws,項目名稱:aws-dynamodb-encryption-python,代碼行數:14,代碼來源:aws_kms.py

示例10: hkdf_expand

# 需要導入模塊: from cryptography.hazmat.primitives.kdf import hkdf [as 別名]
# 或者: from cryptography.hazmat.primitives.kdf.hkdf import HKDF [as 別名]
def hkdf_expand(salt, info, shared_secret):
    """Derive encryption keys from shared secret."""
    hkdf = HKDF(
        algorithm=hashes.SHA512(),
        length=32,
        salt=salt.encode(),
        info=info.encode(),
        backend=default_backend(),
    )
    return hkdf.derive(shared_secret)


# pylint: disable=too-many-instance-attributes 
開發者ID:postlund,項目名稱:pyatv,代碼行數:15,代碼來源:srp.py

示例11: hkdf_expand_and_extract

# 需要導入模塊: from cryptography.hazmat.primitives.kdf import hkdf [as 別名]
# 或者: from cryptography.hazmat.primitives.kdf.hkdf import HKDF [as 別名]
def hkdf_expand_and_extract(secret: bytes,
                            initiator_node_id: NodeID,
                            recipient_node_id: NodeID,
                            id_nonce: IDNonce,
                            ) -> Tuple[bytes, bytes, bytes]:
    info = b"".join((
        HKDF_INFO,
        initiator_node_id,
        recipient_node_id,
    ))

    hkdf = HKDF(
        algorithm=SHA256(),
        length=3 * AES128_KEY_SIZE,
        salt=id_nonce,
        info=info,
        backend=cryptography_default_backend(),
    )
    expanded_key = hkdf.derive(secret)

    if len(expanded_key) != 3 * AES128_KEY_SIZE:
        raise Exception("Invariant: Secret is expanded to three AES128 keys")

    initiator_key = expanded_key[:AES128_KEY_SIZE]
    recipient_key = expanded_key[AES128_KEY_SIZE:2 * AES128_KEY_SIZE]
    auth_response_key = expanded_key[2 * AES128_KEY_SIZE:3 * AES128_KEY_SIZE]

    return initiator_key, recipient_key, auth_response_key 
開發者ID:ethereum,項目名稱:trinity,代碼行數:30,代碼來源:identity_schemes.py

示例12: derive_fernet_key

# 需要導入模塊: from cryptography.hazmat.primitives.kdf import hkdf [as 別名]
# 或者: from cryptography.hazmat.primitives.kdf.hkdf import HKDF [as 別名]
def derive_fernet_key(input_key):
    """Derive a 32-bit b64-encoded Fernet key from arbitrary input key."""
    hkdf = HKDF(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt,
        info=info,
        backend=backend,
    )
    return base64.urlsafe_b64encode(hkdf.derive(force_bytes(input_key))) 
開發者ID:orcasgit,項目名稱:django-fernet-fields,代碼行數:12,代碼來源:hkdf.py

示例13: doECDHE

# 需要導入模塊: from cryptography.hazmat.primitives.kdf import hkdf [as 別名]
# 或者: from cryptography.hazmat.primitives.kdf.hkdf import HKDF [as 別名]
def doECDHE(statprv_u, statpub_v, ephmprv_u, ephmpub_v,
            length=64,
            salt=None,
            info=None):
    '''
    Perform one side of an Ecliptic Curve Diffie Hellman Ephemeral key exchange.

    Args:
        statprv_u (PriKey): Static Private Key for U
        statpub_v (PubKey: Static Public Key for V
        ephmprv_u (PriKey): Ephemeral Private Key for U
        ephmpub_v (PubKey): Ephemeral Public Key for V
        length (int): Number of bytes to return
        salt (bytes): Salt to use when computing the key.
        info (bytes): Additional information to use when computing the key.

    Notes:
        This makes no assumption about the reuse of the Ephemeral keys passed
        to the function. It is the caller's responsibility to destroy the keys
        after they are used for doing key generation. This implementation is
        the dhHybrid1 scheme described in NIST 800-56A Revision 2.

    Returns:
        bytes: The derived key.
    '''
    zs = statprv_u.exchange(statpub_v)
    ze = ephmprv_u.exchange(ephmpub_v)
    z = ze + zs
    kdf = c_hkdf.HKDF(c_hashes.SHA256(),
                      length=length,
                      salt=salt,
                      info=info,
                      backend=default_backend())
    k = kdf.derive(z)
    return k 
開發者ID:vertexproject,項目名稱:synapse,代碼行數:37,代碼來源:ecc.py

示例14: encryption_step_2

# 需要導入模塊: from cryptography.hazmat.primitives.kdf import hkdf [as 別名]
# 或者: from cryptography.hazmat.primitives.kdf.hkdf import HKDF [as 別名]
def encryption_step_2(self, module, message, additional_data, cm):
		server_public_key_stream = message[len(self.cmh_struct_encryption[1][0]):]

		digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
		digest.update(server_public_key_stream)
		pubkey_hash = base64.b64encode(digest.finalize())

		ip = module.config.get("Global", "remoteserverip")
		fingerprint = self.check_fingerprint(ip, pubkey_hash)
		if fingerprint == 2:
			# text was shamelessly copied from OpenSSH
			common.internal_print("The authenticity of host '{0}' can't be established.".format(ip), 1)
			common.internal_print("Server's key fingerprint is SHA256: {0}".format(base64.b64encode(pubkey_hash)), 1)
			answer = ""
			while (answer != "yes") and (answer != "no"):
				answer = raw_input("Are you sure you want to continue connecting? (yes/no) ")
			if answer == "yes":
				if not self.add_fingerprint(ip, pubkey_hash):
					common.internal_print("Error opening known_hosts file.", -1)
					return module.cmh_struct[cm][4+module.is_caller_stateless()]
			else:
				common.internal_print("Exiting...", -1)
				return module.cmh_struct[cm][4+module.is_caller_stateless()]

		if fingerprint == 1:
			common.internal_print("The fingerprint has changed for the server. If you don't trust this network,\nthis can be a Man-in-The-Middle attack!", -1)
			common.internal_print("Exiting...", -1)
			return module.cmh_struct[cm][4+module.is_caller_stateless()]
		try:
			public_numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(self.curve, "\x04"+server_public_key_stream)
		except:
			common.internal_print("Erroneous key received from the server. Are you sure you are using the same settings on both sides?", -1)
			return module.cmh_struct[cm][4+module.is_caller_stateless()]

		server_public_key = public_numbers.public_key(default_backend())

		client_private_key = ec.generate_private_key(self.curve, default_backend())

		hkdf = HKDF(algorithm=hashes.SHA256(), length=32, salt="IRatherEatMaldonThanHimalayan", info=None, backend=default_backend())
		module.encryption.set_shared_key(hkdf.derive(client_private_key.exchange(ec.ECDH(), server_public_key)))

		pbk = client_private_key.public_key().public_numbers().encode_point()[1:]
		module.send(common.CONTROL_CHANNEL_BYTE, self.cmh_struct_encryption[2][0]+pbk, module.modify_additional_data(additional_data, 0))

		module.encryption.set_encrypted(True)

		return module.cmh_struct[cm][3]

	# server side.
	# Client's public key received, key exchanged.
	# A new ephemeral key pair is generated, public key is sent to the client.
	# This is to use a new, disposable key for every session 
開發者ID:earthquake,項目名稱:XFLTReaT,代碼行數:54,代碼來源:enc_advanced.py

示例15: test_lib_crypto_ecc_exchange

# 需要導入模塊: from cryptography.hazmat.primitives.kdf import hkdf [as 別名]
# 或者: from cryptography.hazmat.primitives.kdf.hkdf import HKDF [as 別名]
def test_lib_crypto_ecc_exchange(self):
        spvk1 = s_ecc.PriKey.generate()
        spbk1 = spvk1.public()

        spvk2 = s_ecc.PriKey.generate()
        spbk2 = spvk2.public()

        k1 = (spvk1.exchange(spbk2))
        k2 = (spvk2.exchange(spbk1))
        self.eq(k1, k2)

        # Curves must be the same
        _pkd = c_ec.generate_private_key(
            c_ec.SECP192R1(),  # We don't use this curve
            default_backend()
        )
        prkdiff = s_ecc.PriKey(_pkd)
        pbkdiff = prkdiff.public()
        self.raises(s_exc.BadEccExchange, spvk1.exchange, pbkdiff)
        self.raises(s_exc.BadEccExchange, prkdiff.exchange, spbk1)

        # Do a demonstrative ephemeral exchange
        epvk1 = s_ecc.PriKey.generate()
        epbk1 = epvk1.public()

        epvk2 = s_ecc.PriKey.generate()
        epbk2 = epvk2.public()

        # assume epbk2 is sent to the owner of pvk1
        z1e = epvk1.exchange(epbk2)
        z1s = spvk1.exchange(spbk2)
        z1 = z1e + z1s

        # assume epbk1 is sent to the owner of pvk2
        z2e = epvk2.exchange(epbk1)
        z2s = spvk2.exchange(spbk1)
        z2 = z2e + z2s

        self.eq(z1, z2)

        # run through kdf
        kdf1 = c_hkdf.HKDF(c_hashes.SHA256(),
                           length=64,
                           salt=None,
                           info=b'test',
                           backend=default_backend())
        k1 = kdf1.derive(z1)
        k1tx, k1rx = k1[32:], k1[:32]

        kdf2 = c_hkdf.HKDF(c_hashes.SHA256(),
                           length=64,
                           salt=None,
                           info=b'test',
                           backend=default_backend())
        k2 = kdf2.derive(z2)
        k2rx, k2tx = k2[32:], k2[:32]

        self.eq(k1tx, k2rx)
        self.eq(k1rx, k2tx)
        self.ne(k1tx, k2tx) 
開發者ID:vertexproject,項目名稱:synapse,代碼行數:62,代碼來源:test_lib_crypto_ecc.py


注:本文中的cryptography.hazmat.primitives.kdf.hkdf.HKDF屬性示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。