from jwcrypto import jwk, jwe from jwcrypto.common import json_encode, json_decode public_key = jwk.JWK() private_key = """ {"alg":"RS256", "kty":"RSA", "n": "vfqF7S/dgxm/K7C7r7gc27a/pUPv8jZgjuchDB/fQthDZ19sM1qt76rrTQg8Ey61bRQnzYXN2m7T/KybRe+JV+TdbmtprdQgYNv7U09S1ISckkZ/v8VMu6FX9j82EVkgTUoZuyB3WoZuMz2UEynioHqD26xLFYZoDWOFrOgJ50uKbLDHNK8nKB2g8sTGVkABuX0apYY/OpOJSgx4ZQcRGUMYee3xn1QiszYyvMSijTzKm3iFr6G4IodK/fwBlf3zsyWbMTi8kl7r1CY/fHPoXf7C7UcUIQ69YMzsUdf5m82Ie5HJgU/GP+KOY/rA6EzLSyuwCZuCCes/ycqV2e1Unw==", "e":"AQAB", "d":"G0izBPJLtwvdZkTEDRj9NVraIZM6ZIgFtxBKW+eUlLuNdqJViPc8JWsKecOLKTAbSJainsQu4RuV9g3DYQ26pQpj+NCUBViClpaRUjuBXa8hSMAM5yRKqw8hcbv4o7uFRZm091MoK7KZz2HHyzbH6vHyz6Y/bvsgz3zHEng4D+UMThY6HK0M3h2ken1oRth5HoDvLmTtOpIps3ZpjItP5C4uBGRg/kqyW3Tly0lbPz57uuf0jT8bIXfnPK/mbK3gfv0mqeg7NQN6byEKDkkt2gC3fL87CzZZh1L+nJiveXyvgxmbbONHr3BoS6XOuH2TDkTGC1Z1w7kvfQbHLRDTzQ==", "p":"80/1E2B8aVb3mXrLAVUMZExzqw39IEgma5ooIssbRzyMtNDfon20OmCQmmmntKxLsAzBv3nbxWGLAAOZ7Vafrlw4Tra/siG0ZDFJk9/c+Mn0B5/Mf+hKTngqMU47sDCWpA0r4XF5R/7SW1qnWoNeujVI6duRRV3AKN7ru+tIkyU=", "q":"x+KZb4IP93E49icqntemCppKLFV4o7tVWbKpwuj4HIGLZ7z9rh02mBYtSakdvV8QzNb9Za4v8OEwIgAkGVYKEnRFPx9IUezzYiKXzpN1PxEEyyNNFL4KPK5szAZFviD9LShfFVttSmXsm5r7WOnlpJWjjjcXsW/K9Dlfaimu33M=", "dp":"EH+vgqzcQthe2c11zpVRzctRXJwKOhIqaMl/Rzy2kNIOSISRZZdYjUzXAWGAucOlLj7vNGiy+mNu5YVY/rsNAOnH9650uUOH0/Nzpc9cUJKBNbMkTtgVkdScJ9PCQGRLErzB6Puk2bjx0rgG+SBHYCEU3KbC5w1AZoUXPxrpRPE=", "dq":"TdgW71FUzIYArASW2aOcW5a4+kkTIZjMZZFqAalfLyLYWr9EgHGKGHLSklRVa7HBRjUYHGhY7VOVvjgV1vQmGgfEDBAvxxAjvP1B58aPq88B8ea+lyxnqjg30MFEmgYY82Q8m4Gur4HAQt15s6frskxAlRsplAW4oaJSYXL4Urc=", "qi":"K1sZbejgybDcKUjRnFUvwBCgno9U03UJi1lOl0FS4HjUoADTuykCRcvU+LJQkW48qy26H5O5axZKL2wYP/HLWKEm2z/92Mvbt01FujrGwfnwEnoekPxo+Ykul7Xlcz0LYOhNvs702om3CAYEaYc7Q4SqFtw2JMbzntMx8B398tY="} """ public_key.import_key(**json_decode(private_key)) payload = "My Encrypted message" protected_header = { "alg": "RSA-OAEP-256", "enc": "A256CBC-HS512", "typ": "JWE", "kid": public_key.thumbprint(), } jwetoken = jwe.JWE(payload.encode('utf-8'), recipient=public_key, protected=protected_header) enc = jwetoken.serialize() print(enc)
def _import_key(expkey): if expkey['kty'] != 'EC': raise exceptions.DXFUnexpectedKeyTypeError(expkey['kty'], 'EC') if expkey['crv'] != 'P-256': raise exceptions.DXFUnexpectedKeyTypeError(expkey['crv'], 'P-256') return jwk.JWK(kty='EC', crv='P-256', x=expkey['x'], y=expkey['y'])
def __read_private_key(path: str) -> jwk.JWK: with open(path, "rb") as private_key_file: key = jwk.JWK() key.import_from_pem(data=private_key_file.read()) return key
from jwcrypto import jwk, jwe from jwcrypto.common import json_encode, json_decode public_key_dict = { "alg": "RSA-OAEP", "e": "AQAB", "kid": "rsa-5ofWP09ChW4qop6P43XbF7_F2PnEJ7_hBhXAarwQfnQ", "kty": "RSA", "n": "pZsjTGAeeIV4uvHvFj1U3Pry5RF26MdCYGNUVVr5XJLEuWE0wAe7TBzR-QcOpH0fpo1nK6sf3AYWjJVHSEZWX2v_v7MlyPOihcoy95LEOTpILa3arzMRPuxJD9tuF999VZkRtqNjDlEDCO_tKA0WizhxXtwx7SmuooU93M5JSkw5R-1GslF76J_Lx-bXc6u7zk77ImtLipS6NghRjMYOgsQwZ0mCNWSjq-IdsnGNyYuWrH9IBXXy3cZ8B8bnwQ1LzTepBq2Ai5lkotUuRIkY2Jj0CDkGEDTKjh5rfuprYT0luRy7E15l3UGLUpQ5L4t90vjpMd9JO2sF657H-QleNQ", "use": "enc" } public_key = jwk.JWK(**public_key_dict) payload = "My Encrypted message" protected_header = { "alg": "RSA-OAEP", "enc": "A256GCM", "kid": public_key.thumbprint(), } jwetoken = jwe.JWE(payload.encode('utf-8'), recipient=public_key, protected=protected_header) enc_JSON = jwetoken.serialize() enc = jwetoken.serialize(compact=True) print("JSON:\n", enc_JSON, "\n") print("Compact:\n", enc)
def get_jwk_from_secret(secret): return jwk.JWK(kty="oct", k=base64url_encode(secret.encode("utf-8")))
Here the code is stored along with the user who requested it and service it came from. Service_Components stores the generated code as well. User is redirected to service login with the code. USER: --> GET /login?code=somecode User logins and agrees the linking. Surrogate ID is generated and sent to OPERATOR. SERVICE: --> POST /register?surrogate=SURROGRATEID1&code=somecode <-- :OPERATOR 200 OK Using the code we link surrogate id to MyData Account and service confirming the link. ''' Service_ID = "SRV-SH14W4S3" gen = {"generate": "EC", "cvr": "P-256", "kid": Service_ID} token_key = jwk.JWK(**gen) # templ = {Service_ID: loads(token_key.export_public())} templ = {Service_ID: {"cr_keys": loads(token_key.export_public())}} from functools import wraps from flask import request, Response def valid_credentials(username, password): """This function is called to check if a username / password combination is valid. """ compared_pw = users.get(username, None) if compared_pw is not None: return password == compared_pw else:
### IMPORT CUSTOM KEYS - JSON - ALTERNATIVE 2 priv_json = open("keys/rsa-private-key.json", "rb").read().replace('"use": "sig",','') #ignore use: sig because we are using use: enc print("\nImporting following Private Key:\n" ) print(priv_json.replace(", " , ", \n" )) print("--------") pub_json = open("keys/rsa-public-key.json", "rb").read().replace('"use": "sig",','') #ignore use: sig because we are using use: enc print("\nImporting following Public Key:\n" ) print(pub_json.replace(", " , ", \n" )) print("--------") private_key = jwk.JWK() private_key.import_key(**json_decode(priv_json)) public_key = jwk.JWK() public_key.import_key(**json_decode(pub_json)) ### IMPORT CUSTOM KEYS - PEM - ALTERNATIVE 3 # pub_pem = open("keys/rsa-public-key.pem", "rb").read() # print("\nTrying to import following Public Key PEM:\n" ) # print(pub_pem) # print("--------")
def lambda_handler(event, context): print(event) try: if 'headers' in event: cookie = event['headers']['Cookie'] else: cookie = event['authorizationToken'] charset = re.findall(cookie_re, cookie) if len(charset): token = charset[0] else: token = cookie method = event['methodArn'] print(f'token extracted: {token}') print(f'method requested: {method}') with open('authorizer/key.json', 'rb') as file: key = jwk.JWK(**json.loads(file.read())) verified = jwt.JWT(key=key, jwt=token) except KeyError as e: raise Exception( bodyTemplate.format(403, 'Unauthorized: no session cookie found', str(e))) except (jwk.InvalidJWKValue, jwk.InvalidJWKOperation, jwk.InvalidJWKUsage, jws.InvalidJWSSignature, jws.InvalidJWSObject, jws.InvalidJWSOperation) as e: raise Exception( bodyTemplate.format(403, 'Unauthorized: token not valid', str(e))) except: raise Exception( bodyTemplate.format(403, 'Unauthorized: unknown error', 'token=' + str(token) + ' event=' + str(event))) claims = json.loads(verified.claims) principalId = claims['prn'] """if the token is valid, a policy must be generated which will allow or deny access to the client""" """if access is denied, the client will recieve a 403 Access Denied response""" """if access is allowed, API Gateway will proceed with the backend integration configured on the method that was called""" """this function must generate a policy that is associated with the recognized principal user identifier.""" """depending on your use case, you might store policies in a DB, or generate them on the fly""" """keep in mind, the policy is cached for 5 minutes by default (TTL is configurable in the authorizer)""" """and will apply to subsequent calls to any method/resource in the RestApi""" """made with the same token""" """the example policy below denies access to all resources in the RestApi""" tmp = method.split(':') apiGatewayArnTmp = tmp[5].split('/') awsAccountId = tmp[4] policy = AuthPolicy(principalId, awsAccountId) policy.restApiId = apiGatewayArnTmp[0] policy.region = tmp[3] policy.stage = apiGatewayArnTmp[1] # policy.denyAllMethods() policy.allowMethod(HttpVerb.GET, "/*") # Finally, build the policy authResponse = policy.build() # new! -- add additional key-value pairs associated with the authenticated principal # these are made available by APIGW like so: $context.authorizer.<key> # additional context is cached context = dict(claims) authResponse['context'] = context return authResponse
def generate_secret_key(): key = jwk.JWK() # Generate 256-bit AES key for encryption key = key.generate(kty='oct', alg='A256KW', use='enc') return json.loads(key.export())
def __init__(self): super(RegisterSur, self).__init__() self.app = current_app #print(current_app.config) keysize = current_app.config["KEYSIZE"] cert_key_path = current_app.config["CERT_KEY_PATH"] self.request_timeout = current_app.config["TIMEOUT"] SUPER_DEBUG = True account_id = "ACC-ID-RANDOM" user_account_id = account_id + "_" + str(guid()) # Keys need to come from somewhere else instead of being generated each time. gen = {"generate": "EC", "cvr": "P-256", "kid": user_account_id} gen3 = {"generate": "RSA", "size": keysize, "kid": account_id} operator_key = jwk.JWK(**gen3) try: with open(cert_key_path, "r") as cert_file: operator_key2 = jwk.JWK(**loads(load(cert_file))) operator_key = operator_key2 except Exception as e: print(e) with open(cert_key_path, "w+") as cert_file: dump(operator_key.export(), cert_file, indent=2) # Template to send the key to key server template = { account_id: { "cr_keys": loads(operator_key.export_public()), "token_keys": loads(operator_key.export_public()) } } # post("http://localhost:6666/key", json=template) self.payload = \ { "version": "1.2", "link_id": "", "operator_id": account_id, "service_id": "SRV-SH14W4S3", # How do we know this? "surrogate_id": "", "token_key": "", "operator_key": loads(operator_key.export_public()), "cr_keys": "", "created": "" # time.time(), } debug_log.info(dumps(self.payload, indent=3)) protti = {"alg": "RS256"} headeri = { "kid": user_account_id, "jwk": loads(operator_key.export_public()) } self.service_registry_handler = ServiceRegistryHandler() self.am_url = current_app.config["ACCOUNT_MANAGEMENT_URL"] self.am_user = current_app.config["ACCOUNT_MANAGEMENT_USER"] self.am_password = current_app.config["ACCOUNT_MANAGEMENT_PASSWORD"] self.timeout = current_app.config["TIMEOUT"] try: self.AM = AccountManagerHandler(self.am_url, self.am_user, self.am_password, self.timeout) except Exception as e: debug_log.warn( "Initialization of AccountManager failed. We will crash later but note it here.\n{}" .format(repr(e))) self.Helpers = Helpers(current_app.config) self.query_db = self.Helpers.query_db
async def return_view(req): """Return view for processing authentication results from the Identity Service Broker.""" code = req.args.get('code') error = req.args.get('error') sessionid = req.args.get('state') error_description = req.args.get('error_description') layout = '' # Default value (to be populated with '' or 'embedded') if not sessionid or sessionid not in sessions: error = error or 'Invalid session' else: layout = sessions[sessionid].layout if error: if error == 'cancel': template = jinja.get_template('cancel.html') return sanic.response.html( template.render(error=error, layout=layout)) else: template = jinja.get_template('error.html') return sanic.response.html( template.render(error=error, error_description=error_description, layout=layout)) # Resolve the access code async with aiohttp.ClientSession() as httpSession: data = aiohttp.FormData() data.add_field('code', code) data.add_field('redirect_uri', 'https://{0}/return'.format(HOSTNAME)) data.add_field('grant_type', 'authorization_code') data.add_field('client_assertion', make_token_jwt()) data.add_field( 'client_assertion_type', 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer') headers = dict(Accept='application/json') async with httpSession.post(TOKEN_ENDPOINT, data=data, headers=headers) as tokenresp: token_data = await tokenresp.text() try: id_token = json_decode(token_data)['id_token'] except KeyError: raise ValueError(token_data) jwetoken = jwe.JWE() jwetoken.deserialize(id_token) jwetoken.decrypt(decryption_key) jwstoken = jws.JWS() jwstoken.allowed_algs = ALLOWED_ALGS jwstoken.deserialize(jwetoken.payload.decode('ascii')) sig_key = jwstoken.jose_header['kid'] async with aiohttp.ClientSession() as httpSession: async with httpSession.get(ISBKEY_ENDPOINT) as jwkresp: keys = await jwkresp.json() for key in keys['keys']: kid = key['kid'] if kid == sig_key: isb_cert = jwk.JWK(**key) jwstoken.verify(isb_cert) id_token = json_decode(jwstoken.payload) date = datetime.datetime.now() datestring = date.strftime("%c") variables = repr(id_token) if id_token["nonce"] != sessions[sessionid].nonce: error = 'nonce does not match' error_description = '{} != {}'.format(id_token["nonce"], sessions[sessionid].nonce) template = jinja.get_template('error.html') return sanic.response.html( template.render(error=error, error_description=error_description, layout=layout)) template = jinja.get_template('result.html') return sanic.response.html( template.render(variables=variables, id_token=id_token, layout=layout, datestring=datestring))
def post(self): try: debug_log.info(dumps(request.json, indent=2)) sq.task("Load SLR to object") slr = request.json["slr"] debug_log.info("SLR STORE:\n", slr) sq.task("Load slr payload as object") payload = slr["payload"] payload = slr["payload"] debug_log.info("Before Fix:{}".format(payload)) sq.task("Fix possible incorrect padding in payload") payload += '=' * (-len(payload) % 4 ) # Fix incorrect padding of base64 string. debug_log.info("After Fix :{}".format(payload)) sq.task("Decode payload and store it into object") debug_log.info(payload.encode()) content = decode(payload.encode()) sq.task("Load decoded payload as python dict") payload = loads( loads(content.decode("utf-8")) ) # TODO: Figure out why we get str out of loads the first time? debug_log.info(payload) debug_log.info(type(payload)) sq.task("Fetch surrogate_id from decoded payload") surrogate_id = payload["surrogate_id"].encode() debug_log.info(content) sq.task("Load code from json payload") code = request.json["data"]["code"].encode() sq.task("Verify surrogate_id and code") debug_log.info("Surrogate was found: {}".format( self.helpers.verifySurrogate(code, surrogate_id))) except Exception as e: raise DetailedHTTPException( title="Verifying Surrogate ID failed", exception=e, trace=traceback.format_exc(limit=100).splitlines()) try: sq.task("Create empty JSW object") jwssa = jws.JWS() debug_log.info("SLR R:\n", loads(dumps(slr))) debug_log.info(slr["header"]["jwk"]) sq.task("Deserialize slr to JWS object created before") jwssa.deserialize(dumps(slr)) sq.task( "Load JWK used to sign JWS from the slr headers into an object" ) sign_key = jwk.JWK(**slr["header"]["jwk"]) sq.task("Verify SLR was signed using the key shipped with it") debug_log.info(verifyJWS(slr)) verify = jwssa.verify( sign_key) # Verifying changes the state of this object except Exception as e: raise DetailedHTTPException( title="Verifying JWS signature failed", exception=e, trace=traceback.format_exc(limit=100).splitlines()) try: sq.task("Fix possible serialization errors in JWS") faulty_JSON = loads( jwssa.serialize(compact=False) ) # For some reason serialization messes up "header" from "header": {} to "header": "{}" faulty_JSON["header"] = faulty_JSON["header"] sq.task("Add our signature in the JWS") jwssa.add_signature(self.service_key, alg="RS256", header=dumps(self.headeri), protected=dumps(self.protti)) sq.task("Fix possible header errors") fixed = header_fix(loads(jwssa.serialize(compact=False))) debug_log.info("{}\n{}\n{}".format( "Verified and Signed Signature:\n", dumps(fixed, indent=3), "\n###### END OF SIGNATURE #######")) sq.task("Create template for verifying JWS at Operator_Components") req = {"data": {"code": code}, "slr": fixed} debug_log.info(dumps(req, indent=2)) except Exception as e: raise DetailedHTTPException( exception=e, title= "JWS fix and subsequent signing of JWS with out key failed.", trace=traceback.format_exc(limit=100).splitlines()) sq.send_to("Operator_Components Mgmnt", "Verify SLR(JWS)") endpoint = "/api/1.2/slr/verify" result = post("{}{}".format(self.operator_url, endpoint), json=req) debug_log.info(result.status_code) if result.ok: sq.task("Store SLR into db") store = loads(loads(result.text)) debug_log.debug(dumps(store, indent=2)) self.helpers.storeJSON({store["data"]["surrogate_id"]: store}) endpoint = "/api/1.2/slr/store_slr" result = post("{}{}".format(self.service_url, endpoint), json=store) # Send copy to Service_Components else: debug_log.debug(result.reason) raise DetailedHTTPException( status=result.status_code, detail={ "msg": "Something went wrong while verifying SLR with Operator_SLR.", "Error from Operator_SLR": loads(result.text) }, title=result.reason)
def send_UDP(afilu, bfilu, t, IP, PORT, PAYLOAD, error_test, threadnumber): try: print(threadnumber) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) kierros = 0 while True: print("-" * 60) #Lähetetään check CHECK = "I am Client" PORT = int(PORT) s.sendto(CHECK.encode("utf-8"), (IP, PORT)) #print('*** send check') if error_test == 10: kierros = kierros + 1 if kierros == 20: PAYLOAD = 'max=00-00-00-00-00-00' #bfp = open(bfilu, 'r') #Config.readfp(bfp) #PAYLOAD = Config.get('KaMU','username') #bfp.close() #print ("ip:", IP) #print ("port:", PORT) #print (PAYLOAD) try: s.settimeout(t) info = s.recvfrom(1024) #print(info) key = info[0] s.settimeout(None) except: print(threadnumber, '*** timeout') continue if key == b'Good try <3': afp = open(afilu, 'r') Config.readfp(afp) PORT = int(Config.get('address', 'port')) afp.close() send_UDP(afilu, bfilu, t, IP, PORT, PAYLOAD) #Salataan ja lähetetään tieto julkisella avaimella P = dict(json.loads(key.decode("UTF-8"))) public_key = jwk.JWK(**P) claims = dict(exp=PAYLOAD) header = dict(alg="RSA-OAEP-256", enc="A128GCM") T = jwt.JWT(header, claims) T.make_encrypted_token(public_key) encrypted_signed_token = T.serialize(compact=True) #print("*** engrypted signed token:",encrypted_signed_token) s.sendto(encrypted_signed_token.encode("utf-8"), (IP, PORT)) #print(threadnumber,'*** send inoformation') afp = open(afilu, 'r') Config.readfp(afp) old_PORT = int(Config.get('address', 'port')) afp.close() if PORT == old_PORT: NEW_PORT = s.recv(1024).decode("utf-8") if PORT == b'': send_UDP(afilu, bfilu, t, IP, PORT, PAYLOAD, error_test, threadnumber) else: s.close() send_UDP(afilu, bfilu, t, IP, NEW_PORT, PAYLOAD, error_test, threadnumber) time.sleep(t) except: afp = open(afilu, 'r') Config.readfp(afp) old_PORT = int(Config.get('address', 'port')) afp.close() print(threadnumber, "New start") #time.sleep(t) send_UDP(afilu, bfilu, t, IP, old_PORT, PAYLOAD, error_test, threadnumber)
def post(self): # TODO Make this a GET, is this valid anymore? def renew_token(operator_url, record_id): sq.task("Renewing Auth Token.") token = requests.get("{}/api/1.3/cr/auth_token/{}".format( operator_url, record_id)) # TODO Get api path from some config? debug_log.info("{}, {}, {}, {}".format(token.url, token.reason, token.status_code, token.text)) store_dict = {cr_id: dumps(loads(token.text.encode()))} self.helpers.storeToken(store_dict) def fetch_data_request_urls(): params = request.json debug_log.info(params) debug_log.info(request.json) user_id = params["user_id"] cr_id = params["cr_id"] rs_id = params["rs_id"] sq.task("Get data_set_id from POST json") data_set_id = request.args.get("dataset_id", None) debug_log.info( "data_set_id is ({}), cr_id is ({}), user_id ({}) and rs_id ({})" .format(data_set_id, cr_id, user_id, rs_id)) sq.task("Create request") req = {"we want": "data"} sq.task("Validate CR") cr = self.helpers.validate_cr(cr_id, surrogate_id=user_id) sq.task("Validate Request from UI") distribution_urls = self.helpers.validate_request_from_ui( cr, data_set_id, rs_id) # Fetch data request urls # Data request urls fetched. debug_log.info("Data request urls fetched.") return cr_id, cr, distribution_urls cr_id, cr, distribution_urls = fetch_data_request_urls() sq.task("Validate Authorisation Token") surrogate_id = cr["cr"]["common_part"]["surrogate_id"] our_key = self.helpers.get_key() our_key_pub = our_key["pub"] tries = 3 # TODO: Get this from config while True: try: aud = self.helpers.validate_authorization_token( cr_id, surrogate_id, our_key_pub) break except ValueError as e: debug_log.exception(e) renew_token(self.operator_url, cr_id) if tries == 0: raise EnvironmentError( "Auth token validation failed and retry counter exceeded." ) tries -= 1 except TypeError as e: debug_log.exception(e) raise EnvironmentError("Token used too soon, halting.") # Most verifying and checking below is done in the validate_authorization_token function by jwcrypto # Fetch Authorisation Token related to CR from data storage by rs_id (cr_id?) # Check Integrity ( Signed by operator, Operator's public key can be found from SLR) # Check "Issued" timestamp # Check "Not Before" timestamp # Check "Not After" timestamp # Check that "sub" contains correct public key(Our key.) # OPT: Token expired # Get new Authorization token, start again from validation. # TODO: Make these steps work as functions that call the next step. # Check URL patterns in "aud" field # Check that fetched distribution urls can be found from "aud" field # Token validated debug_log.info("Auth Token Validated.") # With these two steps Sink has verified that it's allowed to make request. # Construct request sq.task("Construct request") # Select request URL from "aud" field # Add Authorisation Token to request # Request constructed. # Sign request # Fetch private key pair of public key specified in Authorisation Token's "sub" field. # Sign with fetched private key sq.task("Fetch key used to sign request") our_key_full = jwk.JWK() our_key_full.import_key(**our_key["key"]) # Add signature to request # Request signed. # Request created. sq.send_to("Service_Components Mgmnt (Source)", "Data Request (PoP stuff)") # Make Data Request data = [] for url in distribution_urls: req = requests.get(url, auth=SignedRequest(token=aud, sign_method=True, sign_path=True, key=our_key_full, protected=dumps( our_key["prot"]))) if req.ok: data.append(loads(req.content)) debug_log.info( "Made data request and received following data from Source: \n{}". format(dumps(loads(req.content), indent=2))) return {"response_data": data}
def decode_token(payload, secret=''): key = jwk.JWK(k=secret, kty='oct') jwt_token = jwt.JWT(key=key, jwt=payload) return json.loads(jwt_token.claims)
from jwcrypto import jwt, jwk import json key = jwk.JWK(generate='oct', size=256) print(key.export()) Token = jwt.JWT(header={"alg": "HS256"}, claims={"info": "I'm a signed token"}) Token.make_signed_token(key) print(Token.serialize()) # Etoken = jwt.JWT(header={"alg": "A256KW", "enc": "A256CBC-HS512"}, # claims=Token.serialize()) # Etoken.make_encrypted_token(key) # print(Etoken.serialize()) # k = json.loads(key.export()) # key = jwk.JWK(**k) # e = Etoken.serialize() # print(e) # ET = jwt.JWT(key=key, jwt=e) # ST = jwt.JWT(key=key, jwt=ET.claims) ST = jwt.JWT(key=key, jwt=Token.serialize()) print(ST.claims)
import ast from flask_mail import Message from jwcrypto import jwt, jwk import logging import json from auth import app from auth_utils import session, admin_auth, validate_token, preValidation, check_mail, randomPassword from DB_Model import init_db, User, Registry, db from MailConfig import mail auth_logic = Blueprint('auth_page', __name__, template_folder='templates') json1_file = open('key.json') json1_str = json1_file.read() json1_data = json.loads(json1_str) key = jwk.JWK(**json1_data) logger = logging.getLogger('REST API') @auth_logic.route('/get_token', methods=['GET']) def get_token(): """Get Token Form""" logger.info(str(request)) def logic(token): try: new_action = Registry(username=request.authorization.username, action='GetToken') db.session.add(new_action) db.session.commit() return jsonify(result=token), 200
from jwcrypto import jwk, jwt import time import json import uuid base_url = "https://test.sram.surf.nl/api/mfa/sfo" redirect_url = "https://localhost/redirect_test" subject = 'urn:john' audience_sbs = 'SBS-appid' # create or load key privkey_filename = "privkey.json" try: with open(privkey_filename, 'rb') as fd: keydata = json.load(fd) eduteams_key = jwk.JWK(**keydata) print("Loaded key from file") except (FileNotFoundError, json.JSONDecodeError): print("Generating key from scrtach") eduteams_key = jwk.JWK.generate(kty='RSA', size=512, use='sig', kid=str(uuid.uuid4())) eduteams_pubkey = eduteams_key.export_public() eduteams_privkey = eduteams_key.export_private() print("Eduteams key is:") print(json.dumps(json.loads(eduteams_privkey), indent=4)) with open("privkey.json", "wb") as privkeyfile: privkeyfile.write(eduteams_privkey.encode('utf-8'))
def read_public_key() -> jwk.JWK: with open(PRIVATE_RSA_KEY, "rb") as public_key_file: key = jwk.JWK() key.import_from_pem(data=public_key_file.read(), password=None) return key