当前位置: 首页>>代码示例>>Python>>正文


Python exceptions.InvalidTag方法代码示例

本文整理汇总了Python中cryptography.exceptions.InvalidTag方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.InvalidTag方法的具体用法?Python exceptions.InvalidTag怎么用?Python exceptions.InvalidTag使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在cryptography.exceptions的用法示例。


在下文中一共展示了exceptions.InvalidTag方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: validate_header

# 需要导入模块: from cryptography import exceptions [as 别名]
# 或者: from cryptography.exceptions import InvalidTag [as 别名]
def validate_header(header, header_auth, raw_header, data_key):
    """Validates the header using the header authentication data.

    :param header: Deserialized header
    :type header: aws_encryption_sdk.structures.MessageHeader
    :param header_auth: Deserialized header auth
    :type header_auth: aws_encryption_sdk.internal.structures.MessageHeaderAuthentication
    :type stream: io.BytesIO
    :param bytes raw_header: Raw header bytes
    :param bytes data_key: Data key with which to perform validation
    :raises SerializationError: if header authorization fails
    """
    _LOGGER.debug("Starting header validation")
    try:
        decrypt(
            algorithm=header.algorithm,
            key=data_key,
            encrypted_data=EncryptedData(header_auth.iv, b"", header_auth.tag),
            associated_data=raw_header,
        )
    except InvalidTag:
        raise SerializationError("Header authorization failed") 
开发者ID:aws,项目名称:aws-encryption-sdk-python,代码行数:24,代码来源:deserialize.py

示例2: decrypt_data

# 需要导入模块: from cryptography import exceptions [as 别名]
# 或者: from cryptography.exceptions import InvalidTag [as 别名]
def decrypt_data(raw, keys=None):
    """
    Decrypt data using the given keys

    :param raw: data to decrypt
    :param keys: list of encryption keys
    :return:
    """
    offset = 0
    version, = struct.unpack('>B', raw[0:VER_SIZE])
    offset += VER_SIZE

    nonce = raw[offset:offset + IV_SIZE]
    offset += IV_SIZE

    tag = raw[offset:offset + TAG_SIZE]
    offset += TAG_SIZE

    cipher_text = raw[offset:]

    for key in keys:
        validate_key(key)

        cipher = ciphers.Cipher(algorithms.AES(key), modes.GCM(nonce, tag), backend=backends.default_backend())

        decryptor = cipher.decryptor()

        try:
            plain_text = decryptor.update(cipher_text) + decryptor.finalize()
        except (exceptions.InvalidTag, exceptions.InvalidKey):
            continue

        return plain_text

    raise DecryptError("Failed to decrypt data") 
开发者ID:kippandrew,项目名称:tattle,代码行数:37,代码来源:crypto.py

示例3: test_validate_header_invalid

# 需要导入模块: from cryptography import exceptions [as 别名]
# 或者: from cryptography.exceptions import InvalidTag [as 别名]
def test_validate_header_invalid(self):
        """Validate that the validate_header function behaves
            as expected for a valid header.
        """
        self.mock_decrypt.side_effect = InvalidTag()
        with pytest.raises(SerializationError) as excinfo:
            aws_encryption_sdk.internal.formatting.deserialize.validate_header(
                header=VALUES["deserialized_header_block"],
                header_auth=VALUES["deserialized_header_auth_block"],
                raw_header=VALUES["header"],
                data_key=VALUES["data_key_obj"],
            )
        excinfo.match("Header authorization failed") 
开发者ID:aws,项目名称:aws-encryption-sdk-python,代码行数:15,代码来源:test_deserialize.py

示例4: auth_decrypt

