Exemplo n.º 1
0
    def setup(self):
        mkey = [
            {"type": "RSA", "use": ["sig"]},
            {"type": "RSA", "use": ["sig"]},
            {"type": "RSA", "use": ["sig"]},
        ]

        skey = [{"type": "RSA", "use": ["sig"]}]

        # Alice has multiple keys
        self.alice_keyjar = build_keyjar(mkey)
        # Bob has one single keys
        self.bob_keyjar = build_keyjar(skey)
        self.alice_keyjar["Alice"] = self.alice_keyjar[""]
        self.bob_keyjar["Bob"] = self.bob_keyjar[""]

        # To Alice's keyjar add Bob's public keys
        self.alice_keyjar.import_jwks(self.bob_keyjar.export_jwks(issuer="Bob"), "Bob")

        # To Bob's keyjar add Alice's public keys
        self.bob_keyjar.import_jwks(self.alice_keyjar.export_jwks(issuer="Alice"), "Alice")

        _jws = JWS('{"aud": "Bob", "iss": "Alice"}', alg="RS256")
        sig_key = self.alice_keyjar.get_signing_key("rsa", owner="Alice")[0]
        self.sjwt_a = _jws.sign_compact([sig_key])

        _jws = JWS('{"aud": "Alice", "iss": "Bob"}', alg="RS256")
        sig_key = self.bob_keyjar.get_signing_key("rsa", owner="Bob")[0]
        self.sjwt_b = _jws.sign_compact([sig_key])
Exemplo n.º 2
0
def test_unknown_alg():
    jws = JWS(msg="Please take a moment to register today",
              jwk=JWKS_b["keys"][0],
              alg="RS768")

    with pytest.raises(UnknownAlgorithm):
        jws.sign_compact()
Exemplo n.º 3
0
def test_mismatch_alg_and_key():
    pkey = import_private_rsa_key_from_file(full_path("./size2048.key"))
    payload = "Please take a moment to register today"
    keys = [RSAKey(priv_key=pkey)]
    _jws = JWS(payload, alg="ES256")
    with pytest.raises(NoSuitableSigningKeys):
        _jws.sign_compact(keys)
Exemplo n.º 4
0
def test_sign_2():
    keyset = {
        "keys": [{
            "alg":
            "RS512",
            "kty":
            "RSA",
            "d":
            "ckLyXxkbjC4szg8q8G0ERBZV"
            "-9CszeOxpRtx1KM9BLl0Do3li_Km2vvFvfXJ7MxQpiZ18pBoCcyYQEU262ym8wI22JWMPrZe24HCNxLxqzr_JEuBhpKFxQF6EFTSvJEJD1FkoTuCTvN0zD7YHGaJQG6JzVEuFUY3ewxjH0FYNa_ppTnPP3LC-T9u_GX9Yqyuw1KOYoHSzhWSWQOeAgs4dH9-iAxN1wdZ6eH1jFWAs43svk_rhwdgyJMlihFtV9MAInBlfi_Zu8wRVhVl5urkJrLf0tGFnMbnzb6dYSlUXxEYClpY12W7kXW9aePDqkCwI4oZyxmOmgq4hunKGR1dAQ",
            "e":
            "AQAB",
            "use":
            "sig",
            "kid":
            "af22448d-4c7b-464d-b63a-f5bd90f6d7d1",
            "n":
            "o9g8DpUwBW6B1qmcm-TfEh4rNX7n1t38jdo4Gkl_cI3q"
            "--7n0Blg0kN88LHZvyZjUB2NhBdFYNxMP8ucy0dOXvWGWzaPmGnq3DM__lN8P4WjD1cCTAVEYKawNBAmGKqrFj1SgpPNsSqiqK-ALM1w6mZ-QGimjOgwCyJy3l9lzZh5D8tKnS2t1pZgE0X5P7lZQWHYpHPqp4jKhETzrCpPGfv0Rl6nmmjp7NlRYBkWKf_HEKE333J6M039m2FbKgxrBg3zmYYpmHuMzVgxxb8LSiv5aqyeyJjxM-YDUAgNQBfKNhONqXyu9DqtSprNkw6sqmuxK0QUVrNYl3b03PgS5Q",
        }]
    }

    keys = KeyBundle(keyset)
    jws = JWS("payload", alg="RS512")
    jws.sign_compact(keys=keys)
