예제 #1
0
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
예제 #2
0
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
예제 #3
0
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
예제 #4
0
 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
         cached_json = json.loads(decrypted)
         request._cached_json = (cached_json, cached_json)
예제 #5
0
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
예제 #6
0
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
예제 #7
0
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 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
예제 #9
0
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
예제 #10
0
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
예제 #11
0
 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
예제 #12
0
 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)
예제 #13
0
파일: jwt.py 프로젝트: moisesbonilla/pyoidc
    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")
예제 #14
0
파일: secret.py 프로젝트: dv10den/IdPproxy
    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)
예제 #15
0
    def auth_app(self, app_id, app_secret, auth_code, state=''):
        """
        Authenticate an app

        :param app_id: the app id
        :param app_secret: the app secret
        :param auth_code: the app auth code
        """
        headers = {'Content-type': 'application/json'}
        payload = {
            'application': app_id,
            'auth_code': auth_code,
            'state': state
        }
        try:
            full_url = utils.urljoin(self.host,
                                     '/api/v1/application-tokens/validate')
            response = requests.post(full_url,
                                     data=json.dumps(payload),
                                     headers=headers,
                                     verify=self.tls_verify)
        except RequestException:
            raise exceptions.TaigaRestException(full_url, 400, 'NETWORK ERROR',
                                                'POST')
        if response.status_code != 200:
            raise exceptions.TaigaRestException(full_url, response.status_code,
                                                response.text, 'POST')
        cyphered_token = response.json().get('cyphered_token', '')
        if cyphered_token:
            from jwkest.jwk import SYMKey
            from jwkest.jwe import JWE

            sym_key = SYMKey(key=app_secret, alg='A128KW')
            data, success = JWE().decrypt(cyphered_token, keys=[sym_key]), True
            if isinstance(data, tuple):
                data, success = data
            try:
                self.token = json.loads(data.decode('utf-8')).get(
                    'token', None)
            except ValueError:  # pragma: no cover
                self.token = None
            if not success:
                self.token = None
        else:
            self.token = None

        if self.token is None:
            raise exceptions.TaigaRestException(full_url, 400, 'INVALID TOKEN',
                                                'POST')

        self.raw_request = RequestMaker('/api/v1', self.host, self.token,
                                        'Application', self.tls_verify)
        self._init_resources()
예제 #16
0
    def auth_app(self, app_id, app_secret, auth_code, state=""):
        """
        Authenticate an app

        :param app_id: the app id
        :param app_secret: the app secret
        :param auth_code: the app auth code
        """
        headers = {"Content-type": "application/json"}
        payload = {
            "application": app_id,
            "auth_code": auth_code,
            "state": state
        }
        try:
            full_url = utils.urljoin(self.host,
                                     "/api/v1/application-tokens/validate")
            response = requests.post(full_url,
                                     data=json.dumps(payload),
                                     headers=headers,
                                     verify=self.tls_verify)
        except RequestException:
            raise exceptions.TaigaRestException(full_url, 400, "NETWORK ERROR",
                                                "POST")
        if response.status_code != 200:
            raise exceptions.TaigaRestException(full_url, response.status_code,
                                                response.text, "POST")
        cyphered_token = response.json().get("cyphered_token", "")
        if cyphered_token:
            from jwkest.jwe import JWE
            from jwkest.jwk import SYMKey

            sym_key = SYMKey(key=app_secret, alg="A128KW")
            data, success = JWE().decrypt(cyphered_token, keys=[sym_key]), True
            if isinstance(data, tuple):
                data, success = data
            try:
                self.token = json.loads(data.decode("utf-8")).get(
                    "token", None)
            except ValueError:  # pragma: no cover
                self.token = None
            if not success:
                self.token = None
        else:
            self.token = None

        if self.token is None:
            raise exceptions.TaigaRestException(full_url, 400, "INVALID TOKEN",
                                                "POST")

        self.raw_request = RequestMaker("/api/v1", self.host, self.token,
                                        "Application", self.tls_verify)
        self._init_resources()
예제 #17
0
    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)
예제 #18
0
 def decrypt_response(self, response):
     """
     Decrypts a response using the stored issuer private keys
     :param response: JWE encrypted string
     :return: Decrypted string
     """
     package = JWEnc().unpack(response)
     keys = list(self.issuer_private_keys)
     if 'kid' in package.headers:
         for key in self.issuer_private_keys:
             if key.kid == package.headers['kid']:
                 keys = [key]
     return JWE().decrypt(response, keys=keys).decode('utf-8')
예제 #19
0
    def from_jwe(self, msg, keys):
        """
        Decrypt an encrypted JWT and load the JSON object that was the body of the JWT into this object.

        :param msg: An encrypted JWT
        :param keys: Dictionary, keys are key type and key is the value or simple list.
        :return: The decrypted message. If decryption failed an exception will be raised.
        """
        if isinstance(keys, dict):
            keys = keyitems2keyreps(keys)

        jwe = JWE()
        _res = jwe.decrypt(msg, keys)
        return self.from_json(_res.decode())
예제 #20
0
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)
예제 #21
0
    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)
예제 #22
0
    def __call__(self):
        res = {}
        jwe = JWE()

        for entid, item in self.metad.items():
            if "spsso_descriptor" not in item:
                continue

            for sp in item["spsso_descriptor"]:
                if "extensions" not in sp:
                    continue

                for elem in sp["extensions"]["extension_elements"]:
                    if elem["__class__"] == ENTITY_ATTR:
                        for attr in elem["attribute"]:
                            if attr["name"] == ATTR_NAME:
                                for val in attr["attribute_value"]:
                                    res[entid] = self.decrypt_client_secrets(
                                        jwe, val, entid)
        self.ava.update(res)
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
예제 #24
0
    parser.add_argument("message", nargs="?", help="The message to encrypt")

    args = parser.parse_args()

    keys = {}
    if args.jwk_url:
        keys = assign(load_jwks_from_url(lrequest, args.jwk_url))
    elif args.jwk_file:
        keys = load_jwks(open(args.jwk_file).read())
    elif args.x509_url:
        keys = load_x509_cert(lrequest, 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))
예제 #25
0
        _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)
예제 #26
0
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")
예제 #27
0
 def from_jwe(self, msg, keys):
     krs = keyitems2keyreps(keys)
     jwe = JWE()
     _res = jwe.decrypt(msg, krs)
     return self.from_json(_res[0].decode())
예제 #28
0
def decrypt(msg, keys):
    _jwe = JWE()
    return _jwe.decrypt(msg, keys)
예제 #29
0
def encrypt(msg, keys, alg, enc):
    _jwe = JWE(msg, alg=alg, enc=enc)
    return _jwe.encrypt(keys)
    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)