Beispiel #1
0
def test_encode_dss_non_integer():
    with pytest.raises(ValueError):
        encode_dss_signature("h", 3)

    with pytest.raises(ValueError):
        encode_dss_signature("3", "2")

    with pytest.raises(ValueError):
        encode_dss_signature(3, "h")

    with pytest.raises(ValueError):
        encode_dss_signature(3.3, 1.2)

    with pytest.raises(ValueError):
        encode_dss_signature("hello", "world")
Beispiel #2
0
    def verify(self, signature, msg):
        """
        Verify whether a given signature is correct for a message.

        :param signature: the given signature
        :param msg: the given message
        """
        length = len(signature) / 2
        r = signature[:length]
        # remove all "\x00" prefixes
        while r and r[0] == "\x00":
            r = r[1:]
        # prepend "\x00" when the most significant bit is set
        if ord(r[0]) & 128:
            r = "\x00" + r

        s = signature[length:]
        # remove all "\x00" prefixes
        while s and s[0] == "\x00":
            s = s[1:]
        # prepend "\x00" when the most significant bit is set
        if ord(s[0]) & 128:
            s = "\x00" + s
        # turn back into int
        r = int(hexlify(r), 16)
        s = int(hexlify(s), 16)
        # verify
        try:
            self.ec.verifier(encode_dss_signature(r, s),
                             ec.ECDSA(hashes.SHA1()))
            return True
        except InvalidSignature:
            return False
Beispiel #3
0
    def extract_signature(auth):
        # type: (str) -> Tuple[str, str]
        """Fix the JWT auth token.

        The JWA spec defines the signature to be a pair of 32octet encoded
        longs.
        The `ecdsa` library signs using a raw, 32octet pair of values (s, r).
        Cryptography, which uses OpenSSL, uses a DER sequence of (s, r).
        This function converts the raw ecdsa to DER.

        :param auth: A JWT authorization token.
        :type auth: str

        :return tuple containing the signature material and signature

        """
        payload, asig = auth.encode('utf8').rsplit(".", 1)
        sig = base64.urlsafe_b64decode(repad(asig))
        if len(sig) != 64:
            return payload, sig

        encoded = utils.encode_dss_signature(
            s=int(binascii.hexlify(sig[32:]), 16),
            r=int(binascii.hexlify(sig[:32]), 16)
        )
        return payload, encoded
Beispiel #4
0
    def test_signature_failures(self, backend, vector):
        hash_type = _HASH_TYPES[vector['digest_algorithm']]
        curve_type = ec._CURVE_TYPES[vector['curve']]

        _skip_ecdsa_vector(backend, curve_type, hash_type)

        key = ec.EllipticCurvePublicNumbers(
            vector['x'],
            vector['y'],
            curve_type()
        ).public_key(backend)

        signature = encode_dss_signature(vector['r'], vector['s'])

        verifier = key.verifier(
            signature,
            ec.ECDSA(hash_type())
        )
        verifier.update(vector['message'])

        if vector["fail"] is True:
            with pytest.raises(exceptions.InvalidSignature):
                verifier.verify()
        else:
            verifier.verify()
Beispiel #5
0
    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())
        try:
            key.verify(signature, data, hashes.SHA1())
        except InvalidSignature:
            return False
        else:
            return True
Beispiel #6
0
def ecdsa_verify(data_file, sig_data, pub_key_file):

    data_f = open(data_file, "rb")
    pay_load = data_f.read()
    data_f.close()

    sig_f = open(sig_data, "rb")
    r_s = sig_f.read()
    sig_f.close()

    with open(pub_key_file, 'rb') as fpkey:
        pem_data = fpkey.read()
    cert = load_pem_x509_certificate(pem_data, default_backend())
    public_key = cert.public_key()

    if isinstance(public_key, ec.EllipticCurvePublicKey):

        sig_r = int.from_bytes(r_s[:int(len(r_s) / 2)], byteorder='big')
        sig_s = int.from_bytes(r_s[-int(len(r_s) / 2):], byteorder='big')

        signature = encode_dss_signature(sig_r, sig_s)
        try:
            public_key.verify(signature, pay_load, ec.ECDSA(hashes.SHA384()))
            print("ECDSA Correct signature detected.. :)\n")
        except InvalidSignature:
            print("ECDSA Invalid signature detected.. :(\n")
    else:
        print("RSA not yet supported")
        exit()