# 需要导入模块: from cryptography import exceptions [as 别名]
# 或者: from cryptography.exceptions import InvalidTag [as 别名]
def auth_decrypt(self, A, C, seq_num):
        """
        Decrypt the data and verify the authentication code (in this order).
        If the verification fails, an AEADTagError is raised. It is the user's
        responsibility to catch it if deemed useful. If we lack the key, we
        raise a CipherError which contains the encrypted input.
        """
        C, mac = C[:-self.tag_len], C[-self.tag_len:]
        if False in six.itervalues(self.ready):
            raise CipherError(C, mac)

        if hasattr(self, "pc_cls"):
            self._cipher.mode._initialization_vector = self._get_nonce(seq_num)
            self._cipher.mode._tag = mac
            decryptor = self._cipher.decryptor()
            decryptor.authenticate_additional_data(A)
            P = decryptor.update(C)
            try:
                decryptor.finalize()
            except InvalidTag:
                raise AEADTagError(P, mac)
        else:
            try:
                if (conf.crypto_valid_advanced and
                        isinstance(self._cipher, AESCCM)):
                    P = self._cipher.decrypt(self._get_nonce(seq_num), C + mac, A)  # noqa: E501
                else:
                    if (conf.crypto_valid_advanced and
                            isinstance(self, Cipher_CHACHA20_POLY1305)):
                        A += struct.pack("!H", len(C))
                    P = self._cipher.decrypt(self._get_nonce(seq_num), C + mac, A)  # noqa: E501
            except InvalidTag:
                raise AEADTagError("<unauthenticated data>", mac)
        return P, mac 
开发者ID:secdev,项目名称:scapy,代码行数:36,代码来源:cipher_aead.py

示例5: decrypt

# 需要导入模块: from cryptography import exceptions [as 别名]
# 或者: from cryptography.exceptions import InvalidTag [as 别名]
def decrypt(self, data: bytes) -> bytes:
        if not self.handshake_finished:
            raise NoiseHandshakeError('Handshake not finished yet!')
        if not isinstance(data, bytes) or len(data) > MAX_MESSAGE_LEN:
            raise NoiseInvalidMessage('Data must be bytes and less or equal {} bytes in length'.format(MAX_MESSAGE_LEN))
        try:
            return self.noise_protocol.cipher_state_decrypt.decrypt_with_ad(None, data)
        except InvalidTag:
            raise NoiseInvalidMessage('Failed authentication of message') 
开发者ID:plizonczyk,项目名称:noiseprotocol,代码行数:11,代码来源:connection.py

示例6: decrypt

# 需要导入模块: from cryptography import exceptions [as 别名]
# 或者: from cryptography.exceptions import InvalidTag [as 别名]
def decrypt(ciphertext: bytes, capsule: Capsule, decrypting_key: UmbralPrivateKey,
            check_proof: bool = True) -> bytes:
    """
    Opens the capsule and gets what's inside.

    We hope that's a symmetric key, which we use to decrypt the ciphertext
    and return the resulting cleartext.
    """

    if not isinstance(ciphertext, bytes) or len(ciphertext) < DEM_NONCE_SIZE:
        raise ValueError("Input ciphertext must be a bytes object of length >= {}".format(DEM_NONCE_SIZE))
    elif not isinstance(capsule, Capsule) or not capsule.verify():
        raise Capsule.NotValid
    elif not isinstance(decrypting_key, UmbralPrivateKey):
        raise TypeError("The decrypting key is not an UmbralPrivateKey")

    if capsule._attached_cfrags:
        # Since there are cfrags attached, we assume this is Bob opening the Capsule.
        # (i.e., this is a re-encrypted capsule)
        encapsulated_key = _open_capsule(capsule, decrypting_key, check_proof=check_proof)
    else:
        # Since there aren't cfrags attached, we assume this is Alice opening the Capsule.
        # (i.e., this is an original capsule)
        encapsulated_key = _decapsulate_original(decrypting_key, capsule)

    dem = UmbralDEM(encapsulated_key)
    try:
        cleartext = dem.decrypt(ciphertext, authenticated_data=bytes(capsule))
    except InvalidTag as e:
        raise UmbralDecryptionError() from e

    return cleartext 
开发者ID:nucypher,项目名称:pyUmbral,代码行数:34,代码来源:pre.py

示例7: test_encrypt_decrypt_associated_data

