Python cryptography.exceptions.InvalidSignature() Examples

The following are 30 code examples of cryptography.exceptions.InvalidSignature(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cryptography.exceptions , or try the search function .
Example #1
Source File: algorithms.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def verify(self, msg, key, sig):
            verifier = key.verifier(
                sig,
                padding.PSS(
                    mgf=padding.MGF1(self.hash_alg()),
                    salt_length=self.hash_alg.digest_size
                ),
                self.hash_alg()
            )

            verifier.update(msg)

            try:
                verifier.verify()
                return True
            except InvalidSignature:
                return False 
Example #2
Source File: crypto.py    From keylime with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def rsa_verify(public_key, message, signature):
    """ RSA verify message  """
    try:
        public_key.verify(
            base64.b64decode(signature),
            message,
            padding.PSS(
                mgf=padding.MGF1(hashes.SHA256()),
                salt_length=padding.PSS.MAX_LENGTH
                ),
            hashes.SHA256()
        )
    except exceptions.InvalidSignature:
        return False
    except Exception as e:
        raise e
    return True 
Example #3
Source File: ecdsakey.py    From imoocc with GNU General Public License v2.0 6 votes vote down vote up
def verify_ssh_sig(self, data, msg):
        if msg.get_text() != self.ecdsa_curve.key_format_identifier:
            return False
        sig = msg.get_binary()
        sigR, sigS = self._sigdecode(sig)
        signature = encode_dss_signature(sigR, sigS)

        verifier = self.verifying_key.verifier(
            signature, ec.ECDSA(self.ecdsa_curve.hash_object())
        )
        verifier.update(data)
        try:
            verifier.verify()
        except InvalidSignature:
            return False
        else:
            return True 
Example #4
Source File: rsakey.py    From imoocc with GNU General Public License v2.0 6 votes vote down vote up
def verify_ssh_sig(self, data, msg):
        if msg.get_text() != 'ssh-rsa':
            return False
        key = self.key
        if isinstance(key, rsa.RSAPrivateKey):
            key = key.public_key()

        verifier = key.verifier(
            signature=msg.get_binary(),
            padding=padding.PKCS1v15(),
            algorithm=hashes.SHA1(),
        )
        verifier.update(data)
        try:
            verifier.verify()
        except InvalidSignature:
            return False
        else:
            return True 
Example #5
Source File: test_crypto_utils.py    From st2 with Apache License 2.0 6 votes vote down vote up
def test_exception_is_thrown_on_invalid_hmac_signature(self):
        aes_key = AESKey.generate()
        plaintext = 'hello world ponies 2'
        encrypted = cryptography_symmetric_encrypt(aes_key, plaintext)

        # Verify original non manipulated value can be decrypted
        decrypted = cryptography_symmetric_decrypt(aes_key, encrypted)
        self.assertEqual(decrypted, plaintext)

        # Corrupt the HMAC signature (last part is the HMAC signature)
        encrypted_malformed = binascii.unhexlify(encrypted)
        encrypted_malformed = encrypted_malformed[:-3]
        encrypted_malformed += b'abc'
        encrypted_malformed = binascii.hexlify(encrypted_malformed)

        # Verify corrupted value results in an excpetion
        expected_msg = 'Signature did not match digest'
        self.assertRaisesRegexp(InvalidSignature, expected_msg, cryptography_symmetric_decrypt,
                                aes_key, encrypted_malformed) 
Example #6
Source File: ecc.py    From synapse with Apache License 2.0 6 votes vote down vote up
def verify(self, byts, sign):
        '''
        Verify the signature for the given bytes using the ECC
        public key.

        Args:
            byts (bytes): The data bytes.
            sign (bytes): The signature bytes.

        Returns:
            bool: True if the data was verified, False otherwise.
        '''
        try:
            chosen_hash = c_hashes.SHA256()
            hasher = c_hashes.Hash(chosen_hash, default_backend())
            hasher.update(byts)
            digest = hasher.finalize()
            self.publ.verify(sign,
                             digest,
                             c_ec.ECDSA(c_utils.Prehashed(chosen_hash))
                             )
            return True
        except InvalidSignature:
            logger.exception('Error in publ.verify')
            return False 
Example #7
Source File: ecdsalib.py    From virtualchain with GNU General Public License v3.0 6 votes vote down vote up
def verify_digest(hash_hex, pubkey_hex, sigb64, hashfunc=hashlib.sha256):
    """
    Given a digest, public key (as hex), and a base64 signature,
    verify that the public key signed the digest.
    Return True if so
    Return False if not
    """
    if not isinstance(hash_hex, (str, unicode)):
        raise ValueError("hash hex is not a string")

    hash_hex = str(hash_hex)
    pubk_uncompressed_hex = keylib.key_formatting.decompress(pubkey_hex)
    sig_r, sig_s = decode_signature(sigb64)

    pubk = ec.EllipticCurvePublicNumbers.from_encoded_point(ec.SECP256K1(), pubk_uncompressed_hex.decode('hex')).public_key(default_backend())
    signature = encode_dss_signature(sig_r, sig_s)

    try:
        pubk.verify(signature, hash_hex.decode('hex'), ec.ECDSA(utils.Prehashed(hashes.SHA256())))
        return True
    except InvalidSignature:
        return False 
Example #8
Source File: crypto.py    From fabric-sdk-py with Apache License 2.0 6 votes vote down vote up
def verify(self, public_key, message, signature):
        """ECDSA verify signature.

        :param public_key: Signing public key
        :param message: Origin message
        :param signature: Signature of message
        :return: verify result boolean, True means valid
        """
        if not (self._check_malleability(signature)):
            return False
        try:
            public_key.verify(signature, message,
                              ec.ECDSA(self.sign_hash_algorithm))
        except InvalidSignature:
            return False
        except Exception as e:
            raise e
        return True 
Example #9
Source File: jwa.py    From jwcrypto with GNU Lesser General Public License v3.0 6 votes vote down vote up
def decrypt(self, k, a, iv, e, t):
        """ Decrypt according to the selected encryption and hashing
        functions.
        :param k: Encryption key (optional)
        :param a: Additional Authenticated Data
        :param iv: Initialization Vector
        :param e: Ciphertext
        :param t: Authentication Tag

        Returns plaintext or raises an error
        """
        hkey = k[:_inbytes(self.keysize)]
        dkey = k[_inbytes(self.keysize):]

        # verify mac
        if not constant_time.bytes_eq(t, self._mac(hkey, a, iv, e)):
            raise InvalidSignature('Failed to verify MAC')

        # decrypt
        cipher = Cipher(algorithms.AES(dkey), modes.CBC(iv),
                        backend=self.backend)
        decryptor = cipher.decryptor()
        d = decryptor.update(e) + decryptor.finalize()
        unpadder = PKCS7(self.blocksize).unpadder()
        return unpadder.update(d) + unpadder.finalize() 
Example #10
Source File: cms.py    From zentral with Apache License 2.0 6 votes vote down vote up
def verify_certificate_signature(certificate, signer, payload):
    public_key = certificate.public_key()
    signature = signer['signature'].native
    if "signed_attrs" in signer and signer["signed_attrs"]:
        # Seen with the iPhone simulator for example
        signed_string = signer["signed_attrs"].dump()
        if signed_string.startswith(b'\xa0'):
            # TODO: WTF!!!
            # see https://stackoverflow.com/questions/24567623/how-to-see-what-attributes-are-signed-inside-pkcs7#24581628  # NOQA
            signed_string = b'\x31' + signed_string[1:]
    else:
        signed_string = payload
    asymmetric_padding = get_cryptography_asymmetric_padding(signer)
    hash_algorithm = get_cryptography_hash_algorithm(signer)
    try:
        public_key.verify(signature, signed_string,
                          asymmetric_padding(), hash_algorithm())
    except InvalidSignature:
        return False
    else:
        return True 
Example #11
Source File: tokenizer.py    From blockstack-auth-python with MIT License 6 votes vote down vote up
def verify(self, token, verifying_key):
        # grab the token parts
        token_parts = self._unpack(token)
        header, payload, raw_signature, signing_input = token_parts
        # load the verifying key
        verifying_key = load_verifying_key(verifying_key, self.crypto_backend)
        # convert the raw_signature to DER format
        der_signature = raw_to_der_signature(
            raw_signature, verifying_key.curve)
        # initialize the verifier
        verifier = self._get_verifier(verifying_key, der_signature)
        verifier.update(signing_input)
        # check to see whether the signature is valid
        try:
            verifier.verify()
        except InvalidSignature:
            # raise DecodeError('Signature verification failed')
            return False
        return True 
Example #12
Source File: cryptography_backend.py    From python-jose with MIT License 5 votes vote down vote up
def verify(self, msg, sig):
        try:
            self.prepared_key.verify(
                sig,
                msg,
                padding.PKCS1v15(),
                self.hash_alg()
            )
            return True
        except InvalidSignature:
            return False 
Example #13
Source File: crypto.py    From spid-testenv2 with GNU Affero General Public License v3.0 5 votes vote down vote up
def verify(self, pubkey, signed_data, signature):
        try:
            pubkey.verify(signature, signed_data, self._padding, self._digest)
        except InvalidSignature:
            return False
        else:
            return True 
Example #14
Source File: transaction.py    From lbry-sdk with MIT License 5 votes vote down vote up
def is_signature_valid(encoded_signature, signature_digest, public_key_bytes):
        try:
            public_key = load_der_public_key(public_key_bytes, default_backend())
            public_key.verify(encoded_signature, signature_digest, ec.ECDSA(Prehashed(hashes.SHA256())))
            return True
        except (ValueError, InvalidSignature):
            pass
        return False 
Example #15
Source File: fields.py    From PGPy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def verify(self, subj, sigbytes, hash_alg):
        # zero-pad sigbytes if necessary
        sigbytes = (b'\x00' * (self.n.byte_length() - len(sigbytes))) + sigbytes
        try:
            self.__pubkey__().verify(sigbytes, subj, padding.PKCS1v15(), hash_alg)
        except InvalidSignature:
            return False
        return True 
Example #16
Source File: fields.py    From PGPy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def verify(self, subj, sigbytes, hash_alg):
        try:
            self.__pubkey__().verify(sigbytes, subj, hash_alg)
        except InvalidSignature:
            return False
        return True 
Example #17
Source File: jwk.py    From python-jwt with Apache License 2.0 5 votes vote down vote up
def verify(self, message: bytes, signature: bytes, **options) -> bool:
        hash_fun = self._get_hash_fun(options)
        if self.is_sign_key():
            pubkey = self.keyobj.public_key()
        else:
            pubkey = self.keyobj
        try:
            pubkey.verify(signature, message, padding.PKCS1v15(), hash_fun())
            return True
        except InvalidSignature:
            return False 
Example #18
Source File: fields.py    From PGPy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def verify(self, subj, sigbytes, hash_alg):
        try:
            self.__pubkey__().verify(sigbytes, subj, ec.ECDSA(hash_alg))
        except InvalidSignature:
            return False
        return True 
Example #19
Source File: decorators.py    From commandment with MIT License 5 votes vote down vote up
def verify_mdm_signature(f):
    """Verify the signature supplied by the client in the request using the ``Mdm-Signature`` header.

    If the authenticity of the message has been verified,
    then the signer is attached to the **g** object as **g.signer**.

    In unit tests, this decorator is completely disabled by the presence of app.testing = True.
    You can also disable enforcement in dev by setting the flask setting DEBUG to true.

    :reqheader Mdm-Signature: BASE64-encoded CMS Detached Signature of the message. (if `SignMessage` was true)
    """
    @wraps(f)
    def decorator(*args, **kwargs):
        if current_app.testing:
            return f(*args, **kwargs)

        if 'Mdm-Signature' not in request.headers:
            raise TypeError('Client did not supply an Mdm-Signature header but signature is required.')

        detached_signature = b64decode(request.headers['Mdm-Signature'])

        try:
            signers, signed_data = _verify_cms_signers(detached_signature, detached=True)
            g.signers = signers
            g.signed_data = signed_data
        except InvalidSignature as e:
            current_app.logger.warn("Invalid Signature in Mdm-Signature header")
            if not current_app.config.get('DEBUG', False):
                return abort(403)

        return f(*args, **kwargs)

    return decorator 
Example #20
Source File: fields.py    From PGPy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def verify(self, subj, sigbytes, hash_alg):
        # GnuPG requires a pre-hashing with EdDSA
        # https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-06#section-14.8
        digest = hashes.Hash(hash_alg, backend=default_backend())
        digest.update(subj)
        subj = digest.finalize()
        try:
            self.__pubkey__().verify(sigbytes, subj)
        except InvalidSignature:
            return False
        return True 
Example #21
Source File: dsskey.py    From imoocc with GNU General Public License v2.0 5 votes vote down vote up
def verify_ssh_sig(self, data, msg):
        if len(msg.asbytes()) == 40:
            # spies.com bug: signature has no header
            sig = msg.asbytes()
        else:
            kind = msg.get_text()
            if kind != 'ssh-dss':
                return 0
            sig = msg.get_binary()

        # pull out (r, s) which are NOT encoded as mpints
        sigR = util.inflate_long(sig[:20], 1)
        sigS = util.inflate_long(sig[20:], 1)

        signature = encode_dss_signature(sigR, sigS)

        key = dsa.DSAPublicNumbers(
            y=self.y,
            parameter_numbers=dsa.DSAParameterNumbers(
                p=self.p,
                q=self.q,
                g=self.g
            )
        ).public_key(backend=default_backend())
        verifier = key.verifier(signature, hashes.SHA1())
        verifier.update(data)
        try:
            verifier.verify()
        except InvalidSignature:
            return False
        else:
            return True 
Example #22
Source File: fernet.py    From quickstart-redhat-openshift with Apache License 2.0 5 votes vote down vote up
def _verify_signature(self, data):
        h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend)
        h.update(data[:-32])
        try:
            h.verify(data[-32:])
        except InvalidSignature:
            raise InvalidToken 
