Пример #1
0
def test_verify_protected_headers():
    payload = "Please take a moment to register today"
    eck = ec.generate_private_key(ec.SECP256R1(), default_backend())
    _key = ECKey().load_key(eck)
    keys = [_key]
    _jws = JWS(payload, alg="ES256")
    protected = dict(header1=u"header1 is protected",
                     header2="header2 is protected too",
                     a=1)
    _jwt = _jws.sign_compact(keys, protected=protected)
    protectedHeader, enc_payload, sig = _jwt.split(".")
    data = dict(
        payload=enc_payload,
        signatures=[
            dict(
                header=dict(alg=u"ES256", jwk=_key.serialize()),
                protected=protectedHeader,
                signature=sig,
            )
        ],
    )

    # _pub_key = ECKey().load_key(eck.public_key())
    _jws = JWS()
    assert _jws.verify_json(json.dumps(data)) == payload
Пример #2
0
def test_verify_json_flattened_syntax():
    key = ECKey().load_key(P256())
    protected_headers = {"foo": "bar"}
    unprotected_headers = {"abc": "xyz"}
    payload = "hello world"
    _jwt = JWS(msg=payload, alg="ES256").sign_json(headers=[
        (protected_headers, unprotected_headers)
    ],
                                                   keys=[key],
                                                   flatten=True)

    vkeys = [ECKey().load_key(key.public_key())]
    _jws = JWS()
    assert _jws.verify_json(_jwt, keys=vkeys)
    assert _jws.protected_headers() == {"alg": "ES256", "foo": "bar"}
Пример #3
0
def test_verify_json():
    eck = ec.generate_private_key(ec.SECP256R1(), default_backend())
    key = ECKey().load_key(eck)
    payload = "hello world"
    unprotected_headers = {"abc": "xyz"}
    protected_headers = {"foo": "bar"}
    _jwt = JWS(msg=payload, alg="ES256").sign_json(headers=[
        (protected_headers, unprotected_headers)
    ],
                                                   keys=[key])

    vkeys = [ECKey().load_key(eck.public_key())]
    _jws = JWS()
    assert _jws.verify_json(_jwt, keys=vkeys)
    _protected = _jws.protected_headers()
    assert set(_protected.keys()) == {"foo", "alg"}
    assert _protected["foo"] == protected_headers["foo"]
    # alg is always protected by default
    assert _protected["alg"] == "ES256"
Пример #4
0
def test_missing_payload():
    jws = JWS()
    with pytest.raises(FormatError):
        jws.verify_json('{"foo":"bar"}')
Пример #5
0
def main():
    """Main function"""

    parser = argparse.ArgumentParser(description="JWS verifier")

    parser.add_argument(
        "--trusted",
        dest="trusted",
        metavar="filename",
        help="Trusted keys (JWKS)",
        required=False,
    )
    parser.add_argument(
        "--input",
        dest="jws_input",
        metavar="filename",
        help="JWS file input",
        required=True,
    )
    parser.add_argument(
        "--output",
        dest="output",
        metavar="filename",
        help="Output",
        required=False,
    )
    parser.add_argument(
        "--headers",
        dest="headers_output",
        metavar="filename",
        help="Headers output",
        required=False,
    )
    parser.add_argument("--debug",
                        dest="debug",
                        action="store_true",
                        help="Enable debugging")

    args = parser.parse_args()

    if args.debug:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.INFO)

    trusted_keys = []
    if args.trusted:
        with open(args.trusted) as input_file:
            trusted_payload = json.load(input_file)
            if isinstance(trusted_payload, dict):
                trusted_keys.append(key_from_jwk_dict(trusted_payload))
            elif isinstance(trusted_payload, dict):
                for jwk_dict in trusted_payload["keys"]:
                    trusted_keys.append(
                        key_from_jwk_dict(jwk_dict, private=False))
            else:
                raise ValueError("Unknown trusted list format")

    with open(args.jws_input, "rt") as input_file:
        jws_file = input_file.read()

    protected_headers = []
    jws_dict = json.loads(jws_file)

    if args.trusted:
        jws = JWS()
        message = jws.verify_json(jws_file, keys=trusted_keys)
    else:
        message = json.loads(b64d(jws_dict["payload"].encode()).decode())

    for signatures in jws_dict["signatures"]:
        if "protected" in signatures:
            protected_headers.append(extract_headers(signatures["protected"]))

    if args.headers_output:
        with open(args.headers_output, "wt") as output_file:
            print(json.dumps(protected_headers, indent=4), file=output_file)
    else:
        if args.trusted:
            print("# JWS PROTECTED HEADERS (VERIFIED)")
        else:
            print("# JWS PROTECTED HEADERS (NOT VERIFIED)")
        print(json.dumps(protected_headers, indent=4, sort_keys=True))

    if args.output:
        with open(args.output, "wt") as output_file:
            print(json.dumps(message, indent=4), file=output_file)
    else:
        if args.trusted:
            print("# JWS CONTENTS (VERIFIED)")
        else:
            print("# JWS CONTENTS (NOT VERIFIED)")
        print(json.dumps(message, indent=4, sort_keys=True))