def test_pjwt_with_jwe(): pj = PopJWT("https://server.example.com", "https://client.example.org", sub="12345678") 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") pjwt = pj.pack_jwe(jwe=_jwe) 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, encryption_keys) assert msg assert json.loads(msg.decode("utf8")) == jwk
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 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 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_with_jwe(): pj = PopJWT("https://server.example.com", "https://client.example.org", sub='12345678') 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") pjwt = pj.pack_jwe(jwe=_jwe) 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, encryption_keys) assert msg assert json.loads(msg.decode('utf8')) == jwk
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 request_finished_handler(self, sender, response: Response, **extra): if 200 >= response.status_code < 300 and response.content_type == 'application/json': data = response.get_data(as_text=True) jwe = JWE(data, alg='A256KW', enc='A256CBC-HS512', cty='application/json') encrypted = jwe.encrypt(self._keys, kid=self._keys[0].kid) response.content_type = 'application/jose' response.data = encrypted
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 test_ecdh_no_setup_dynamic_epk(): jwenc = JWE(plain, alg="ECDH-ES", enc="A128GCM") jwt = jwenc.encrypt([remotekey]) assert jwt ret_jwe = factory(jwt) res = ret_jwe.decrypt(jwt, [remotekey]) assert res
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 request_finished_handler(self, sender, response, **extra): if response.content_type == 'application/json': jwe = JWE(str(response.data), alg='A256KW', enc='A256CBC-HS512', cty='application/json') encrypted = jwe.encrypt(self._keys, kid=self._keys[0].kid) response.content_type = 'application/jose' response.data = encrypted
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 _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 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 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 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 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 = factory(jwt) msg = _jwe1.decrypt(jwt, [_key]) assert msg == plain
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 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 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 encrypt(request): jws_request = JWSRequest() jws_request.iss = "https://merchantname.com" jws_request.aud = "https://capitalone.com" jws_request.payload = json.dumps(request, default=lambda x: x.__dict__) jws = JWS(json.dumps(jws_request, default=lambda x: x.__dict__), alg="RS256") signed_content = jws.sign_compact(keys=signing_keys) jwe = JWE(signed_content, alg="RSA-OAEP-256", enc="A256GCM", iat=int(round(time.time() * 1000)), jti=str(uuid.uuid4())) return jwe.encrypt(keys=encryption_keys)
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 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 _get_request_data(): if config.name is None: method = 'GET' body = None headers = dict() print("=== No Request ===") else: method = 'POST' data = json.dumps({'name': config.name}, indent=2) print("Unencrypted Body:") print(data) print() if config.no_encryption: body = data headers = {'content-type': 'application/json'} else: jwe = JWE(data, alg='A256KW', enc='A256CBC-HS512', cty='application/json') body = jwe.encrypt(enc_keys) headers = {'content-type': 'application/jose'} path = '/' jti = None if config.no_nonce else str(uuid1()) if config.no_jwt: headers['Authorization'] = 'Nonce {}'.format(jti) else: jwt = _get_request_token(method, path, body, jti, config.issuer, config.audience) headers['Authorization'] = 'EX-JWT {}'.format(jwt) if config.verbose: print(method, path, "HTTP/1.1") for key, value in headers.items(): print("{}: {}".format(key, value)) if body is not None: print("\n" + body) return method, config.base_url + path, headers, body, jti
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(): pj = PopJWT("https://server.example.com", "https://client.example.org", sub='12345678') 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") pjwt = pj.pack_jwe(jwe=_jwe) 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, encryption_keys) assert msg assert json.loads(msg.decode('utf8')) == jwk
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")
_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 encrypt(msg, keys, alg, enc): _jwe = JWE(msg, alg=alg, enc=enc) return _jwe.encrypt(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)
def encrypt(content, key): sym_key = SYMKey(key=key, alg="A128KW") jwe = JWE(content, alg="A128KW", enc="A256GCM") return jwe.encrypt([sym_key])
def encrypt(msg, keys, alg, enc): _jwe = JWE(msg, alg=alg, enc=enc) return _jwe.encrypt(keys)
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))
_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))
_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 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_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)