def test_pop_jwe(): jwk = {"kty": "oct", "alg": "HS256", "k": "ZoRSOrFzN_FzUA5XKMYoVHyzff5oRJxl-IXRtztJ6uE"} encryption_keys = [RSAKey(use="enc", key=rsa, kid="some-key-id")] jwe = JWE(json.dumps(jwk), alg="RSA-OAEP", enc="A256CBC-HS512") _jwe = jwe.encrypt(keys=encryption_keys, kid="some-key-id") jwt = { "iss": "https://server.example.com", "aud": "https://client.example.org", "exp": 1361398824, "cnf": { "jwe": _jwe } } pjwt = PJWT(**jwt) s = pjwt.to_json() de_pjwt = PJWT().from_json(s) assert _eq(de_pjwt.keys(), ['iss', 'aud', 'exp', 'cnf']) assert list(de_pjwt['cnf'].keys()) == ['jwe'] _jwe = de_pjwt['cnf']['jwe'] msg = jwe.decrypt(_jwe, encryption_keys) assert msg assert json.loads(msg.decode('utf8')) == jwk
def request_object_encryption(self, msg, **kwargs): try: encalg = self.behaviour["request_object_encryption_alg"] except KeyError: return msg else: encenc = self.behaviour["request_object_encryption_enc"] _jwe = JWE(msg, alg=encalg, enc=encenc) _kty = jwe.alg2keytype(encalg) try: _kid = kwargs["enc_kid"] except KeyError: try: _kid = self.kid["enc"][_kty] except KeyError: _kid = "" if _kid: _jwe["keys"] = self.keyjar.get_encrypt_key(_kty, kid=_kid) _jwe["kid"] = _kid else: _jwe["keys"] = self.keyjar.get_signing_key(_kty) return _jwe.encrypt(self.keyjar)
def _encrypt_request(self, data): """ Encrypts the input data for the stored api_public_keys :param data: Information to be encrypted :return: JWE formatted string """ jwe = JWE(json.dumps(data), alg=self.jwe_cek_encryption, enc=self.jwe_claims_encryption) return jwe.encrypt(keys=self.api_public_keys)
def _encrypt(self, payload, cty='JWT'): keys = self.keyjar.get_encrypt_key(owner='') kwargs = {"alg": self.enc_alg, "enc": self.enc_enc} if cty: kwargs["cty"] = cty # use the clients public key for encryption _jwe = JWE(payload, **kwargs) return _jwe.encrypt(keys, context="public")
def test_encrypt_decrypt_rsa_cbc(): _key = RSAKey(key=rsa) _key._keytype = "private" _jwe0 = JWE(plain, alg="RSA1_5", enc="A128CBC-HS256") jwt = _jwe0.encrypt([_key]) _jwe1 = JWE() msg = _jwe1.decrypt(jwt, [_key]) assert msg == plain
def handle_metadata_save(self, environ, start_response, qs): """ Takes the input for the page metadata.mako. Encrypts entity id and secret information for the social services. Creates the partial xml to be added to the metadata for the service provider. :param environ: wsgi enviroment :param start_response: wsgi start respons :param qs: Query parameters in a dictionary. :return: wsgi response for the mako file metadatasave.mako. """ resp = Response(mako_template="metadatasave.mako", template_lookup=self.lookup, headers=[]) if "entityId" not in qs or "secret" not in qs: xml = ("Xml could not be generated because no entityId or secret" "has been sent to the service.") _logger.warning(xml) else: try: secret_data = json.dumps({"entityId": json.loads(qs["entityId"]), "secret": json.loads(qs["secret"])}) # create a JWE jwe = JWE(secret_data, alg=self.alg, enc=self.enc) secret_data_encrypted = jwe.encrypt([self.key]) val = AttributeValue() val.set_text(secret_data_encrypted) attr = Attribute( name_format=NAME_FORMAT_URI, name="http://social2saml.nordu.net/customer", attribute_value=[val]) eattr = mdattr.EntityAttributes(attribute=[attr]) nspair = { "mdattr": "urn:oasis:names:tc:SAML:metadata:attribute", "samla": "urn:oasis:names:tc:SAML:2.0:assertion", } xml = eattr.to_string(nspair) xml_list = xml.split("\n", 1) if len(xml_list) == 2: xml = xml_list[1] except Exception: _logger.fatal('Unknown error in handle_metadata_save.', exc_info=True) xml = "Xml could not be generated." argv = { "home": CONST_METADATA, "action": CONST_METADATAVERIFY, "xml": xml } return resp(environ, start_response, **argv)
def to_jwe(self, keys, enc, alg, lev=0): """ :param keys: Dictionary, keys are key type and key is the value :param enc: The encryption method to use :param alg: Encryption algorithm :param lev: Used for JSON construction :return: A JWE """ krs = keyitems2keyreps(keys) _jwe = JWE(self.to_json(lev), alg=alg, enc=enc) return _jwe.encrypt(krs)
def deconstruct_state(relay_state, keys, alg="A128KW", enc="A128CBC-HS256"): """ Deconstruct the SAML RelayState (received back from the IdP). :param relay_state: A JWS :param key: A decryption key (a SYMKey instance) :return: The payload of the JWS """ jwe = JWE(alg=alg, enc=enc) payload, success = jwe.decrypt(relay_state, keys) if success: return json.loads(payload) else: raise DecryptionFailed()
def construct_state(payload, key, alg="A128KW", enc="A128CBC-HS256"): """ Construct the SAML RelayState to send to the IdP. :param payload: A JSON structure :param keys: A SYMKey :param alg: The encryption algorithm :param enc: :return: A JWS """ _jwe = JWE(json.dumps(payload), alg=alg, enc=enc) relay_state = _jwe.encrypt([key]) return relay_state
def to_jwe(self, keys, enc, alg, lev=0): """ Place the information in this instance in a JSON object. Make that JSON object the body of a JWT. Then encrypt that JWT using the specified algorithms and the given keys. Return the encrypted JWT. :param keys: Dictionary, keys are key type and key is the value or simple list. :param enc: Content Encryption Algorithm :param alg: Key Management Algorithm :param lev: Used for JSON construction :return: An encrypted JWT. If encryption failed an exception will be raised. """ if isinstance(keys, dict): keys = keyitems2keyreps(keys) _jwe = JWE(self.to_json(lev), alg=alg, enc=enc) return _jwe.encrypt(keys)
def test_enc_hmac(): payload = {'nonce': 'CYeHPyA6Kmr_jy5HDHXykznu2BpDLm8ngbIJvhBoupI,', 'sub': 'diana', 'iss': 'https://xenosmilus2.umdc.umu.se:8091/', 'acr': '2', 'exp': 1401176001, 'iat': 1401096801, 'aud': ['ApB7TBoKV1tV']} _jwe = JWE(json.dumps(payload), alg="A128KW", enc="A128CBC-HS256") kb = KeyBundle(JWK1["keys"]) kj = KeyJar() kj.issuer_keys["abcdefgh"] = [kb] keys = kj.get_encrypt_key(owner="abcdefgh") _enctxt = _jwe.encrypt(keys, context="public") assert _enctxt # and now for decryption msg, state = _jwe.decrypt(_enctxt, keys) assert json.loads(msg) == payload
def test_pjwt_unpack_jwe(): keys = KEYS() keys.append(RSAKey(use="enc", key=rsa, kid="some-key-id")) pj = PopJWT("https://server.example.com", "https://client.example.org", sub='12345678') jwk = {"kty": "oct", "alg": "HS256", "k": "ZoRSOrFzN_FzUA5XKMYoVHyzff5oRJxl-IXRtztJ6uE"} jwe = JWE(json.dumps(jwk), alg="RSA-OAEP", enc="A256CBC-HS512") _jwe = jwe.encrypt(keys=keys.keys(), kid="some-key-id") pjwt = pj.pack_jwe(jwe=_jwe) s = pjwt.to_json() _jwt = PopJWT(jwe=jwe, keys=keys).unpack(s) assert _eq(_jwt.keys(), ['iss', 'aud', 'exp', 'cnf', 'sub', 'iat']) assert _eq(_jwt['cnf'].keys(), ['jwk', 'jwe']) assert _jwt['cnf']['jwk'] == jwk
def encrypt(self, payload, client_info, cid, val_type="id_token"): """ Handles the encryption of a payload :param payload: The information to be encrypted :param client_info: Client information :param cid: Client id :return: The encrypted information as a JWT """ alg = client_info["%s_encrypted_response_alg" % val_type] try: enc = client_info["%s_encrypted_response_enc" % val_type] except KeyError: enc = "A128CBC" keys = self.keyjar.get_encrypt_key(owner=cid) logger.debug("keys for %s: %s" % (cid, self.keyjar[cid])) logger.debug("alg=%s, enc=%s" % (alg, enc)) logger.debug("Encryption keys for %s: %s" % (cid, keys)) # use the clients public key for encryption _jwe = JWE(payload, alg=alg, enc=enc) return _jwe.encrypt(keys, context="public")
def test_pjwt_with_jwe_jwk(): keys = KEYS() keys.append(RSAKey(use="enc", key=rsa, kid="some-key-id")) jwe = JWE(alg="RSA-OAEP", enc="A256CBC-HS512") pj = PopJWT("https://server.example.com", "https://client.example.org", sub='12345678', jwe=jwe, keys=keys) jwk = {"kty": "oct", "alg": "HS256", "k": "ZoRSOrFzN_FzUA5XKMYoVHyzff5oRJxl-IXRtztJ6uE"} pjwt = pj.pack_jwe(jwk=jwk, kid='some-key-id') s = pjwt.to_json() de_pjwt = PJWT().from_json(s) assert _eq(de_pjwt.keys(), ['iss', 'aud', 'exp', 'cnf', 'sub', 'iat']) assert list(de_pjwt['cnf'].keys()) == ['jwe'] _jwe = de_pjwt['cnf']['jwe'] msg = jwe.decrypt(_jwe, keys.keys()) assert msg assert json.loads(msg.decode('utf8')) == jwk
_key.serialize() keys = [_key] else: print("Needs encryption key", file=sys.stderr) exit() if not args.enc or not args.alg: print("There are no default encryption methods", file=sys.stderr) exit() if args.enc not in SUPPORTED["enc"]: print("Encryption method %s not supported", args.enc, file=sys.stderr) print("Methods supported: %s", SUPPORTED["enc"], file=sys.stderr) exit() if args.alg not in SUPPORTED["alg"]: print("Encryption algorithm %s not supported", args.alg, file=sys.stderr) print("Algorithms supported: %s", SUPPORTED["alg"], file=sys.stderr) exit() if args.file: message = open(args.file).read() elif args.message == "-": message = sys.stdin.read() else: message = args.message jwe = JWE(message, alg=args.alg, enc=args.enc) print(jwe.encrypt(keys))
keys = assign(load_jwks(open(args.jwk_file).read())) if args.mode == "private": print >> sys.stderr, "Missing private key to decrypt with" exit() elif args.x509_url: keys = assign(load_x509_cert(lrequest, args.x509_url)) if args.mode == "private": print >> sys.stderr, "Missing private key to decrypt with" exit() elif args.x509_file: keys = {"rsa": [import_rsa_key_from_file(args.x509_file)]} if args.mode == "private": print >> sys.stderr, "Missing private key to decrypt with" exit() elif args.rsa_file: keys = {"rsa": [rsa_load(args.rsa_file)]} else: print >> sys.stderr, "Needs encryption key" exit() if args.file: msg = open(args.file).read() msg = msg.strip("\n\r") else: msg = args.message krs = keyitems2keyreps(keys) jwe = JWE() print jwe.decrypt(msg, krs)
def from_jwe(self, msg, keys): krs = keyitems2keyreps(keys) jwe = JWE() _res = jwe.decrypt(msg, krs) return self.from_json(_res[0].decode())
def decrypt(msg, keys): _jwe = JWE() return _jwe.decrypt(msg, keys)
def encrypt(msg, keys, alg, enc): _jwe = JWE(msg, alg=alg, enc=enc) return _jwe.encrypt(keys)
def test_rsa_with_kid(): encryption_keys = [RSAKey(use="enc", key=rsa, kid="some-key-id")] jwe = JWE("some content", alg="RSA-OAEP", enc="A256CBC-HS512") jwe.encrypt(keys=encryption_keys, kid="some-key-id")
def request_started_handler(self, sender, **extra): if request.content_type == u'application/jose': jwe = JWE() decrypted = jwe.decrypt(request.get_data(), self._keys) request._cached_data = decrypted request._cached_json = json.loads(decrypted)
def decrypt(content, key): sym_key = SYMKey(key=key, alg="A128KW") return JWE().decrypt(content, keys=[sym_key])
def encrypt(content, key): sym_key = SYMKey(key=key, alg="A128KW") jwe = JWE(content, alg="A128KW", enc="A256GCM") return jwe.encrypt([sym_key])
def decrypt(request): decrypted_content = JWE().decrypt(request, keys=decryption_keys) response = JWS().verify_compact(decrypted_content, keys=verifying_keys) return json.loads(response["payload"])
parser.add_argument("message", nargs="?", help="The message to encrypt") args = parser.parse_args() keys = {} if args.jwk_url: keys = load_jwks_from_url(args.jwk_url) elif args.jwk_file: keys = load_jwks(open(args.jwk_file).read()) elif args.x509_url: keys = load_x509_cert(args.x509_url, {}) elif args.x509_file: keys = [import_rsa_key_from_file(args.x509_file)] elif args.rsa_file: key = rsa_load(args.rsa_file) rsa_key = RSAKey(key=key) rsa_key.serialize() keys = [rsa_key] else: print("Needs encryption key") exit() if args.file: msg = open(args.file).read() msg = msg.strip("\n\r") else: msg = args.message jwe = JWE() print(jwe.decrypt(msg, keys))
if jwt['response']['body_hash'] != body_hash: raise Exception("Unexpected response body_hash") print("REQUEST:") print() method, url, headers, body, jti = _get_request_data() request = Request(method, url, headers, None, body) prepared = request.prepare() response = Session().send(prepared) print() print("RESPONSE:") print() if config.verbose: print(u"HTTP/1.1 {} {}".format(response.status_code, response.reason)) for header in response.headers.items(): print(u'{}: {}'.format(*header)) print(u'\n{}\n'.format(response.content.decode())) _verify_response(response) if response.headers.get('content-type') == 'application/jose': jwe = JWE() decrypted = jwe.decrypt(response.content, enc_keys) decoded = decrypted.decode() print("Decrypted Body:") print(decoded) elif not config.verbose: print(response.text)
def from_jwt(self, txt, key=None, verify=True, keyjar=None, **kwargs): """ Given a signed and/or encrypted JWT, verify its correctness and then create a class instance from the content. :param txt: The JWT :param key: keys that might be used to decrypt and/or verify the signature of the JWT :param verify: Whether the signature should be verified or not :return: A class instance """ if key is None and keyjar is not None: key = keyjar.get_verify_key(owner="") elif key is None: key = {} header = json.loads(b64d(str(txt.split(".")[0]))) logger.debug("header: %s" % (header, )) try: htype = header["typ"] except KeyError: htype = None try: _kid = header["kid"] except KeyError: _kid = "" jso = None if htype == "JWE" or ("alg" in header and "enc" in header): # encrypted if keyjar: dkeys = keyjar.get_decrypt_key(owner="") else: dkeys = {} txt = JWE().decrypt(txt, dkeys) try: jso = json.loads(txt) except Exception: pass # assume htype == 'JWS' _jws = JWS() if not jso: try: jso = jwkest.unpack(txt)[1] if isinstance(jso, basestring): jso = json.loads(jso) if keyjar: if "jku" in header: if not keyjar.find(header["jku"], jso["iss"]): # This is really questionable try: if kwargs["trusting"]: keyjar.add(jso["iss"], header["jku"]) except KeyError: pass if _kid: try: _key = keyjar.get_key_by_kid(_kid, jso["iss"]) if _key: key.append(_key) except KeyError: pass try: self._add_key(keyjar, kwargs["opponent_id"], key) except KeyError: pass if verify: if keyjar: for ent in ["iss", "aud", "client_id"]: if ent not in jso: continue if ent == "aud": # list or basestring if isinstance(jso["aud"], basestring): _aud = [jso["aud"]] else: _aud = jso["aud"] for _e in _aud: self._add_key(keyjar, _e, key) else: self._add_key(keyjar, jso[ent], key) if "alg" in header and header["alg"] != "none": if not key: raise MissingSigningKey("alg=%s" % header["alg"]) _jws.verify_compact(txt, key) except Exception: raise return self.from_dict(jso)
def request_started_handler(self, sender, **extra): if request.content_type == u'application/jose': jwe = JWE() decrypted = jwe.decrypt(request.body, self._keys)
mode = "" else: print >> sys.stderr, "Needs encryption key" exit() if not args.enc or not args.alg: print >> sys.stderr, "There are no default encryption methods" exit() if args.enc not in SUPPORTED["enc"]: print >> sys.stderr, "Encryption method %s not supported" % args.enc print >> sys.stderr, "Methods supported: %s" % SUPPORTED["enc"] exit() if args.alg not in SUPPORTED["alg"]: print >> sys.stderr, "Encryption algorithm %s not supported" % args.alg print >> sys.stderr, "Algorithms supported: %s" % SUPPORTED["alg"] exit() if args.file: message = open(args.file).read() elif args.message == "-": message = sys.stdin.read() else: message = args.message krs = keyitems2keyreps(keys) jwe = JWE(message, alg=args.alg, enc=args.enc) print jwe.encrypt(krs)
_key = RSAKey(key=rsa_load(args.rsa_file)) _key.serialize() keys = [_key] else: print >> sys.stderr, "Needs encryption key" exit() if not args.enc or not args.alg: print >> sys.stderr, "There are no default encryption methods" exit() if args.enc not in SUPPORTED["enc"]: print >> sys.stderr, "Encryption method %s not supported" % args.enc print >> sys.stderr, "Methods supported: %s" % SUPPORTED["enc"] exit() if args.alg not in SUPPORTED["alg"]: print >> sys.stderr, "Encryption algorithm %s not supported" % args.alg print >> sys.stderr, "Algorithms supported: %s" % SUPPORTED["alg"] exit() if args.file: message = open(args.file).read() elif args.message == "-": message = sys.stdin.read() else: message = args.message jwe = JWE(message, alg=args.alg, enc=args.enc) print jwe.encrypt(keys)
def from_jwe(self, msg, keys): krs = keyitems2keyreps(keys) jwe = JWE() _res = jwe.decrypt(msg, krs) return self.from_json(_res[0])
def request_object_encryption(self, msg, **kwargs): try: encalg = kwargs["request_object_encryption_alg"] except KeyError: try: encalg = self.behaviour["request_object_encryption_alg"] except KeyError: return msg try: encenc = kwargs["request_object_encryption_enc"] except KeyError: try: encenc = self.behaviour["request_object_encryption_enc"] except KeyError: raise MissingRequiredAttribute("No request_object_encryption_enc specified") _jwe = JWE(msg, alg=encalg, enc=encenc) _kty = jwe.alg2keytype(encalg) try: _kid = kwargs["enc_kid"] except KeyError: _kid = "" if "target" not in kwargs: raise MissingRequiredAttribute("No target specified") if _kid: _keys = self.keyjar.get_encrypt_key(_kty, owner=kwargs["target"], kid=_kid) _jwe["kid"] = _kid else: _keys = self.keyjar.get_encrypt_key(_kty, owner=kwargs["target"]) return _jwe.encrypt(_keys)