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_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'
Ejemplo n.º 3
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()
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
Ejemplo n.º 8
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_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_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_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_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_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_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_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_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