Exemplo n.º 5
0
def test_no_alg_and_alg_none_same():
    payload = "Please take a moment to register today"
    _jws = JWS(payload, alg="none")

    # Create a JWS (signed JWT)
    _jwt0 = _jws.sign_compact([])

    # The class instance that sets up the signing operation
    _jws = JWS(payload, alg="none")

    # Create a JWS (signed JWT)
    _jwt1 = _jws.sign_compact([])

    assert _jwt0 == _jwt1
Exemplo n.º 6
0
def test_jws_mac_authenticator_and_verifier():
    algs = ['HS256', 'HS384', 'HS512']
    for alg in algs:
        calgs = algs[:]
        calgs.remove(alg)

        json_hmac_key = json.loads(test_vector.json_hmac_key)
        json_hmac_key['alg'] = alg
        json_hmac_key = json.dumps(json_hmac_key)
        json_header_hmac = json.loads(test_vector.test_header_hmac)
        json_header_hmac['alg'] = alg
        json_header_hmac = json.dumps(json_header_hmac)

        # Authenticator
        mac_key = key_from_jwk_dict(json.loads(json_hmac_key))
        authenticator = JWS(test_vector.test_payload,
                            **json.loads(json_header_hmac))
        signed_token = authenticator.sign_compact([mac_key])

        # Verify
        verifier = JWS(alg=alg)
        assert verifier.verify_compact(signed_token, [mac_key])
        for modified_token in modify_token(signed_token, calgs):
            with pytest.raises(JWKESTException):
                assert verifier.verify_compact(modified_token, [mac_key])
Exemplo n.º 7
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
def test_back_channel_logout_request():
    val = {
        "iss": ISS,
        "aud": [CLIENT_ID],
        "iat": NOW,
        "jti": "bWJq",
        "sid": "08a5019c-17e1-4977-8f42-65a12843ea02",
        "events": {
            BACK_CHANNEL_LOGOUT_EVENT: {}
        }
    }
    lt = LogoutToken(**val)
    signer = JWS(lt.to_json(), alg='ES256')
    _jws = signer.sign_compact(keys=ISS_KEY.get_signing_key(issuer_id=ISS))

    bclr = BackChannelLogoutRequest(logout_token=_jws)

    # This is how it is posted
    _req = bclr.to_urlencoded()

    _request = BackChannelLogoutRequest().from_urlencoded(_req)

    assert 'logout_token' in _request

    _verified = _request.verify(keyjar=CLI_KEY,
                                iss=ISS,
                                aud=CLIENT_ID,
                                skew=30)

    assert _verified
    assert set(_request.keys()) == {'logout_token', '__verified_logout_token'}
Exemplo n.º 9
0
def test_signer_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)

    exp_protected = protected.copy()
    exp_protected["alg"] = "ES256"
    enc_header, enc_payload, sig = _jwt.split(".")
    assert json.loads(b64d(
        enc_header.encode("utf-8")).decode("utf-8")) == exp_protected
    assert b64d(enc_payload.encode("utf-8")).decode("utf-8") == payload

    _pub_key = ECKey().load_key(eck.public_key())
    _rj = JWS(alg="ES256")
    info = _rj.verify_compact(_jwt, [_pub_key])
    assert info == payload
    # Protected by default
    protected["alg"] = "ES256"
    assert _rj.protected_headers() == protected