# 需要导入模块: from cryptography import exceptions [as 别名]
# 或者: from cryptography.exceptions import InvalidTag [as 别名]
def test_encrypt_decrypt_associated_data():
    key = os.urandom(32)
    aad = b'secret code 1234'

    dem = UmbralDEM(key)

    plaintext = b'peace at dawn'

    ciphertext0 = dem.encrypt(plaintext, authenticated_data=aad)
    ciphertext1 = dem.encrypt(plaintext, authenticated_data=aad)

    assert ciphertext0 != plaintext
    assert ciphertext1 != plaintext

    assert ciphertext0 != ciphertext1

    assert ciphertext0[:DEM_NONCE_SIZE] != ciphertext1[:DEM_NONCE_SIZE]

    cleartext0 = dem.decrypt(ciphertext0, authenticated_data=aad)
    cleartext1 = dem.decrypt(ciphertext1, authenticated_data=aad)

    assert cleartext0 == plaintext
    assert cleartext1 == plaintext

    # Attempt decryption with invalid associated data
    with pytest.raises(InvalidTag):
        cleartext2 = dem.decrypt(ciphertext0, authenticated_data=b'wrong data') 
开发者ID:nucypher,项目名称:pyUmbral,代码行数:29,代码来源:test_dem.py

示例8: decrypt

# 需要导入模块: from cryptography import exceptions [as 别名]
# 或者: from cryptography.exceptions import InvalidTag [as 别名]
def decrypt(self, jsons):
        """Import file is AES GCM encrypted, let's decrypt it.

        Based on the import script from Aegis:
        https://github.com/beemdevelopment/Aegis/blob/master/scripts/decrypt.py
        Format documentation:
        https://github.com/beemdevelopment/Aegis/blob/master/docs/vault.md
        """
        if not CRYPTOGRAPHY:
            raise ImportError(name='cryptography')

        password = getpassword(self.prefix)
        master_key = None
        for slot in jsons['header']['slots']:
            if slot['type'] != 1:
                continue

            kdf = Scrypt(salt=bytes.fromhex(slot['salt']),
                         length=32,
                         n=slot['n'],
                         r=slot['r'],
                         p=slot['p'],
                         backend=default_backend())
            key = kdf.derive(password.encode("utf-8"))

            cipher = AESGCM(key)
            param = slot['key_params']
            try:
                nonce = bytes.fromhex(param['nonce'])
                data = bytes.fromhex(slot['key']) + bytes.fromhex(param['tag'])
                master_key = cipher.decrypt(nonce=nonce,
                                            data=data,
                                            associated_data=None)
            except InvalidTag:  # pragma: no cover
                pass

        if master_key is None:  # pragma: no cover
            raise FormatError("unable to decrypt the master key.")

        cipher = AESGCM(master_key)
        param = jsons['header']['params']
        content = base64.b64decode(jsons['db']) + bytes.fromhex(param['tag'])
        plain = cipher.decrypt(nonce=bytes.fromhex(param['nonce']),
                               data=content,
                               associated_data=None)
        return plain.decode('utf-8') 
开发者ID:roddhjav,项目名称:pass-import,代码行数:48,代码来源:aegis.py

示例9: decrypt