Example #23
Source File: algorithms.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def verify(self, msg, key, sig):
            verifier = key.verifier(
                sig,
                padding.PKCS1v15(),
                self.hash_alg()
            )

            verifier.update(msg)

            try:
                verifier.verify()
                return True
            except InvalidSignature:
                return False 
Example #24
Source File: algorithms.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def verify(self, msg, key, sig):
            try:
                der_sig = raw_to_der_signature(sig, key.curve)
            except ValueError:
                return False

            verifier = key.verifier(der_sig, ec.ECDSA(self.hash_alg()))

            verifier.update(msg)

            try:
                verifier.verify()
                return True
            except InvalidSignature:
                return False 
Example #25
Source File: verifier.py    From alexa-skills-kit-sdk-for-python with Apache License 2.0 5 votes vote down vote up
def _valid_request_body(
            self, cert_chain, signature, serialized_request_env):
        # type: (Certificate, str, str) -> None
        """Validate the request body hash with signature.

        This method checks if the hash value of the request body
        matches with the hash value of the signature, decrypted using
        certificate chain. A
        :py:class:`VerificationException` is raised if there is a
        mismatch.

        :param cert_chain: Certificate chain to be validated
        :type cert_chain: cryptography.x509.Certificate
        :param signature: Encrypted signature of the request
        :type: str
        :param serialized_request_env: Raw request body
        :type: str
        :raises: :py:class:`VerificationException` if certificate is
            not valid
        """
        decoded_signature = base64.b64decode(signature)
        public_key = cert_chain.public_key()  # type: rsa._RSAPublicKey
        request_env_bytes = serialized_request_env.encode(CHARACTER_ENCODING)

        try:
            public_key.verify(
                decoded_signature, request_env_bytes,
                self._padding, self._hash_algorithm)
        except InvalidSignature as e:
            raise VerificationException("Request body is not valid", e) 
