11import binascii
22import datetime
3+ import json
34import logging
45import six
56import zlib
67
78from base64 import urlsafe_b64encode , urlsafe_b64decode
89from collections import namedtuple
910from copy import deepcopy
10- from json import loads as json_decode , dumps as json_encode
1111from struct import pack
1212from time import time
1313
@@ -137,15 +137,13 @@ def encrypt(claims, jwk, adata=six.b(''), add_header=None, alg='RSA-OAEP',
137137 assert _TEMP_VER_KEY not in claims
138138 claims [_TEMP_VER_KEY ] = _TEMP_VER
139139
140- header = dict (
141- list ((add_header or {}).items ()) + [('enc' , enc ), ('alg' , alg )]
142- )
140+ header = dict (add_header or {}, enc = enc , alg = alg )
143141
144142 # promote the temp key to the header
145143 assert _TEMP_VER_KEY not in header
146144 header [_TEMP_VER_KEY ] = claims [_TEMP_VER_KEY ]
147145
148- plaintext = six . b ( json_encode (claims ) )
146+ plaintext = json_encode (claims )
149147
150148 # compress (if required)
151149 if compression is not None :
@@ -205,7 +203,7 @@ def decrypt(jwe, jwk, adata=six.b(''), validate_claims=True,
205203 header , encryption_key_ciphertext , iv , ciphertext , tag = map (
206204 b64decode_url , jwe
207205 )
208- header = json_decode (header . decode () )
206+ header = json_decode (header )
209207
210208 # decrypt cek
211209 (_ , decipher ), _ = JWA [header ['alg' ]]
@@ -240,7 +238,7 @@ def decrypt(jwe, jwk, adata=six.b(''), validate_claims=True,
240238
241239 plaintext = decompress (plaintext )
242240
243- claims = json_decode (plaintext . decode () )
241+ claims = json_decode (plaintext )
244242 try :
245243 del claims [_TEMP_VER_KEY ]
246244 except KeyError :
@@ -265,8 +263,7 @@ def sign(claims, jwk, add_header=None, alg='HS256'):
265263 :rtype: :class:`~jose.JWS`
266264 """
267265 (hash_fn , _ ), mod = JWA [alg ]
268-
269- header = dict (list ((add_header or {}).items ()) + [('alg' , alg )])
266+ header = dict (add_header or {}, alg = alg )
270267 header , payload = map (b64encode_url , map (json_encode , (header , claims )))
271268
272269 sig = b64encode_url (
@@ -295,7 +292,7 @@ def verify(jws, jwk, alg, validate_claims=True, expiry_seconds=None):
295292 :raises: :class:`~jose.Error` if there is an error decrypting the JWE
296293 """
297294 header , payload , sig = map (b64decode_url , jws )
298- header = json_decode (header . decode () )
295+ header = json_decode (header )
299296 if alg != header ['alg' ]:
300297 raise Error ('Invalid algorithm' )
301298
@@ -306,7 +303,7 @@ def verify(jws, jwk, alg, validate_claims=True, expiry_seconds=None):
306303 ):
307304 raise Error ('Mismatched signatures' )
308305
309- claims = json_decode (b64decode_url (jws .payload ). decode () )
306+ claims = json_decode (b64decode_url (jws .payload ))
310307 _validate (claims , validate_claims , expiry_seconds )
311308
312309 return JWT (header , claims )
@@ -326,22 +323,21 @@ def b64encode_url(istr):
326323 """ JWT Tokens may be truncated without the usual trailing padding '='
327324 symbols. Compensate by padding to the nearest 4 bytes.
328325 """
329- return urlsafe_b64encode (encode_safe ( istr ) ).rstrip (six .b ('=' ))
326+ return urlsafe_b64encode (istr ).rstrip (six .b ('=' ))
330327
331328
332- if six .PY3 :
333- def encode_safe (istr , encoding = 'utf8' ):
334- if not isinstance (istr , bytes ):
335- return bytes (istr , encoding = encoding )
336- return istr
337- else :
338- def encode_safe (istr , encoding = 'utf8' ):
339- try :
340- return istr .encode (encoding )
341- except UnicodeDecodeError :
342- # this will fail if istr is already encoded
343- pass
344- return istr
329+ def json_encode (x ):
330+ """
331+ Dict -> Binary
332+ """
333+ return json .dumps (x ).encode ()
334+
335+
336+ def json_decode (x ):
337+ """
338+ Binary -> Dict
339+ """
340+ return json .loads (x .decode ())
345341
346342
347343def auth_tag (hmac ):
@@ -355,12 +351,16 @@ def pad_pkcs7(s):
355351 return s + (six .int2byte (sz ) * sz )
356352
357353
358- if six .PY3 :
359- def unpad_pkcs7 ( s ):
360- return s [: - s [ - 1 ]]
354+ if six .PY2 :
355+ def _ord ( x ):
356+ return ord ( x )
361357else :
362- def unpad_pkcs7 (s ):
363- return s [:- ord (s [- 1 ])]
358+ def _ord (x ):
359+ return x
360+
361+
362+ def unpad_pkcs7 (s ):
363+ return s [:- _ord (s [- 1 ])]
364364
365365
366366def encrypt_oaep (plaintext , jwk ):
@@ -411,24 +411,14 @@ def decrypt_aescbc(ciphertext, key, iv):
411411 return unpad_pkcs7 (AES .new (key , AES .MODE_CBC , iv ).decrypt (ciphertext ))
412412
413413
414- if six .PY3 :
415- def const_compare (stra , strb ):
416- if len (stra ) != len (strb ):
417- return False
414+ def const_compare (stra , strb ):
415+ if len (stra ) != len (strb ):
416+ return False
418417
419- res = 0
420- for a , b in zip (stra , strb ):
421- res |= a ^ b
422- return res == 0
423- else :
424- def const_compare (stra , strb ):
425- if len (stra ) != len (strb ):
426- return False
427-
428- res = 0
429- for a , b in zip (stra , strb ):
430- res |= ord (a ) ^ ord (b )
431- return res == 0
418+ res = 0
419+ for a , b in zip (stra , strb ):
420+ res |= _ord (a ) ^ _ord (b )
421+ return res == 0
432422
433423
434424class _JWA (object ):
0 commit comments