# 需要导入模块: from cryptography import exceptions [as 别名]
# 或者: from cryptography.exceptions import InvalidTag [as 别名]
def decrypt(self, crypto, circuit=None, relay_session_keys=None):
        if self.plaintext:
            return

        if circuit:
            if not circuit.hops:
                raise CryptoException("Error decrypting message for 0-hop circuit %d" % self.circuit_id)

            # Remove all the encryption layers
            for layer, hop in enumerate(circuit.hops):
                try:
                    self.message = crypto.decrypt_str(self.message,
                                                      hop.session_keys[ORIGINATOR],
                                                      hop.session_keys[ORIGINATOR_SALT])
                except InvalidTag as e:
                    raise CryptoException("Got exception %r when trying to remove encryption layer %s "
                                          "for message: %r received for circuit_id: %s, circuit_hops: %r" %
                                          (e, layer, self.message, self.circuit_id, circuit.hops))

            if circuit.hs_session_keys and circuit.ctype in [CIRCUIT_TYPE_RP_SEEDER, CIRCUIT_TYPE_RP_DOWNLOADER]:
                direction = int(circuit.ctype == CIRCUIT_TYPE_RP_DOWNLOADER)
                direction_salt = direction + 2
                self.message = crypto.decrypt_str(self.message,
                                                  circuit.hs_session_keys[direction],
                                                  circuit.hs_session_keys[direction_salt])

        elif relay_session_keys:
            try:
                self.message = crypto.decrypt_str(self.message,
                                                  relay_session_keys[EXIT_NODE],
                                                  relay_session_keys[EXIT_NODE_SALT])
            except InvalidTag as e:
                # Reasons that can cause this:
                # - The introductionpoint circuit is extended with a candidate
                # that is already part of the circuit, causing a crypto error.
                # Should not happen anyway, thorough analysis of the debug log
                # may reveal why and how this candidate is discovered.
                # - The pubkey of the introduction point changed (e.g. due to a
                # restart), while other peers in the network are still exchanging
                # the old key information.
                # - A hostile peer may have forged the key of a candidate while
                # pexing information about candidates, thus polluting the network
                # with wrong information. I doubt this is the case but it's
                # possible. :)
                # (from https://github.com/Tribler/tribler/issues/1932#issuecomment-182035383)
                raise CryptoException("Got exception %r when trying to decrypt relay message: "
                                      "cell received for circuit_id: %s" % (e, self.circuit_id))

        else:
            raise CryptoException("Error decrypting message for unknown circuit %d" % self.circuit_id) 
开发者ID:Tribler,项目名称:py-ipv8,代码行数:52,代码来源:payload.py

示例10: decrypt

# 需要导入模块: from cryptography import exceptions [as 别名]
# 或者: from cryptography.exceptions import InvalidTag [as 别名]
def decrypt(self, sa, esp, key, icv_size=None, esn_en=False, esn=0):
        """
        Decrypt an ESP packet

        :param sa: the SecurityAssociation associated with the ESP packet.
        :param esp: an encrypted ESP packet
        :param key: the secret key used for encryption
        :param icv_size: the length of the icv used for integrity check
        :param esn_en: extended sequence number enable which allows to use
                       64-bit sequence number instead of 32-bit when using an
                       AEAD algorithm
        :param esn: extended sequence number (32 MSB)
        :returns: a valid ESP packet encrypted with this algorithm
        :raise scapy.layers.ipsec.IPSecIntegrityError: if the integrity check
            fails with an AEAD algorithm
        """
        if icv_size is None:
            icv_size = self.icv_size if self.is_aead else 0

        iv = esp.data[:self.iv_size]
        data = esp.data[self.iv_size:len(esp.data) - icv_size]
        icv = esp.data[len(esp.data) - icv_size:]

        if self.cipher:
            mode_iv = self._format_mode_iv(sa=sa, iv=iv)
            cipher = self.new_cipher(key, mode_iv, icv)
            decryptor = cipher.decryptor()

            if self.is_aead:
                # Tag value check is done during the finalize method
                if esn_en:
                    decryptor.authenticate_additional_data(
                        struct.pack('!LLL', esp.spi, esn, esp.seq))
                else:
                    decryptor.authenticate_additional_data(
                        struct.pack('!LL', esp.spi, esp.seq))
            try:
                data = decryptor.update(data) + decryptor.finalize()
            except InvalidTag as err:
                raise IPSecIntegrityError(err)

        # extract padlen and nh
        padlen = orb(data[-2])
        nh = orb(data[-1])

        # then use padlen to determine data and padding
        data = data[:len(data) - padlen - 2]
        padding = data[len(data) - padlen - 2: len(data) - 2]

        return _ESPPlain(spi=esp.spi,
                         seq=esp.seq,
                         iv=iv,
                         data=data,
                         padding=padding,
                         padlen=padlen,
                         nh=nh,
                         icv=icv)

###############################################################################
# The names of the encryption algorithms are the same than in scapy.contrib.ikev2  # noqa: E501
# see http://www.iana.org/assignments/ikev2-parameters/ikev2-parameters.xhtml 
开发者ID:secdev,项目名称:scapy,代码行数:63,代码来源:ipsec.py

示例11: decrypt