Beispiel #7
0
def _ecc_static_length_signature(key, algorithm, digest):
    """Calculates an elliptic curve signature with a static length using pre-calculated hash.

    :param key: Elliptic curve private key
    :type key: cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey
    :param algorithm: Master algorithm to use
    :type algorithm: aws_encryption_sdk.identifiers.Algorithm
    :param bytes digest: Pre-calculated hash digest
    :returns: Signature with required length
    :rtype: bytes
    """
    pre_hashed_algorithm = ec.ECDSA(Prehashed(algorithm.signing_hash_type()))
    signature = b''
    while len(signature) != algorithm.signature_len:
        _LOGGER.debug(
            'Signature length %d is not desired length %d.  Recalculating.',
            len(signature), algorithm.signature_len)
        signature = key.sign(digest, pre_hashed_algorithm)
        if len(signature) != algorithm.signature_len:
            # Most of the time, a signature of the wrong length can be fixed
            # by negating s in the signature relative to the group order.
            _LOGGER.debug(
                'Signature length %d is not desired length %d.  Negating s.',
                len(signature), algorithm.signature_len)
            r, s = decode_dss_signature(signature)
            s = _ECC_CURVE_PARAMETERS[
                algorithm.signing_algorithm_info.name].order - s
            signature = encode_dss_signature(r, s)
    return signature
