def test_jws_1():
    msg = {"iss": "joe", "exp": 1300819380, "http://example.com/is_root": True}
    key = SYMKey(key=cryptojwt.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
def test_hmac_from_keyrep():
    payload = "Please take a moment to register today"
    symkeys = [k for k in SIGKEYS if k.kty == "oct"]
    _jws = JWS(payload, alg="HS512")
    _jwt = _jws.sign_compact(symkeys)

    _rj = JWS()
    info = _rj.verify_compact(_jwt, symkeys)
    assert info == payload
def test_hmac_512():
    payload = "Please take a moment to register today"
    keys = [SYMKey(key=b'My hollow echo', alg="HS512")]
    _jws = JWS(payload, alg="HS512")
    _jwt = _jws.sign_compact(keys)

    _rj = JWS()
    info = _rj.verify_compact(_jwt, keys)
    assert info == payload
def test_hmac_256():
    payload = 'Please take a moment to register today'
    keys = [SYMKey(key=cryptojwt.intarr2bin(HMAC_KEY))]
    _jws = JWS(payload, alg="HS256")
    _jwt = _jws.sign_compact(keys)

    info = JWS().verify_compact(_jwt, keys)

    assert info == payload
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.key.public_key())]
    assert JWS().verify_json(_jwt, keys=vkeys)
def test_signer_es256():
    payload = "Please take a moment to register today"
    eck = ec.generate_private_key(ec.SECP256R1(), default_backend())
    keys = [ECKey().load_key(eck)]
    _jws = JWS(payload, alg="ES256")
    _jwt = _jws.sign_compact(keys)

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

    vkeys = [RSAKey(key=_pkey.public_key())]
    _rj = JWS()
    info = _rj.verify_compact(_jwt, vkeys)
    assert info == payload
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())]
    assert JWS().verify_json(_jwt, keys=vkeys)
def test_signer_es512():
    payload = "Please take a moment to register today"
    eck = ec.generate_private_key(ec.SECP521R1(), default_backend())
    _key = ECKey().load_key(eck)
    keys = [_key]
    # keys[0]._keytype = "private"
    _jws = JWS(payload, alg="ES512")
    _jwt = _jws.sign_compact(keys)

    _pubkey = ECKey().load_key(eck.public_key())
    _rj = JWS()
    info = _rj.verify_compact(_jwt, [_pubkey])
    assert info == payload
def test_1():
    claimset = {"iss": "joe",
                "exp": 1300819380,
                "http://example.com/is_root": True}

    _jws = JWS(claimset, cty="JWT")
    _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
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)

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

    assert _jwt0 == _jwt1
def test_signer_ps256_fail():
    payload = "Please take a moment to register today"
    _pkey = import_private_rsa_key_from_file(PRIV_KEY)
    keys = [RSAKey(key=_pkey)]
    # keys[0]._keytype = "private"
    _jws = JWS(payload, alg="PS256")
    _jwt = _jws.sign_compact(keys)[:-5] + 'abcde'

    vkeys = [RSAKey(key=_pkey.public_key())]
    _rj = JWS()
    try:
        _rj.verify_compact(_jwt, vkeys)
    except cryptojwt.exception.BadSignature:
        pass
    else:
        assert False
def test_a_1_3b():
    _jwt = ("eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJl"
            "eHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0c"
            "nVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk")
    keys = [SYMKey(key=cryptojwt.intarr2bin(HMAC_KEY))]
    _jws2 = JWS()
    _jws2.verify_compact(_jwt, keys)
Ejemplo n.º 14
0
    def test_client_secret_jwt(self, client):
        _ci = client.client_info
        _ci.token_endpoint = "https://example.com/token"
        _ci.provider_info = {
            'issuer': 'https://example.com/',
            'token_endpoint': "https://example.com/token"
        }

        csj = ClientSecretJWT()
        request = AccessTokenRequest()

        csj.construct(request,
                      cli_info=client.client_info,
                      algorithm="HS256",
                      authn_endpoint='userinfo')
        assert request["client_assertion_type"] == JWT_BEARER
        assert "client_assertion" in request
        cas = request["client_assertion"]

        _skey = [SYMKey(k=b64e(as_bytes(_ci.client_secret)), use='sig')]
        jso = JWT(rec_keys={client.client_id: _skey}).unpack(cas)
        assert _eq(jso.keys(), ["aud", "iss", "sub", "jti", "exp", "iat"])

        _rj = JWS()
        info = _rj.verify_compact(
            cas, [SYMKey(k=b64e(as_bytes(_ci.client_secret)))])

        assert _eq(info.keys(), ["aud", "iss", "sub", "jti", "exp", "iat"])
        assert info['aud'] == [_ci.provider_info['issuer']]
Ejemplo n.º 15
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()
Ejemplo n.º 16
0
def get_signing_keys(claims, keyjar, httpcli):
    if 'signed_jwks_uri' not in claims:
        return None

    res = httpcli.get(claims['signed_jwks_uri'])

    if res.status == 200:
        _jws = JWS()
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(key=pkey)]
    _jws = JWS(payload, alg='RS256')
    sjwt = _jws.sign_compact(keys)
    _jwt = factory(sjwt)
    assert _jwt.jwt.headers['alg'] == 'RS256'
def test_pick_alg_dont_get_alg_from_single_key_if_already_specified():
    expected_alg = "RS512"
    _pkey = import_private_rsa_key_from_file(PRIV_KEY)
    #keys = [RSAKey(key=_pkey, alg="RS256")]

    vkeys = [RSAKey(key=_pkey.public_key())]
    alg = JWS(alg=expected_alg)._pick_alg(vkeys)
    assert alg == expected_alg