# 需要导入模块: from cryptography import exceptions [as 别名]
# 或者: from cryptography.exceptions import InvalidTag [as 别名]
def decrypt(self, esp, key, icv_size=None):
        """
        Decrypt an ESP packet

        @param esp:        an encrypted ESP packet
        @param key:        the secret key used for encryption
        @param icv_size:   the length of the icv used for integrity check

        @return:    a valid ESP packet encrypted with this algorithm
        @raise IPSecIntegrityError: if the integrity check fails with an AEAD
                                    algorithm
        """
        if icv_size is None:
            icv_size = self.icv_size if self.is_aead else 0

        iv = esp.data[:self.iv_size]
        data = esp.data[self.iv_size:len(esp.data) - icv_size]
        icv = esp.data[len(esp.data) - icv_size:]

        if self.cipher:
            cipher = self.new_cipher(key, iv, icv)
            decryptor = cipher.decryptor()

            if self.is_aead:
                # Tag value check is done during the finalize method
                decryptor.authenticate_additional_data(
                    struct.pack('!LL', esp.spi, esp.seq)
                )

            try:
                data = decryptor.update(data) + decryptor.finalize()
            except InvalidTag as err:
                raise IPSecIntegrityError(err)

        # extract padlen and nh
        padlen = (data[-2])
        nh = data[-1]

        # then use padlen to determine data and padding
        data = data[:len(data) - padlen - 2]
        padding = data[len(data) - padlen - 2: len(data) - 2]

        return _ESPPlain(spi=esp.spi,
                        seq=esp.seq,
                        iv=iv,
                        data=data,
                        padding=padding,
                        padlen=padlen,
                        nh=nh,
                        icv=icv)

#------------------------------------------------------------------------------
# The names of the encryption algorithms are the same than in kamene.contrib.ikev2
# see http://www.iana.org/assignments/ikev2-parameters/ikev2-parameters.xhtml 
开发者ID:phaethon,项目名称:kamene,代码行数:56,代码来源:ipsec.py

示例12: decrypt

# 需要导入模块: from cryptography import exceptions [as 别名]
# 或者: from cryptography.exceptions import InvalidTag [as 别名]
def decrypt(self, esp, key, icv_size=None):
        """
        Decrypt an ESP packet

        @param esp:        an encrypted ESP packet
        @param key:        the secret key used for encryption
        @param icv_size:   the length of the icv used for integrity check

        @return:    a valid ESP packet encrypted with this algorithm
        @raise IPSecIntegrityError: if the integrity check fails with an AEAD
                                    algorithm
        """
        if icv_size is None:
            icv_size = self.icv_size if self.is_aead else 0

        iv = esp.data[:self.iv_size]
        data = esp.data[self.iv_size:len(esp.data) - icv_size]
        icv = esp.data[len(esp.data) - icv_size:]

        if self.cipher:
            cipher = self.new_cipher(key, iv, icv)
            decryptor = cipher.decryptor()

            if self.is_aead:
                # Tag value check is done during the finalize method
                decryptor.authenticate_additional_data(
                    struct.pack('!LL', esp.spi, esp.seq)
                )

            try:
                data = decryptor.update(data) + decryptor.finalize()
            except InvalidTag as err:
                raise IPSecIntegrityError(err)

        # extract padlen and nh
        padlen = (data[-2])
        nh = data[-1]

        # then use padlen to determine data and padding
        data = data[:len(data) - padlen - 2]
        padding = data[len(data) - padlen - 2: len(data) - 2]

        return _ESPPlain(spi=esp.spi,
                        seq=esp.seq,
                        iv=iv,
                        data=data,
                        padding=padding,
                        padlen=padlen,
                        nh=nh,
                        icv=icv)

#------------------------------------------------------------------------------
# The names of the encryption algorithms are the same than in scapy.contrib.ikev2
# see http://www.iana.org/assignments/ikev2-parameters/ikev2-parameters.xhtml 
开发者ID:entynetproject,项目名称:arissploit,代码行数:56,代码来源:ipsec.py


注:本文中的cryptography.exceptions.InvalidTag方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。