Example #26
Source File: signing.py    From pyUmbral with GNU General Public License v3.0 5 votes vote down vote up
def verify(self, message: bytes,
               verifying_key: UmbralPublicKey,
               is_prehashed: bool = False) -> bool:
        """
        Verifies that a message's signature was valid.

        :param message: The message to verify
        :param verifying_key: UmbralPublicKey of the signer
        :param is_prehashed: True if the message has been prehashed previously
        :return: True if valid, False if invalid
        """
        cryptography_pub_key = verifying_key.to_cryptography_pubkey()
        if is_prehashed:
            signature_algorithm = ECDSA(utils.Prehashed(self.hash_algorithm()))
        else:
            signature_algorithm = ECDSA(self.hash_algorithm())

        # TODO: Raise error instead of returning boolean
        try:
            cryptography_pub_key.verify(
                signature=self._der_encoded_bytes(),
                data=message,
                signature_algorithm=signature_algorithm
            )
        except InvalidSignature:
            return False
        return True 
Example #27
Source File: fernet.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _verify_signature(self, data):
        h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend)
        h.update(data[:-32])
        try:
            h.verify(data[-32:])
        except InvalidSignature:
            raise InvalidToken 
Example #28
Source File: poly1305.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def verify(self, tag):
        mac = self.finalize()
        if not constant_time.bytes_eq(mac, tag):
            raise InvalidSignature("Value did not match computed tag.") 