Exemplo n.º 10
0
def test_jws_rsa_signer_and_verifier():
    algs = ['RS256', 'RS384', 'RS512', 'PS256', 'PS384', 'PS512']
    for alg in algs:
        calgs = algs[:]
        calgs.remove(alg)
        json_priv_key = json.loads(test_vector.json_rsa_priv_key)
        json_priv_key['alg'] = alg
        json_priv_key = json.dumps(json_priv_key)
        json_pub_key = json.loads(test_vector.json_rsa_pub_key)
        json_pub_key['alg'] = alg
        json_pub_key = json.dumps(json_pub_key)

        json_header_rsa = json.loads(test_vector.test_header_rsa)
        json_header_rsa['alg'] = alg

        # Sign
        priv_key = key_from_jwk_dict(json.loads(json_priv_key))
        jws = JWS(msg=test_vector.test_payload, **json_header_rsa)
        signed_token = jws.sign_compact([priv_key])

        # Verify
        pub_key = key_from_jwk_dict(json.loads(json_pub_key))
        verifier = JWS(alg=[alg])
        assert verifier.verify_compact(signed_token, [pub_key])

        for modified_token in modify_token(signed_token, calgs):
            with pytest.raises(JWKESTException):
                verifier.verify_compact(modified_token, [pub_key])
Exemplo n.º 11
0
def test_dj_usage():
    pkey = import_private_rsa_key_from_file(full_path("./size2048.key"))
    payload = "Please take a moment to register today"
    keys = [RSAKey(priv_key=pkey)]
    _jws = JWS(payload, alg="RS256")
    sjwt = _jws.sign_compact(keys)
    _jwt = factory(sjwt)
    assert _jwt.jwt.headers["alg"] == "RS256"
Exemplo n.º 12
0
def store_signed_jwks(keyjar, sign_keyjar, path, alg, iss=''):
    _jwks = keyjar.export_jwks()
    _jws = JWS(_jwks, alg=alg)
    _jwt = _jws.sign_compact(
        sign_keyjar.get_signing_key(owner=iss, key_type=alg2keytype(alg)))
    fp = open(path, 'w')
    fp.write(_jwt)
    fp.close()
Exemplo n.º 13
0
def test_extra_headers_1():
    pkey = import_private_rsa_key_from_file(full_path("./size2048.key"))
    payload = "Please take a moment to register today"
    keys = [RSAKey(priv_key=pkey)]
    _jws = JWS(payload, alg="RS256")
    sjwt = _jws.sign_compact(keys, foo="bar")
    _jwt = factory(sjwt)
    assert set(_jwt.jwt.headers.keys()) == {"alg", "foo"}
    def setup(self):
        mkey = [
            {
                "type": "RSA",
                "use": ["sig"]
            },
            {
                "type": "RSA",
                "use": ["sig"]
            },
            {
                "type": "RSA",
                "use": ["sig"]
            },
        ]

        skey = [
            {
                "type": "RSA",
                "use": ["sig"]
            },
        ]

        # Alice has multiple keys
        self.alice_keyjar = build_keyjar(mkey)
        # Bob has one single keys
        self.bob_keyjar = build_keyjar(skey)
        self.alice_keyjar['Alice'] = self.alice_keyjar['']
        self.bob_keyjar['Bob'] = self.bob_keyjar['']

        # To Alice's keyjar add Bob's public keys
        self.alice_keyjar.import_jwks(
            self.bob_keyjar.export_jwks(issuer='Bob'), 'Bob')

        # To Bob's keyjar add Alice's public keys
        self.bob_keyjar.import_jwks(
            self.alice_keyjar.export_jwks(issuer='Alice'), 'Alice')

        _jws = JWS('{"aud": "Bob", "iss": "Alice"}', alg='RS256')
        sig_key = self.alice_keyjar.get_signing_key('rsa', owner='Alice')[0]
        self.sjwt_a = _jws.sign_compact([sig_key])

        _jws = JWS('{"aud": "Alice", "iss": "Bob"}', alg='RS256')
        sig_key = self.bob_keyjar.get_signing_key('rsa', owner='Bob')[0]
        self.sjwt_b = _jws.sign_compact([sig_key])
Exemplo n.º 15
0
def test_extra_headers_3():
    pkey = import_private_rsa_key_from_file(full_path("./size2048.key"))
    payload = "Please take a moment to register today"
    keys = [RSAKey(priv_key=pkey)]
    _jws = JWS(payload, alg='RS256')
    _jws.set_header_claim('foo', 'bar')
    sjwt = _jws.sign_compact(keys, abc=123)
    _jwt = factory(sjwt)
    assert set(_jwt.jwt.headers.keys()) == {'alg', 'foo', 'abc'}