def test_sign_json_dont_flatten_if_multiple_signatures():
    key = ECKey().load_key(P256())
    unprotected_headers = {"foo": "bar"}
    _jwt = JWS(msg="hello world", alg="ES256").sign_json(
        headers=[(None, unprotected_headers),
                 (None, {"abc": "xyz"})],
        keys=[key], flatten=True)
    assert "signatures" in json.loads(_jwt)
Ejemplo n.º 20
0
    def pack(self,
             payload=None,
             kid='',
             owner='',
             recv='',
             aud=None,
             **kwargs):
        """

        :param payload: Information to be carried as payload in the JWT
        :param kid: Key ID
        :param owner: The owner of the the keys that are to be used for signing
        :param recv: The intended immediate receiver
        :param aud: Intended audience for this JWS/JWE, not expected to
            contain the recipient.
        :param kwargs: Extra keyword arguments
        :return: A signed or signed and encrypted JsonWebtoken
        """
        _args = self.pack_init(recv, aud)

        try:
            _encrypt = kwargs['encrypt']
        except KeyError:
            _encrypt = self.encrypt
        else:
            del kwargs['encrypt']

        if self.with_jti:
            try:
                _jti = kwargs['jti']
            except KeyError:
                _jti = uuid.uuid4().hex

            _args['jti'] = _jti

        if payload is not None:
            _args.update(payload)

        if self.sign:
            if self.sign_alg != 'none':
                _key = self.pack_key(owner, kid)
                _args['kid'] = _key.kid
            else:
                _key = None

            _jws = JWS(json.dumps(_args), alg=self.sign_alg)
            _sjwt = _jws.sign_compact([_key])
        else:
            _sjwt = json.dumps(_args)

        if _encrypt:
            if not self.sign:
                return self._encrypt(_sjwt, recv, cty='json')
            else:
                return self._encrypt(_sjwt, recv)
        else:
            return _sjwt
def test_rs256_rm_signature():
    payload = "Please take a moment to register today"
    _pkey = import_private_rsa_key_from_file(PRIV_KEY)
    keys = [RSAKey(key=_pkey)]
    # keys[0]._keytype = "private"
    _jws = JWS(payload, alg="RS256")
    _jwt = _jws.sign_compact(keys)

    p = _jwt.split('.')
    _jwt = '.'.join(p[:-1])

    vkeys = [RSAKey(key=_pkey.public_key())]
    _rj = JWS()
    try:
        _ = _rj.verify_compact(_jwt, vkeys)
    except WrongNumberOfParts:
        pass
    else:
        assert False
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()
    info = _rj.verify_compact(_jwt, [_pub_key])
    assert info == payload
def test_sign_json_dont_include_empty_protected_headers():
    key = ECKey().load_key(P256())
    unprotected_headers = {"foo": "bar"}
    _jwt = JWS(msg="hello world", alg="ES256").sign_json(
        headers=[(None, unprotected_headers)],
        keys=[key])
    json_jws = json.loads(_jwt)
    jws_protected_headers = json.loads(
        b64d_enc_dec(json_jws["signatures"][0]["protected"]))
    assert jws_protected_headers == {"alg": "ES256"}
    jws_unprotected_headers = json_jws["signatures"][0]["header"]
    assert unprotected_headers == jws_unprotected_headers
def test_sign_json_dont_include_empty_unprotected_headers():
    key = ECKey().load_key(P256())
    protected_headers = {"foo": "bar"}
    _jwt = JWS(msg="hello world", alg="ES256").sign_json(
        headers=[(protected_headers, None)],
        keys=[key])
    json_jws = json.loads(_jwt)
    assert "header" not in json_jws["signatures"][0]
    jws_protected_headers = json.loads(
        b64d_enc_dec(json_jws["signatures"][0]["protected"]))
    assert set(protected_headers.items()).issubset(
        set(jws_protected_headers.items()))
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_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(key=_pkey)]
    # keys[0]._keytype = "private"
    _jws = JWS(payload, alg="PS512")
    _jwt = _jws.sign_compact(keys)

    vkeys = [RSAKey(key=_pkey.public_key())]
    _rj = factory(_jwt)
    info = _rj.verify_compact(_jwt, vkeys)
    assert info == payload
def test_sign_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)
    json_jws = json.loads(_jwt)
    assert "signatures" not in json_jws

    assert b64d_enc_dec(json_jws["payload"]) == payload
    assert json_jws["header"] == unprotected_headers
    assert json.loads(b64d_enc_dec(json_jws["protected"])) == protected_headers
def test_sign_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])
    jwt = json.loads(_jwt)
    assert b64d_enc_dec(jwt["payload"]) == payload
    assert len(jwt["signatures"]) == 1
    assert jwt["signatures"][0]["header"] == unprotected_headers
    assert json.loads(
        b64d_enc_dec(jwt["signatures"][0]["protected"])) == protected_headers
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 = KEYS()
    keys.load_dict(keyset)
    jws = JWS("payload", alg="RS512")
    jws.sign_compact(keys=keys)
def test_pick_alg_assume_alg_from_single_key():
    expected_alg = "HS256"
    keys = [SYMKey(k="foobar", alg=expected_alg)]

    alg = JWS()._pick_alg(keys)
    assert alg == expected_alg