<s> """<STR_LIT>""" <EOL> import base64 <EOL> import hashlib <EOL> import hmac <EOL> try : <EOL> import json <EOL> except ImportError : <EOL> import simplejson as json <EOL> __all__ = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> class DecodeError ( Exception ) : pass <EOL> signing_methods = { <EOL> '<STR_LIT>' : lambda msg , key : hmac . new ( key , msg , hashlib . sha256 ) . digest ( ) , <EOL> '<STR_LIT>' : lambda msg , key : hmac . new ( key , msg , hashlib . sha384 ) . digest ( ) , <EOL> '<STR_LIT>' : lambda msg , key : hmac . new ( key , msg , hashlib . sha512 ) . digest ( ) , <EOL> } <EOL> def base64url_decode ( input ) : <EOL> input += '<STR_LIT:=>' * ( <NUM_LIT:4> - ( len ( input ) % <NUM_LIT:4> ) ) <EOL> return base64 . urlsafe_b64decode ( input ) <EOL> def base64url_encode ( input ) : <EOL> return base64 . urlsafe_b64encode ( input ) . replace ( '<STR_LIT:=>' , '<STR_LIT>' ) <EOL> def header ( jwt ) : <EOL> header_segment = jwt . split ( '<STR_LIT:.>' , <NUM_LIT:1> ) [ <NUM_LIT:0> ] <EOL> try : <EOL> return json . loads ( base64url_decode ( header_segment ) ) <EOL> except ( ValueError , TypeError ) : <EOL> raise DecodeError ( "<STR_LIT>" ) <EOL> def encode ( payload , key , algorithm = '<STR_LIT>' ) : <EOL> segments = [ ] <EOL> header = { "<STR_LIT>" : "<STR_LIT>" , "<STR_LIT>" : algorithm } <EOL> segments . append ( base64url_encode ( json . dumps ( header ) ) ) <EOL> segments . append ( base64url_encode ( json . dumps ( payload ) ) ) <EOL> signing_input = '<STR_LIT:.>' . join ( segments ) <EOL> try : <EOL> ascii_key = unicode ( key ) . encode ( '<STR_LIT:utf8>' ) <EOL> signature = signing_methods [ algorithm ] ( signing_input , ascii_key ) <EOL> except KeyError : <EOL> raise NotImplementedError ( "<STR_LIT>" ) <EOL> segments . append ( base64url_encode ( signature ) ) <EOL> return '<STR_LIT:.>' . join ( segments ) <EOL> def decode ( jwt , key = '<STR_LIT>' , verify = True ) : <EOL> try : <EOL> signing_input , crypto_segment = jwt . rsplit ( '<STR_LIT:.>' , <NUM_LIT:1> ) <EOL> header_segment , payload_segment = signing_input . split ( '<STR_LIT:.>' , <NUM_LIT:1> ) <EOL> except ValueError : <EOL> raise DecodeError ( "<STR_LIT>" ) <EOL> try : <EOL> header = json . loads ( base64url_decode ( header_segment ) ) <EOL> payload = json . loads ( base64url_decode ( payload_segment ) ) <EOL> signature = base64url_decode ( crypto_segment ) <EOL> except ( ValueError , TypeError ) : <EOL> raise DecodeError ( "<STR_LIT>" ) <EOL> if verify : <EOL> try : <EOL> ascii_key = unicode ( key ) . encode ( '<STR_LIT:utf8>' ) <EOL> if not signature == signing_methods [ header [ '<STR_LIT>' ] ] ( signing_input , ascii_key ) : <EOL> raise DecodeError ( "<STR_LIT>" ) <EOL> except KeyError : <EOL> raise DecodeError ( "<STR_LIT>" ) <EOL> return payload </s>