Exemplo n.º 16
0
def test_hmac_from_keyrep():
    payload = "Please take a moment to register today"
    symkeys = [k for k in SIGJWKS if k.kty == "oct"]
    _jws = JWS(payload, alg="HS512")
    _jwt = _jws.sign_compact(symkeys)

    _rj = JWS(alg="HS512")
    info = _rj.verify_compact(_jwt, symkeys)
    assert info == payload
Exemplo n.º 17
0
def test_jws_1():
    msg = {"iss": "joe", "exp": 1300819380, "http://example.com/is_root": True}
    key = SYMKey(key=intarr2bin(HMAC_KEY))
    _jws = JWS(msg, cty="JWT", alg="HS256", jwk=key.serialize())
    res = _jws.sign_compact()

    _jws2 = JWS(alg="HS256")
    _jws2.verify_compact(res, keys=[key])
    assert _jws2.msg == msg
Exemplo n.º 18
0
def test_hmac_256():
    payload = "Please take a moment to register today"
    keys = [SYMKey(key=intarr2bin(HMAC_KEY))]
    _jws = JWS(payload, alg="HS256")
    _jwt = _jws.sign_compact(keys)

    info = JWS(alg="HS256").verify_compact(_jwt, keys)

    assert info == payload
Exemplo n.º 19
0
def test_factory_verify_alg():
    pkey = import_private_rsa_key_from_file(full_path("./size2048.key"))
    payload = "Please take a moment to register today"
    keys = [RSAKey(priv_key=pkey)]
    _signer = JWS(payload, alg="RS256")
    _signer.set_header_claim("foo", "bar")
    _jws = _signer.sign_compact(keys, abc=123)
    _verifier = factory(_jws)
    assert _verifier.jwt.verify_headers(alg="RS512") is False
Exemplo n.º 20
0
def test_hmac_512():
    payload = "Please take a moment to register today"
    keys = [SYMKey(key=b"My hollow echo chamber", alg="HS512")]
    _jws = JWS(payload, alg="HS512")
    _jwt = _jws.sign_compact(keys)

    _rj = JWS(alg="HS512")
    info = _rj.verify_compact(_jwt, keys)
    assert info == payload
Exemplo n.º 21
0
def test_jws_mm():
    msg = {"iss": "joe", "exp": 1300819380, "http://example.com/is_root": True}
    key = SYMKey(key=intarr2bin(HMAC_KEY))
    _jws = JWS(msg, cty="JWT", alg="HS256", jwk=key.serialize())
    res = _jws.sign_compact()

    _jws2 = JWS(alg="HS512")

    with pytest.raises(SignerAlgError):
        _jws2.verify_compact(res, keys=[key])
Exemplo n.º 22
0
def test_signer_es(ec_func, alg):
    payload = "Please take a moment to register today"
    eck = ec.generate_private_key(ec_func(), default_backend())
    keys = [ECKey().load_key(eck)]
    _jws = JWS(payload, alg=alg)
    _jwt = _jws.sign_compact(keys)

    _pubkey = ECKey().load_key(eck.public_key())
    _rj = JWS(alg=alg)
    info = _rj.verify_compact(_jwt, [_pubkey])
    assert info == payload
Exemplo n.º 23
0
def test_signer_ps384():
    payload = "Please take a moment to register today"
    _pkey = import_private_rsa_key_from_file(PRIV_KEY)
    keys = [RSAKey(priv_key=_pkey)]
    # keys[0]._keytype = "private"
    _jws = JWS(payload, alg="PS384")
    _jwt = _jws.sign_compact(keys)

    vkeys = [RSAKey(pub_key=_pkey.public_key())]
    _rj = JWS(alg="PS384")
    info = _rj.verify_compact(_jwt, vkeys)
    assert info == payload
Exemplo n.º 24
0
    def to_jwt(self, key=None, algorithm="", lev=0, lifetime=0):
        """
        Create a signed JWT representation of the class instance

        :param key: The signing key
        :param algorithm: The signature algorithm to use
        :param lev:
        :param lifetime: The lifetime of the JWS
        :return: A signed JWT
        """

        _jws = JWS(self.to_json(lev), alg=algorithm)
        return _jws.sign_compact(key)