Example #29
Source File: validators.py    From refstack with Apache License 2.0 5 votes vote down vote up
def validate(self, request):
        """Validate uploaded test results."""
        super(TestResultValidator, self).validate(request)
        if request.headers.get('X-Signature') or \
                request.headers.get('X-Public-Key'):
            try:
                sign = binascii.a2b_hex(request.headers.get('X-Signature', ''))
            except (binascii.Error, TypeError) as e:
                raise api_exc.ValidationError('Malformed signature', e)

            try:
                key = load_ssh_public_key(
                    request.headers.get('X-Public-Key', ''),
                    backend=backends.default_backend()
                )
            except (binascii.Error, ValueError) as e:
                raise api_exc.ValidationError('Malformed public key', e)

            verifier = key.verifier(sign, padding.PKCS1v15(), hashes.SHA256())
            verifier.update(request.body)
            try:
                verifier.verify()
            except InvalidSignature:
                raise api_exc.ValidationError('Signature verification failed')
        if self._is_empty_result(request):
            raise api_exc.ValidationError('Uploaded results must contain at '
                                          'least one passing test.') 
Example #30
Source File: validators.py    From refstack with Apache License 2.0 5 votes vote down vote up
def validate(self, request):
        """Validate uploaded test results."""
        super(PubkeyValidator, self).validate(request)
        body = json.loads(request.body.decode('utf-8'))
        key_format = body['raw_key'].strip().split()[0]

        if key_format not in ('ssh-dss', 'ssh-rsa',
                              'pgp-sign-rsa', 'pgp-sign-dss'):
            raise api_exc.ValidationError('Public key has unsupported format')

        try:
            sign = binascii.a2b_hex(body['self_signature'])
        except (binascii.Error, TypeError) as e:
            raise api_exc.ValidationError('Malformed signature', e)

        try:
            key = load_ssh_public_key(body['raw_key'].encode('utf-8'),
                                      backend=backends.default_backend())
        except (binascii.Error, ValueError) as e:
            raise api_exc.ValidationError('Malformed public key', e)

        verifier = key.verifier(sign, padding.PKCS1v15(), hashes.SHA256())
        verifier.update('signature'.encode('utf-8'))
        try:
            verifier.verify()
        except InvalidSignature:
            raise api_exc.ValidationError('Signature verification failed')