本文整理汇总了Python中jwkest.jwe.JWE类的典型用法代码示例。如果您正苦于以下问题:Python JWE类的具体用法?Python JWE怎么用?Python JWE使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了JWE类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: request_object_encryption
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)
示例2: request_object_encryption
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)
示例3: test_pop_jwe
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
示例4: _encrypt_request
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)
示例5: _encrypt
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")
示例6: test_encrypt_decrypt_rsa_cbc
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
示例7: handle_metadata_save
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)
示例8: to_jwe
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)
示例9: deconstruct_state
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()
示例10: construct_state
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
示例11: to_jwe
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)
示例12: test_enc_hmac
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
示例13: test_pjwt_unpack_jwe
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
示例14: encrypt
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")
示例15: test_pjwt_with_jwe_jwk
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