當前位置: 首頁>>代碼示例>>Python>>正文


Python jwe.JWE類代碼示例

本文整理匯總了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)
開發者ID:joostd,項目名稱:pyoidc,代碼行數:35,代碼來源:__init__.py

示例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)
開發者ID:takehikokodama,項目名稱:pyoidc,代碼行數:25,代碼來源:__init__.py

示例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
開發者ID:Magosgruss,項目名稱:pyoidc,代碼行數:30,代碼來源:test_popjwt.py

示例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)
開發者ID:LaunchKey,項目名稱:launchkey-python,代碼行數:9,代碼來源:jose_auth.py

示例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")
開發者ID:SilentCircle,項目名稱:pyoidc,代碼行數:10,代碼來源:jwt.py

示例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
開發者ID:dv10den,項目名稱:pyjwkest,代碼行數:11,代碼來源:test_2_jwe.py

示例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)
開發者ID:NORDUnet,項目名稱:IdPproxy,代碼行數:54,代碼來源:secret.py

示例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)
開發者ID:StudienprojektUniTrier,項目名稱:Authorization-Server,代碼行數:12,代碼來源:message.py

示例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()
開發者ID:SvHu,項目名稱:svs,代碼行數:14,代碼來源:utils.py

示例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
開發者ID:SvHu,項目名稱:svs,代碼行數:14,代碼來源:utils.py

示例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)
開發者ID:Magosgruss,項目名稱:pyoidc,代碼行數:19,代碼來源:message.py

示例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
開發者ID:dallerbarn,項目名稱:pyoidc,代碼行數:21,代碼來源:test_keyio.py

示例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
開發者ID:Magosgruss,項目名稱:pyoidc,代碼行數:23,代碼來源:test_popjwt.py

示例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")
開發者ID:wayward710,項目名稱:pyoidc,代碼行數:24,代碼來源:provider.py

示例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
開發者ID:Magosgruss,項目名稱:pyoidc,代碼行數:24,代碼來源:test_popjwt.py


注:本文中的jwkest.jwe.JWE類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。