Exemplo n.º 25
0
def test_signer_es256_verbose():
    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")
    _jwt = _jws.sign_compact(keys)

    _pubkey = ECKey().load_key(eck.public_key())
    _rj = JWS(alg="ES256")
    info = _rj.verify_compact_verbose(_jwt, [_pubkey])
    assert info["msg"] == payload
    assert info["key"] == _pubkey
Exemplo n.º 26
0
    def test_aud(self):
        self.alice_keyjar.import_jwks(JWK1, issuer="D")
        self.bob_keyjar.import_jwks(JWK1, issuer="D")

        _jws = JWS('{"iss": "D", "aud": "A"}', alg="HS256")
        sig_key = self.alice_keyjar.get_signing_key("oct", owner="D")[0]
        _sjwt = _jws.sign_compact([sig_key])

        no_kid_issuer = {"D": []}

        _jwt = factory(_sjwt)

        keys = self.bob_keyjar.get_jwt_verify_keys(_jwt.jwt, no_kid_issuer=no_kid_issuer)
        assert len(keys) == 1
Exemplo n.º 27
0
def test_jws_ecdsa_signer_verifier_es256():
    # Sign
    priv_key = key_from_jwk_dict(json.loads(test_vector.es256_ecdsa_priv_key))
    signer = JWS(msg=test_vector.test_payload,
                 **json.loads(test_vector.test_header_ecdsa))
    signed_token = signer.sign_compact([priv_key])

    # Verify
    pub_key = key_from_jwk_dict(json.loads(test_vector.es256_ecdsa_pub_key))
    verifier = JWS(alg='ES256')
    assert verifier.verify_compact(signed_token, [pub_key])
    for modified_token in modify_token(signed_token, ['ES384', 'ES512']):
        with pytest.raises(JWKESTException):
            verifier.verify_compact(modified_token, [pub_key])
Exemplo n.º 28
0
def test_signer_ps512():
    payload = "Please take a moment to register today"
    # Key has to be big enough  > 512+512+2
    _pkey = import_private_rsa_key_from_file(full_path("./size2048.key"))
    keys = [RSAKey(priv_key=_pkey)]
    # keys[0]._keytype = "private"
    _jws = JWS(payload, alg="PS512")
    _jwt = _jws.sign_compact(keys)

    vkeys = [RSAKey(pub_key=_pkey.public_key())]
    _rj = factory(_jwt, alg="PS512")
    info = _rj.verify_compact(_jwt, vkeys)
    assert info == payload
    assert _rj.verify_alg("PS512")
Exemplo n.º 29
0
def test_jws_verifier_with_kid():
    # Sign
    priv_key = key_from_jwk_dict(
        json.loads(test_vector.test_json_ecdsa_priv_key_kid1))

    signer = JWS(test_vector.test_payload,
                 **json.loads(test_vector.test_header_ecdsa_kid1))
    signed_token_kid1 = signer.sign_compact([priv_key])

    priv_key = key_from_jwk_dict(
        json.loads(test_vector.test_json_ecdsa_priv_key_kid2))
    signer = JWS(test_vector.test_payload,
                 **json.loads(test_vector.test_header_ecdsa_kid2))
    signed_token_kid2 = signer.sign_compact([priv_key])

    # Verify
    pub_key = key_from_jwk_dict(
        json.loads(test_vector.test_json_ecdsa_pub_key_kid1))

    verifier = JWS(alg='ES256')
    assert verifier.verify_compact(signed_token_kid1, [pub_key])
    # The signature is valid but the kids don't match.
    with pytest.raises(NoSuitableSigningKeys):
        verifier.verify_compact(signed_token_kid2, [pub_key])
Exemplo n.º 30
0
def test_1():
    claimset = {
        "iss": "joe",
        "exp": 1300819380,
        "http://example.com/is_root": True
    }

    _jws = JWS(claimset, cty="JWT", alg="none")
    _jwt = _jws.sign_compact()

    _jr = JWS()
    _msg = _jr.verify_compact(_jwt, allow_none=True)
    print(_jr)
    assert _jr.jwt.headers["alg"] == "none"
    assert _msg == claimset