Skip to content

Commit 8ce7278

Browse files
committed
Working on the tests
1 parent e460aae commit 8ce7278

File tree

6 files changed

+124
-134
lines changed

6 files changed

+124
-134
lines changed

src/cryptojwt/aes_key_wrap.py

Lines changed: 0 additions & 95 deletions
This file was deleted.

src/cryptojwt/jwk.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -145,20 +145,16 @@ def load_x509_cert(url, spec2key):
145145
return []
146146

147147

148-
def rsa_load(filename, passphrase):
149-
"""Read a PEM-encoded RSA key pair from a file."""
148+
def rsa_load(filename, passphrase=None):
149+
"""Read a PEM-encoded RSA private key from a file."""
150150
with open(filename, "rb") as key_file:
151151
pem_data = key_file.read()
152152
private_key = serialization.load_pem_private_key(
153153
pem_data,
154154
password=passphrase,
155155
backend=default_backend())
156156

157-
public_key = serialization.load_pem_public_key(
158-
pem_data,
159-
backend=default_backend()
160-
)
161-
return private_key, public_key
157+
return private_key
162158

163159

164160
def rsa_eq(key1, key2):

src/cryptojwt/jwt.py

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
from cryptojwt import jwe
77
from cryptojwt import jws
88
from cryptojwt.jwe import JWE
9-
from cryptojwt.jws import alg2keytype
109
from cryptojwt.jws import JWS
1110
from cryptojwt.jws import NoSuitableSigningKeys
1211

@@ -20,6 +19,15 @@ def utc_time_sans_frac():
2019

2120

2221
def pick_key(keys, use, alg='', key_type='', kid=''):
22+
"""
23+
24+
:param keys: List of keys
25+
:param use: What the key is going to be used for
26+
:param alg: crypto algorithm
27+
:param key_type: Type of key
28+
:param kid: Ley ID
29+
:return: list of keys that match the pattern
30+
"""
2331
res = []
2432
if not key_type:
2533
if use == 'sig':
@@ -51,14 +59,17 @@ def get_jwt_keys(jwt, keys, use):
5159
except KeyError:
5260
_kid = ''
5361

62+
# Pick issuers keys
63+
5464
return pick_key(keys, use, key_type=_key_type, kid=_kid)
5565

5666