Beispiel #8
0
 def verify(self, key, payload, signature):
     pkey = key.get_op_key('verify', self._curve)
     r = signature[:len(signature) // 2]
     s = signature[len(signature) // 2:]
     enc_signature = ec_utils.encode_dss_signature(
         int(hexlify(r), 16), int(hexlify(s), 16))
     pkey.verify(enc_signature, payload, ec.ECDSA(self.hashfn))
Beispiel #9
0
    def test__ecdsa_sha256_response(self, load_key_mock):
        challenge = b'challenge'

        # success case
        private_key = ec.generate_private_key(ec.SECP384R1(), default_backend())
        load_key_mock.return_value = private_key
        r, s = self.manager._ecdsa_sha256_response(challenge)
        r = int.from_bytes(r, 'big')
        s = int.from_bytes(s, 'big')
        signature = encode_dss_signature(r, s)
        private_key.public_key().verify(
            signature, challenge, ec.ECDSA(hashes.SHA256()))

        # no key found
        load_key_mock.reset_mock()
        load_key_mock.side_effect = IOError
        with self.assertRaises(bm.BootstrapError):
            self.manager._ecdsa_sha256_response(challenge)

        # wrong type of key, e.g. rsa
        load_key_mock.reset_mock()
        load_key_mock.return_value = rsa.generate_private_key(
            65537, 2048, default_backend())
        with self.assertRaises(
                bm.BootstrapError,
                msg='Challenge key cannot be used for ECDSA signature'):
            self.manager._ecdsa_sha256_response(challenge)
    def test_dsa_verification(self, vector, backend):
        digest_algorithm = vector['digest_algorithm'].replace("-", "")
        algorithm = self._algorithms_dict[digest_algorithm]
        if (
            not backend.dsa_parameters_supported(
                vector['p'], vector['q'], vector['g']
            ) or not backend.dsa_hash_supported(algorithm)
        ):
            pytest.skip(
                "{0} does not support the provided parameters".format(backend)
            )

        public_key = dsa.DSAPublicNumbers(
            parameter_numbers=dsa.DSAParameterNumbers(
                vector['p'], vector['q'], vector['g']
            ),
            y=vector['y']
        ).public_key(backend)
        sig = encode_dss_signature(vector['r'], vector['s'])
        verifier = public_key.verifier(sig, algorithm())
        verifier.update(vector['msg'])
        if vector['result'] == "F":
            with pytest.raises(InvalidSignature):
                verifier.verify()
        else:
            verifier.verify()
Beispiel #11
0
    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
Beispiel #12
0
    def test_signature_failures(self, backend, vector):
        hash_type = _HASH_TYPES[vector['digest_algorithm']]
        curve_type = ec._CURVE_TYPES[vector['curve']]

        _skip_ecdsa_vector(backend, curve_type, hash_type)

        key = ec.EllipticCurvePublicNumbers(
            vector['x'],
            vector['y'],
            curve_type()
        ).public_key(backend)

        signature = encode_dss_signature(vector['r'], vector['s'])

        if vector["fail"] is True:
            with pytest.raises(exceptions.InvalidSignature):
                key.verify(
                    signature,
                    vector['message'],
                    ec.ECDSA(hash_type())
                )
        else:
            key.verify(
                signature,
                vector['message'],
                ec.ECDSA(hash_type())
            )
Beispiel #13
0
    def test_signatures(self, backend, subtests):
        vectors = itertools.chain(
            load_vectors_from_file(
                os.path.join(
                    "asymmetric", "ECDSA", "FIPS_186-3", "SigGen.txt"
                ),
                load_fips_ecdsa_signing_vectors,
            ),
            load_vectors_from_file(
                os.path.join("asymmetric", "ECDSA", "SECP256K1", "SigGen.txt"),
                load_fips_ecdsa_signing_vectors,
            ),
        )
        for vector in vectors:
            with subtests.test():
                hash_type = _HASH_TYPES[vector["digest_algorithm"]]
                curve_type: typing.Type[ec.EllipticCurve] = ec._CURVE_TYPES[
                    vector["curve"]
                ]

                _skip_ecdsa_vector(backend, curve_type, hash_type)

                key = ec.EllipticCurvePublicNumbers(
                    vector["x"], vector["y"], curve_type()
                ).public_key(backend)

                signature = encode_dss_signature(vector["r"], vector["s"])

                key.verify(signature, vector["message"], ec.ECDSA(hash_type()))
Beispiel #14
0
    def test_dsa_verification(self, backend, subtests):
        vectors = load_vectors_from_file(
            os.path.join("asymmetric", "DSA", "FIPS_186-3", "SigVer.rsp"),
            load_fips_dsa_sig_vectors,
        )
        for vector in vectors:
            with subtests.test():
                digest_algorithm = vector["digest_algorithm"].replace("-", "")
                algorithm = _ALGORITHMS_DICT[digest_algorithm]()

                _skip_if_dsa_not_supported(backend, algorithm, vector["p"],
                                           vector["q"], vector["g"])

                public_key = dsa.DSAPublicNumbers(
                    parameter_numbers=dsa.DSAParameterNumbers(
                        vector["p"], vector["q"], vector["g"]),
                    y=vector["y"],
                ).public_key(backend)
                sig = encode_dss_signature(vector["r"], vector["s"])

                if vector["result"] == "F":
                    with pytest.raises(InvalidSignature):
                        public_key.verify(sig, vector["msg"], algorithm)
                else:
                    public_key.verify(sig, vector["msg"], algorithm)
Beispiel #15
0
 def verify(self, dnskey):
     """
     Verify signature with specified key. Raises a crypto key
     specific exception on failure.
     """
     pubkey = dnskey.key
     hashalg = HASHFUNC[dnskey.algorithm]
     if dnskey.algorithm in [5, 7, 8, 10]:
         _ = pubkey.verify(self.rdata.signature, self.indata,
                           padding.PKCS1v15(), hashalg())
     elif dnskey.algorithm in [13, 14]:
         if dnskey.algorithm == 13:
             sig_r = self.rdata.signature[0:32]
             sig_s = self.rdata.signature[32:]
         elif dnskey.algorithm == 14:
             sig_r = self.rdata.signature[0:48]
             sig_s = self.rdata.signature[48:]
         sig_r = int.from_bytes(sig_r, byteorder='big')
         sig_s = int.from_bytes(sig_s, byteorder='big')
         encoded_sig = utils.encode_dss_signature(sig_r, sig_s)
         _ = pubkey.verify(encoded_sig, self.indata, ec.ECDSA(hashalg()))
     elif dnskey.algorithm in [15, 16]:
         _ = pubkey.verify(self.rdata.signature, self.indata)
     else:
         raise ResError("Unknown key type: {}".format(type(pubkey)))
Beispiel #16
0
    def test_dsa_verification(self, vector, backend):
        digest_algorithm = vector['digest_algorithm'].replace("-", "")
        algorithm = self._algorithms_dict[digest_algorithm]

        _skip_if_dsa_not_supported(
            backend, algorithm, vector['p'], vector['q'], vector['g']
        )

        public_key = dsa.DSAPublicNumbers(
            parameter_numbers=dsa.DSAParameterNumbers(
                vector['p'], vector['q'], vector['g']
            ),
            y=vector['y']
        ).public_key(backend)
        sig = encode_dss_signature(vector['r'], vector['s'])
        verifier = pytest.deprecated_call(
            public_key.verifier, sig, algorithm()
        )

        verifier.update(vector['msg'])
        if vector['result'] == "F":
            with pytest.raises(InvalidSignature):
                verifier.verify()
        else:
            verifier.verify()
Beispiel #17
0
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
Beispiel #18
0
def verify_signature_ecc(signature, key, halg, data):
    sig = signature.signature
    rbytes = buffer_to_bytes(sig.ecdsa.signatureR)
    r = int.from_bytes(rbytes, 'big')
    sbytes = buffer_to_bytes(sig.ecdsa.signatureS)
    s = int.from_bytes(sbytes, 'big')
    dersig = encode_dss_signature(r, s)
    key.verify(dersig, data, ECDSA(halg()))
Beispiel #19
0
 def __init__(self, pubkey_hex, sigb64):
     """
     Instantiate the verifier with a hex-encoded public key and a base64-encoded signature
     """
     sig_r, sig_s = decode_signature(sigb64)
     pubkey_hex_decompressed = keylib.key_formatting.decompress(pubkey_hex)
     pubk = ec.EllipticCurvePublicNumbers.from_encoded_point(ec.SECP256K1(), pubkey_hex_decompressed.decode('hex')).public_key(default_backend())
     signature = encode_dss_signature(sig_r, sig_s)
     self.verifier = pubk.verifier(signature, ec.ECDSA(hashes.SHA256()))
Beispiel #20
0
 def sign(self, private_key, message):
     hash = hashlib.sha256(message).digest()
     signature = private_key.private_key.sign(hash,
                                              mechanism=Mechanism.ECDSA)
     encoded_signature = encode_ecdsa_signature(signature)
     r, s = decode_dss_signature(encoded_signature)
     if s > self.half_order:
         s = self.order - s
     return encode_dss_signature(r, s)
Beispiel #21
0
def test_dss_signature():
    sig = encode_dss_signature(1, 1)
    assert sig == b"0\x06\x02\x01\x01\x02\x01\x01"
    assert decode_dss_signature(sig) == (1, 1)

    r_s1 = (
        1037234182290683143945502320610861668562885151617,
        559776156650501990899426031439030258256861634312,
    )
    sig2 = encode_dss_signature(*r_s1)
    assert sig2 == (
        b"0-\x02\x15\x00\xb5\xaf0xg\xfb\x8bT9\x00\x13\xccg\x02\r\xdf\x1f,\x0b"
        b'\x81\x02\x14b\r;"\xabP1D\x0c>5\xea\xb6\xf4\x81)\x8f\x9e\x9f\x08')
    assert decode_dss_signature(sig2) == r_s1

    sig3 = encode_dss_signature(0, 0)
    assert sig3 == b"0\x06\x02\x01\x00\x02\x01\x00"
    assert decode_dss_signature(sig3) == (0, 0)
Beispiel #22
0
def verify_signature_ecc(signature, key, data):
    dt = _get_digest(signature.signature.any.hashAlg)
    if dt is None:
        raise ValueError(
            f"unsupported digest algorithm: {signature.signature.ecdsa.hash}")
    r = int.from_bytes(signature.signature.ecdsa.signatureR, byteorder="big")
    s = int.from_bytes(signature.signature.ecdsa.signatureS, byteorder="big")
    sig = encode_dss_signature(r, s)
    key.verify(sig, data, ec.ECDSA(dt()))
Beispiel #23
0
def raw_to_der_signature(raw_sig, curve):
    length = (curve.key_size + 7) // 8

    if len(raw_sig) != 2 * length:
        raise ValueError('Invalid signature')

    r = bytes_to_number(raw_sig[:length])
    s = bytes_to_number(raw_sig[length:])
    return encode_dss_signature(r, s)
Beispiel #24
0
 def verify(self, msg, sig, key):
     try:
         # cryptography uses ASN.1-encoded signature data; split JWS signature (r||s) and encode before verification
         (r, s) = self._split_raw_signature(sig)
         asn1sig = encode_dss_signature(r, s)
         key.verify(asn1sig, msg, ec.ECDSA(self.hash_algorithm()))
     except InvalidSignature as err:
         raise BadSignature(err)
     else:
         return True
    def _raw_to_der(self, raw_signature):
        """Convert signature from RAW encoding to DER encoding."""
        component_length = self._sig_component_length()
        if len(raw_signature) != int(2 * component_length):
            raise ValueError("Invalid signature")

        r_bytes = raw_signature[:component_length]
        s_bytes = raw_signature[component_length:]
        r = int_from_bytes(r_bytes, "big")
        s = int_from_bytes(s_bytes, "big")
        return encode_dss_signature(r, s)
def test_dss_signature():
    sig = encode_dss_signature(1, 1)
    assert sig == b"0\x06\x02\x01\x01\x02\x01\x01"
    assert decode_dss_signature(sig) == (1, 1)

    r_s1 = (1037234182290683143945502320610861668562885151617, 559776156650501990899426031439030258256861634312)
    sig2 = encode_dss_signature(*r_s1)
    assert sig2 == (
        b"0-\x02\x15\x00\xb5\xaf0xg\xfb\x8bT9\x00\x13\xccg\x02\r\xdf\x1f,\x0b"
        b'\x81\x02\x14b\r;"\xabP1D\x0c>5\xea\xb6\xf4\x81)\x8f\x9e\x9f\x08'
    )
    assert decode_dss_signature(sig2) == r_s1

    sig3 = encode_dss_signature(0, 0)
    assert sig3 == b"0\x06\x02\x01\x00\x02\x01\x00"
    assert decode_dss_signature(sig3) == (0, 0)

    sig4 = encode_dss_signature(-1, 0)
    assert sig4 == b"0\x06\x02\x01\xFF\x02\x01\x00"
    assert decode_dss_signature(sig4) == (-1, 0)
Beispiel #27
0
def ecdsa_sig_from_agent_signed_response(response):
    msg = Message(response)
    algo = msg.get_text()
    sig = msg.get_binary()

    sig_msg = Message(sig)
    r = sig_msg.get_mpint()
    s = sig_msg.get_mpint()
    signature = encode_dss_signature(r, s)

    return signature
 def verify(public_key, data, signature):
     """
     verify a signature based on the public key and data
     """
     deserialized_public_key = serialization.load_pem_public_key(public_key.encode('utf-8'), default_backend())
     (r , s) = signature
     try:
         deserialized_public_key.verify(encode_dss_signature(r, s), json.dumps(data).encode('utf-8'), ec.ECDSA(hashes.SHA256()))
         return True
     except InvalidSignature :
         return False
Beispiel #29
0
 def verify(self, key: ec.EllipticCurvePublicKey, msg: bytes,
            sig: bytes) -> bool:
     """Verify the ``msg` and ``sig`` using ``key``."""
     rlen = jwk.JWKEC.expected_length_for_curve(key.curve)
     if len(sig) != 2 * rlen:
         # Format error - rfc7518 - 3.4 … MUST NOT be shortened to omit any leading zero octets
         return False
     asn1sig = encode_dss_signature(
         int.from_bytes(sig[0:rlen], byteorder='big'),
         int.from_bytes(sig[rlen:], byteorder='big'))
     return self._verify(key, msg, asn1sig)
Beispiel #30
0
def ecdsa_sig_from_agent_signed_response(response):
    msg = Message(response)
    algo = msg.get_text()
    sig = msg.get_binary()

    sig_msg = Message(sig)
    r = sig_msg.get_mpint()
    s = sig_msg.get_mpint()
    signature = encode_dss_signature(r, s)

    return signature
Beispiel #31
0
def raw_to_der_signature(raw_sig, curve):
    num_bits = curve.key_size
    num_bytes = (num_bits + 7) // 8

    if len(raw_sig) != 2 * num_bytes:
        raise ValueError("Invalid signature")

    r = bytes_to_number(raw_sig[:num_bytes])
    s = bytes_to_number(raw_sig[num_bytes:])

    return encode_dss_signature(r, s)
    def _raw_to_der(self, raw_signature):
        """Convert signature from RAW encoding to DER encoding."""
        component_length = self._sig_component_length()
        if len(raw_signature) != int(2 * component_length):
            raise ValueError("Invalid signature")

        r_bytes = raw_signature[:component_length]
        s_bytes = raw_signature[component_length:]
        r = int_from_bytes(r_bytes, "big")
        s = int_from_bytes(s_bytes, "big")
        return encode_dss_signature(r, s)
def ecdsa_to_asn1_der(signature):
    """ASN.1 DER encode an ECDSA signature.

    :param bytes signature: ECDSA signature encoded according to RFC 7518, i.e. the concatenated big-endian bytes of
      two integers (as produced by Key Vault)
    :return: signature, ASN.1 DER encoded (as expected by ``cryptography``)
    """
    mid = len(signature) // 2
    r = _bytes_to_int(signature[:mid])
    s = _bytes_to_int(signature[mid:])
    return utils.encode_dss_signature(r, s)
Beispiel #34
0
 def _encode_dss_signature(self, raw_signature, key_size_bits):
     want_raw_signature_len = key_size_bits // 8 * 2
     if len(raw_signature) != want_raw_signature_len:
         raise InvalidSignature(
             "Expected %d byte SignatureValue, got %d"
             % (want_raw_signature_len, len(raw_signature))
         )
     int_len = len(raw_signature) // 2
     r = bytes_to_long(raw_signature[:int_len])
     s = bytes_to_long(raw_signature[int_len:])
     return utils.encode_dss_signature(r, s)
Beispiel #35
0
 def verify(self, signature, data, hash_context):
     if not isinstance(hash_context, hashes.HashContext):
         raise TypeError("hash_context must be an instance of hashes.HashContext.")
     size = self.public_numbers.parameter_numbers.q.bit_length() // 8
     r, s = (bytes_to_long(value) for value in read_content(signature, '{0}s{0}s'.format(size)))
     # r, s = (bytes_to_long(value) for value in read_content(signature, '20s20s'))
     hash_context.update(data)
     digest = hash_context.finalize()
     try:
         self._key.verify(encode_dss_signature(r, s), digest, Prehashed(SHA256HMAC160()))
     except InvalidSignature:
         raise ValueError("invalid signature")
Beispiel #36
0
    def test_signatures(self, backend, vector):
        hash_type = _HASH_TYPES[vector['digest_algorithm']]
        curve_type = ec._CURVE_TYPES[vector['curve']]

        _skip_ecdsa_vector(backend, curve_type, hash_type)

        key = ec.EllipticCurvePublicNumbers(vector['x'], vector['y'],
                                            curve_type()).public_key(backend)

        signature = encode_dss_signature(vector['r'], vector['s'])

        key.verify(signature, vector['message'], ec.ECDSA(hash_type()))
Beispiel #37
0
def forge(data, pk, r, s, k):
    p, q, g, y = pk['p'], pk['q'], pk['g'], pk['y']
    h1 = int(hashlib.sha1(data.encode()).hexdigest(), 16)
    h2 = int(hashlib.sha256(data.encode()).hexdigest(), 16)
    kinv = _modinv(k, q)

    x = ((s * k - h1) * _modinv(r, q)) % q
    assert y == pow(g, x, p), 'Error extracting private key'

    forge_s = kinv * (h2 + r * x) % q
    signature = encode_dss_signature(r, forge_s).hex()
    return signature, data
Beispiel #38
0
 def verify(self, signature, data, hash_context):
     if not isinstance(hash_context, hashes.HashContext):
         raise TypeError("hash_context must be an instance of hashes.HashContext.")
     size = self.public_numbers.parameter_numbers.q.bit_length() // 8
     r, s = (bytes_to_long(value) for value in read_content(signature, '{0}s{0}s'.format(size)))
     # r, s = (bytes_to_long(value) for value in read_content(signature, '20s20s'))
     verifier = self._key.verifier(encode_dss_signature(r, s), hashes.SHA256())
     verifier._hash_ctx = hash_context
     verifier.update(data)
     try:
         verifier.verify()
     except InvalidSignature:
         raise ValueError("invalid signature")
Beispiel #39
0
    def verify(self, signature, data):
        """
        Verify a signature using this key.

        @type signature: L{bytes}
        @param signature: The signature to verify.

        @type data: L{bytes}
        @param data: The signed data.

        @rtype: L{bool}
        @return: C{True} if the signature is valid.
        """
        if len(signature) == 40:
            # DSA key with no padding
            signatureType, signature = b'ssh-dss', common.NS(signature)
        else:
            signatureType, signature = common.getNS(signature)
        if signatureType != self.sshType():
            return False
        if self.type() == 'RSA':
            k = self._keyObject
            if not self.isPublic():
                k = k.public_key()
            verifier = k.verifier(
                common.getNS(signature)[0],
                padding.PKCS1v15(),
                hashes.SHA1(),
            )
        elif self.type() == 'DSA':
            concatenatedSignature = common.getNS(signature)[0]
            r = int_from_bytes(concatenatedSignature[:20], 'big')
            s = int_from_bytes(concatenatedSignature[20:], 'big')
            signature = encode_dss_signature(r, s)
            k = self._keyObject
            if not self.isPublic():
                k = k.public_key()
            verifier = k.verifier(
                signature, hashes.SHA1())
        else:
            raise BadKeyError("unknown key type %s" % (self.type(),))

        verifier.update(data)
        try:
            verifier.verify()
        except InvalidSignature:
            return False
        else:
            return True
Beispiel #40
0
    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)

        try:
            self.verifying_key.verify(
                signature, data, ec.ECDSA(self.ecdsa_curve.hash_object())
            )
        except InvalidSignature:
            return False
        else:
            return True
Beispiel #41
0
def der_encode(signature_bin_asn):
    """
    This encodes a raw signature to DER.
    It uses the encode_dss_signature() function from cryptography.

    :param signature_bin_asn: RAW signature
    :type signature_bin_asn: bytes
    :return: DER encoded signature
    :rtype: bytes
    """
    if len(signature_bin_asn) != 64:
        raise Exception("The signature needs to be 64 bytes.")
    vr = int(binascii.hexlify(signature_bin_asn[:32]), 16)
    vs = int(binascii.hexlify(signature_bin_asn[32:]), 16)
    signature_bin = encode_dss_signature(vr, vs)
    return signature_bin
Beispiel #42
0
    def test_signatures(self, backend, vector):
        hash_type = _HASH_TYPES[vector['digest_algorithm']]
        curve_type = ec._CURVE_TYPES[vector['curve']]

        _skip_ecdsa_vector(backend, curve_type, hash_type)

        key = ec.EllipticCurvePublicNumbers(
            vector['x'],
            vector['y'],
            curve_type()
        ).public_key(backend)

        signature = encode_dss_signature(vector['r'], vector['s'])

        key.verify(
            signature,
            vector['message'],
            ec.ECDSA(hash_type())
        )
Beispiel #43
0
def extract_signature(auth):
    """Extracts the payload and signature from a JWT, converting from RFC7518
    to RFC 3279

    :param auth: A JWT Authorization Token.
    :type auth: str

    :return tuple containing the signature material and signature

    """
    payload, asig = auth.encode('utf8').rsplit(b'.', 1)
    sig = b64urldecode(asig)
    if len(sig) != 64:
        raise InvalidSignature()

    encoded = utils.encode_dss_signature(
        s=int(binascii.hexlify(sig[32:]), 16),
        r=int(binascii.hexlify(sig[:32]), 16)
    )
    return payload, encoded
Beispiel #44
0
def verify_one_vector(vector):
    digest_algorithm = vector['digest_algorithm']
    message = vector['message']
    x = vector['x']
    y = vector['y']
    signature = encode_dss_signature(vector['r'], vector['s'])

    numbers = ec.EllipticCurvePublicNumbers(
        x, y,
        ec.SECP256K1()
    )

    key = numbers.public_key(default_backend())

    verifier = key.verifier(
        signature,
        ec.ECDSA(CRYPTOGRAPHY_HASH_TYPES[digest_algorithm]())
    )
    verifier.update(message)
    return verifier.verify()
    def verify(self, payload, signature):
        """
        Verify that the token signed the data
        :type payload: String
        :param payload: message that was signed and needs verified
        :type signature: Base64 URL Safe
        :param signature: Signature that can verify the sender\'s identity and payload
        :return:

        """
        raw_sig = utils.base64url_decode(signature)
        sig_r_bin = raw_sig[:len(raw_sig)//2]
        sig_s_bin = raw_sig[len(raw_sig)//2:]

        sig_r = unpack_bytes(sig_r_bin)
        sig_s = unpack_bytes(sig_s_bin)

        sig = encode_dss_signature(sig_r, sig_s)
        signer = self.public_key.verifier(sig, ec.ECDSA(hashes.SHA256()))
        signer.update(utils.to_bytes(payload))
        return signer.verify()
Beispiel #46
0
    def verify_token(self, validation_token, verification_token):
        """Internally used to verify the verification token is correct.

        :param validation_token: Provided validation token string
        :type validation_token: str
        :param verification_token: Generated verification token
        :type verification_token: str
        :returns: Boolean indicating if verifictation token is valid.
        :rtype: boolean

        """
        hsig = b64urldecode(verification_token.encode('utf8'))
        r = int(binascii.hexlify(hsig[:32]), 16)
        s = int(binascii.hexlify(hsig[32:]), 16)
        try:
            self.public_key.verify(
                ecutils.encode_dss_signature(r, s),
                validation_token,
                signature_algorithm=ec.ECDSA(hashes.SHA256())
            )
            return True
        except InvalidSignature:
            return False