5767
class JWT(object):
58-
def __init__(self, keys, iss='', lifetime=0, sign_alg='RS256',
59-
encrypt=False, enc_enc="A128CBC-HS256",
68+
def __init__(self, own_keys, iss='', rec_keys=None, lifetime=0,
69+
sign_alg='RS256', encrypt=False, enc_enc="A128CBC-HS256",
6070
enc_alg="RSA1_5"):
61-
self.keys = keys
71+
self.own_keys = own_keys
72+
self.rec_keys = rec_keys or {}
6273
self.iss = iss
6374
self.lifetime = lifetime
6475
self.sign_alg = sign_alg
@@ -67,15 +78,15 @@ def __init__(self, keys, iss='', lifetime=0, sign_alg='RS256',
6778
self.enc_enc = enc_enc
6879
self.with_jti = False
6980

70-
def _encrypt(self, payload, cty='JWT'):
81+
def _encrypt(self, payload, recv, cty='JWT'):
7182
kwargs = {"alg": self.enc_alg, "enc": self.enc_enc}
7283

7384
if cty:
7485
kwargs["cty"] = cty
7586

7687
# use the clients public key for encryption
7788
_jwe = JWE(payload, **kwargs)
78-
return _jwe.encrypt(self.keys, context="public")
89+
return _jwe.encrypt(self.rec_keys[recv], context="public")
7990

8091
def pack_init(self):
8192
"""
@@ -96,21 +107,20 @@ def pack_key(self, owner='', kid=''):
96107
:param kid: Key ID
97108
:return: One key
98109
"""
99-
keys = pick_key(self.keys, 'sig', alg=self.sign_alg, kid=kid)
110+
keys = pick_key(self.own_keys, 'sig', alg=self.sign_alg, kid=kid)
100111

101112
if not keys:
102113
raise NoSuitableSigningKeys('kid={}'.format(kid))
103114

104115
return keys[0] # Might be more then one if kid == ''
105116

106-
def pack(self, payload=None, kid='', owner='', cls_instance=None, **kwargs):
117+
def pack(self, payload=None, kid='', owner='', recv='', **kwargs):
107118
"""
108119
109120
:param payload: Information to be carried as payload in the JWT
110121
:param kid: Key ID
111122
:param owner: The owner of the the keys that are to be used for signing
112-
:param cls_instance: This might be a instance of a class already
113-
prepared with information
123+
:param recv: The intended receiver
114124
:param kwargs: Extra keyword arguments
115125
:return: A signed or signed and encrypted JsonWebtoken
116126
"""
@@ -144,12 +154,12 @@ def pack(self, payload=None, kid='', owner='', cls_instance=None, **kwargs):
144154
_sjwt = _jws.sign_compact([_key])
145155
#_jws = _jwt.to_jwt([_key], self.sign_alg)
146156
if _encrypt:
147-
return self._encrypt(_sjwt)
157+
return self._encrypt(_sjwt, recv)
148158
else:
149159
return _sjwt
150160

151161
def _verify(self, rj, token):
152-
keys = get_jwt_keys(rj.jwt, self.keys, 'sig')
162+
keys = get_jwt_keys(rj.jwt, self.rec_keys, 'sig')
153163
return rj.verify_compact(token, keys)
154164

155165
def _decrypt(self, rj, token):
@@ -160,7 +170,7 @@ def _decrypt(self, rj, token):
160170
:param token: The encrypted JsonWebToken
161171
:return:
162172
"""
163-
keys = get_jwt_keys(rj.jwt, self.keys, 'enc')
173+
keys = get_jwt_keys(rj.jwt, self.own_keys, 'enc')
164174
return rj.decrypt(token, keys=keys)
165175

166176
def unpack(self, token):

tests/test_1_jwt.py renamed to tests/test_0_simplejwt.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import pytest
22

3-
from cryptojwt.jwt import bytes2str_conv
4-
from cryptojwt.jwt import JWT
3+
from cryptojwt import bytes2str_conv
4+
from cryptojwt import SimpleJWT
55

66
__author__ = 'roland'
77

@@ -11,7 +11,7 @@ def _eq(l1, l2):
1111

1212

1313
def test_pack_jwt():
14-
_jwt = JWT(**{"alg": "none", "cty": "jwt"})
14+
_jwt = SimpleJWT(**{"alg": "none", "cty": "jwt"})
1515
jwt = _jwt.pack(parts=[{"iss": "joe", "exp": 1300819380,
1616
"http://example.com/is_root": True}, ""])
1717

@@ -20,22 +20,22 @@ def test_pack_jwt():
2020

2121

2222
def test_unpack_pack():
23-
_jwt = JWT(**{"alg": "none"})
23+
_jwt = SimpleJWT(**{"alg": "none"})
2424
payload = {"iss": "joe", "exp": 1300819380,
2525
"http://example.com/is_root": True}
2626
jwt = _jwt.pack(parts=[payload, ""])
27-
repacked = JWT().unpack(jwt).pack()
27+
repacked = SimpleJWT().unpack(jwt).pack()
2828

2929
assert jwt == repacked
3030

3131

3232
def test_pack_unpack():
33-
_jwt = JWT(**{"alg": "none"})
33+
_jwt = SimpleJWT(**{"alg": "none"})
3434
payload = {"iss": "joe", "exp": 1300819380,
3535
"http://example.com/is_root": True}
3636
jwt = _jwt.pack(parts=[payload, ""])
3737

38-
_jwt2 = JWT().unpack(jwt)
38+
_jwt2 = SimpleJWT().unpack(jwt)
3939

4040
assert _jwt2
4141
out_payload = _jwt2.payload()
@@ -47,18 +47,18 @@ def test_pack_unpack():
4747

4848

4949
def test_pack_with_headers():
50-
_jwt = JWT()
50+
_jwt = SimpleJWT()
5151
jwt = _jwt.pack(parts=["", ""], headers={"foo": "bar"})
52-
assert JWT().unpack(jwt).headers["foo"] == "bar"
52+
assert SimpleJWT().unpack(jwt).headers["foo"] == "bar"
5353

5454

5555
def test_unpack_str():
56-
_jwt = JWT(**{"alg": "none"})
56+
_jwt = SimpleJWT(**{"alg": "none"})
5757
payload = {"iss": "joe", "exp": 1300819380,
5858
"http://example.com/is_root": True}
5959
jwt = _jwt.pack(parts=[payload, ""])
6060

61-
_jwt2 = JWT().unpack(jwt)
61+
_jwt2 = SimpleJWT().unpack(jwt)
6262
assert _jwt2
6363
out_payload = _jwt2.payload()
6464

tests/test_2_jwk.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -372,28 +372,22 @@ def test_thumbprint():
372372
keyl.load_dict(JWKS)
373373
for key in keyl:
374374
txt = key.thumbprint('SHA-256')
375-
assert b64e(txt) in EXPECTED
375+
assert txt in EXPECTED
376376

377377

378378
def test_thumbprint_7638_example():
379379
key = RSAKey(
380380
n='0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw',
381381
e='AQAB', alg='RS256', kid='2011-04-29')
382382
thumbprint = key.thumbprint('SHA-256')
383-
assert b64e(thumbprint) == b'NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs'
383+
assert thumbprint == b'NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs'
384384

385385

386386
def test_load_jwks():
387387
keysl = load_jwks(json.dumps(JWKS))
388388
assert len(keysl) == 3
389389

390390

391-
# def test_copy():
392-
# keysl = load_jwks(json.dumps(JWKS))
393-
# ckl = [copy.copy(k) for k in keysl]
394-
# assert len(ckl) == 3
395-
396-
397391
def test_encryption_key():
398392
sk = SYMKey(key='df34db91c16613deba460752522d28f6ebc8a73d0d9185836270c26b')
399393
_enc = sk.encryption_key(alg='A128KW')

0 commit comments

Comments
 (0)