コード例 #1
0
    def encode(self, header, payload, key):
        """Encode a JWS with the given header, payload and key.

        :param header: A dict of JWS header
        :param payload: text/dict to be encoded
        :param key: key used to sign the signature
        :return: JWS text
        """
        if 'alg' not in header:
            raise MissingAlgorithmError()

        alg = header['alg']
        if alg not in self._algorithms:
            raise UnsupportedAlgorithmError()

        algorithm = self._algorithms[alg]

        if self.load_key:
            key = self.load_key(key, header)

        key = algorithm.prepare_sign_key(key)

        header = json.dumps(header, separators=(',', ':'))
        if isinstance(payload, Mapping):
            payload = json.dumps(payload, separators=(',', ':'))

        segments = [
            urlsafe_b64encode(to_bytes(header)),
            urlsafe_b64encode(to_bytes(payload)),
        ]
        signing_input = b'.'.join(segments)
        signature = urlsafe_b64encode(algorithm.sign(signing_input, key))
        return b'.'.join([signing_input, signature])
コード例 #2
0
    def serialize_compact(self, protected, payload, key):
        """Generate a JWS Compact Serialization. The JWS Compact Serialization
        represents digitally signed or MACed content as a compact, URL-safe
        string, per `Section 7.1`_.

        .. code-block:: text

            BASE64URL(UTF8(JWS Protected Header)) || '.' ||
            BASE64URL(JWS Payload) || '.' ||
            BASE64URL(JWS Signature)

        :param protected: A dict of protected header
        :param payload: A bytes/string of payload
        :param key: Private key used to generate signature
        :return: byte
        """
        jws_header = JWSHeader(protected, None)
        self._validate_private_headers(protected)
        algorithm, key = self._prepare_algorithm_key(protected, payload, key)

        protected_segment = json_b64encode(jws_header.protected)
        payload_segment = urlsafe_b64encode(to_bytes(payload))

        # calculate signature
        signing_input = b'.'.join([protected_segment, payload_segment])
        signature = urlsafe_b64encode(algorithm.sign(signing_input, key))
        return b'.'.join([protected_segment, payload_segment, signature])
コード例 #3
0
    def serialize_compact(self, protected, payload, key):
        """Generate a JWE Compact Serialization. The JWE Compact Serialization
        represents encrypted content as a compact, URL-safe string.  This
        string is:

            BASE64URL(UTF8(JWE Protected Header)) || '.' ||
            BASE64URL(JWE Encrypted Key) || '.' ||
            BASE64URL(JWE Initialization Vector) || '.' ||
            BASE64URL(JWE Ciphertext) || '.' ||
            BASE64URL(JWE Authentication Tag)

        Only one recipient is supported by the JWE Compact Serialization and
        it provides no syntax to represent JWE Shared Unprotected Header, JWE
        Per-Recipient Unprotected Header, or JWE AAD values.

        :param protected: A dict of protected header
        :param payload: A string/dict of payload
        :param key: Private key used to generate signature
        :return: byte
        """
        self._pre_validate_header(protected)
        # step 1: Prepare algorithms
        algorithm, enc_alg, key = self._prepare_alg_enc_key(protected, key)
        self._post_validate_header(protected, algorithm)

        # step 2: Generate a random Content Encryption Key (CEK)
        cek = enc_alg.generate_cek()

        # step 3: Encrypt the CEK with the recipient's public key
        ek = algorithm.wrap(cek, protected, key)
        if isinstance(ek, dict):
            # AESGCMKW algorithm contains iv, tag in header
            header = ek.get('header')
            if header:
                protected.update(header)
            ek = ek.get('ek')

        # step 4: Generate a random JWE Initialization Vector
        iv = enc_alg.generate_iv()

        # step 5: Let the Additional Authenticated Data encryption parameter
        # be ASCII(BASE64URL(UTF8(JWE Protected Header)))
        protected_segment = json_b64encode(protected)
        aad = to_bytes(protected_segment, 'ascii')

        # step 6: compress message if required
        msg = self._zip_compress(payload, protected)

        # step 7: perform encryption
        ciphertext, tag = enc_alg.encrypt(msg, aad, iv, cek)
        return b'.'.join([
            protected_segment,
            urlsafe_b64encode(ek),
            urlsafe_b64encode(iv),
            urlsafe_b64encode(ciphertext),
            urlsafe_b64encode(tag)
        ])
コード例 #4
0
ファイル: test_jwe.py プロジェクト: josven/authlib
 def test_ecdh_key_agreement_computation(self):
     # https://tools.ietf.org/html/rfc7518#appendix-C
     jwe = JsonWebEncryption(algorithms=JWE_ALGORITHMS)
     alice_key = {
         "kty": "EC",
         "crv": "P-256",
         "x": "gI0GAILBdu7T53akrFmMyGcsF3n5dO7MmwNBHKW5SV0",
         "y": "SLW_xSffzlPWrHEVI30DHM_4egVwt3NQqeUD7nMFpps",
         "d": "0_NxaRPUMQoAJt50Gz8YiTr8gRTwyEaCumd-MToTmIo"
     }
     bob_key = {
         "kty": "EC",
         "crv": "P-256",
         "x": "weNJy2HscCSM6AEDTDg04biOvhFhyyWvOHQfeF_PxMQ",
         "y": "e8lnCO-AlStT-NJVX-crhB7QRYhiix03illJOVAOyck",
         "d": "VEmDZpDXXK8p8N0Cndsxs924q6nS1RXFASRl6BfUqdw"
     }
     headers = {
         "alg": "ECDH-ES",
         "enc": "A128GCM",
         "apu": "QWxpY2U",
         "apv": "Qm9i",
     }
     alg = jwe._alg_algorithms['ECDH-ES']
     key = alg.prepare_key(alice_key)
     bob_key = alg.prepare_key(bob_key)
     public_key = bob_key.get_op_key('wrapKey')
     dk = alg.deliver(key, public_key, headers, 128)
     self.assertEqual(urlsafe_b64encode(dk), b'VqqN6vgjbSBcIijNcacQGg')
コード例 #5
0
 def dumps_private_key(self):
     obj = self.dumps_public_key(self.private_key.public_key())
     d_bytes = self.private_key.private_bytes(Encoding.Raw,
                                              PrivateFormat.Raw,
                                              NoEncryption())
     obj['d'] = to_unicode(urlsafe_b64encode(d_bytes))
     return obj
コード例 #6
0
ファイル: okp_key.py プロジェクト: azmeuk/authlib
 def dumps_public_key(self, public_key=None):
     if public_key is None:
         public_key = self.public_key
     x_bytes = public_key.public_bytes(Encoding.Raw, PublicFormat.Raw)
     return {
         'crv': self.get_key_curve(public_key),
         'x': to_unicode(urlsafe_b64encode(x_bytes)),
     }
コード例 #7
0
ファイル: util.py プロジェクト: Jay-Shah10/FSND-catalog
def create_half_hash(s, alg):
    hash_type = 'sha{}'.format(alg[2:])
    hash_alg = getattr(hashlib, hash_type, None)
    if not hash_alg:
        return None
    data_digest = hash_alg(to_bytes(s)).digest()
    slice_index = int(len(data_digest) / 2)
    return urlsafe_b64encode(data_digest[:slice_index])
コード例 #8
0
    def wrap(self, cek, headers, key):
        self._check_key(key)

        #: https://tools.ietf.org/html/rfc7518#section-4.7.1.1
        #: The "iv" (initialization vector) Header Parameter value is the
        #: base64url-encoded representation of the 96-bit IV value
        iv_size = 96
        iv = os.urandom(iv_size // 8)

        cipher = Cipher(AES(key), GCM(iv), backend=default_backend())
        enc = cipher.encryptor()
        ek = enc.update(cek) + enc.finalize()

        h = {
            'iv': to_native(urlsafe_b64encode(iv)),
            'tag': to_native(urlsafe_b64encode(enc.tag))
        }
        return {'ek': ek, 'header': h}
コード例 #9
0
ファイル: jws.py プロジェクト: yoophi/authlib
    def _sign_signature(self, header, payload, key, payload_segment=None):
        self._validate_header(header)
        algorithm, key = self._prepare_algorithm_key(header, payload, key)
        key = algorithm.prepare_sign_key(key)

        protected = _b64encode_json(header)
        if payload_segment is None:
            payload_segment = _b64encode_json(payload)
        signing_input = b'.'.join([protected, payload_segment])
        signature = urlsafe_b64encode(algorithm.sign(signing_input, key))
        return protected, payload_segment, signature
コード例 #10
0
    def thumbprint(self):
        """Implementation of RFC7638 JSON Web Key (JWK) Thumbprint."""
        fields = list(self.REQUIRED_JSON_FIELDS)
        fields.append('kty')
        fields.sort()
        data = OrderedDict()

        for k in fields:
            data[k] = self.tokens[k]

        json_data = json_dumps(data)
        digest_data = hashlib.sha256(to_bytes(json_data)).digest()
        return to_unicode(urlsafe_b64encode(digest_data))
コード例 #11
0
ファイル: jwe_algs.py プロジェクト: azmeuk/authlib
    def wrap(self, enc_alg, headers, key, preset=None):
        if preset and 'cek' in preset:
            cek = preset['cek']
        else:
            cek = enc_alg.generate_cek()

        op_key = key.get_op_key('wrapKey')
        self._check_key(op_key)

        #: https://tools.ietf.org/html/rfc7518#section-4.7.1.1
        #: The "iv" (initialization vector) Header Parameter value is the
        #: base64url-encoded representation of the 96-bit IV value
        iv_size = 96
        iv = os.urandom(iv_size // 8)

        cipher = Cipher(AES(op_key), GCM(iv), backend=default_backend())
        enc = cipher.encryptor()
        ek = enc.update(cek) + enc.finalize()

        h = {
            'iv': to_native(urlsafe_b64encode(iv)),
            'tag': to_native(urlsafe_b64encode(enc.tag))
        }
        return {'ek': ek, 'cek': cek, 'header': h}
コード例 #12
0
        def _sign(jws_header):
            self._validate_private_headers(jws_header)
            _alg, _key = self._prepare_algorithm_key(jws_header, payload, key)

            protected_segment = json_b64encode(jws_header.protected)
            signing_input = b'.'.join([protected_segment, payload_segment])
            signature = urlsafe_b64encode(_alg.sign(signing_input, _key))

            rv = {
                'protected': to_unicode(protected_segment),
                'signature': to_unicode(signature)
            }
            if jws_header.header is not None:
                rv['header'] = jws_header.header
            return rv
コード例 #13
0
ファイル: oct_key.py プロジェクト: johnjdailey/authlib
    def import_key(cls, raw, options=None):
        if isinstance(raw, dict):
            cls.check_required_fields(raw)
            payload = raw
            raw_key = urlsafe_b64decode(to_bytes(payload['k']))
        else:
            raw_key = to_bytes(raw)
            k = to_unicode(urlsafe_b64encode(raw_key))
            payload = {'k': k}

        if options is not None:
            payload.update(options)

        obj = cls(payload)
        obj.raw_key = raw_key
        obj.key_type = 'secret'
        return obj
コード例 #14
0
ファイル: okp_key.py プロジェクト: johnjdailey/authlib
 def dumps_public_key(raw_key):
     x_bytes = raw_key.public_bytes(Encoding.Raw, PublicFormat.Raw)
     return {
         'crv': OKPKey.get_key_curve(raw_key),
         'x': to_unicode(urlsafe_b64encode(x_bytes)),
     }
コード例 #15
0
ファイル: jws.py プロジェクト: yoophi/authlib
def _b64encode_json(text):
    if isinstance(text, dict):
        text = json.dumps(text, separators=(',', ':'))
    return urlsafe_b64encode(to_bytes(text))
コード例 #16
0
 def dumps(self, key):
     return {
         'k': to_unicode(urlsafe_b64encode(key)),
         'kty': 'oct'
     }
コード例 #17
0
ファイル: jwe.py プロジェクト: azmeuk/authlib
    def serialize_compact(self, protected, payload, key, sender_key=None):
        """Generate a JWE Compact Serialization.

        The JWE Compact Serialization represents encrypted content as a compact,
        URL-safe string. This string is::

            BASE64URL(UTF8(JWE Protected Header)) || '.' ||
            BASE64URL(JWE Encrypted Key) || '.' ||
            BASE64URL(JWE Initialization Vector) || '.' ||
            BASE64URL(JWE Ciphertext) || '.' ||
            BASE64URL(JWE Authentication Tag)

        Only one recipient is supported by the JWE Compact Serialization and
        it provides no syntax to represent JWE Shared Unprotected Header, JWE
        Per-Recipient Unprotected Header, or JWE AAD values.

        :param protected: A dict of protected header
        :param payload: Payload (bytes or a value convertible to bytes)
        :param key: Public key used to encrypt payload
        :param sender_key: Sender's private key in case
            JWEAlgorithmWithTagAwareKeyAgreement is used
        :return: JWE compact serialization as bytes
        """

        # step 1: Prepare algorithms & key
        alg = self.get_header_alg(protected)
        enc = self.get_header_enc(protected)
        zip_alg = self.get_header_zip(protected)

        self._validate_sender_key(sender_key, alg)
        self._validate_private_headers(protected, alg)

        key = prepare_key(alg, protected, key)
        if sender_key is not None:
            sender_key = alg.prepare_key(sender_key)

        # self._post_validate_header(protected, algorithm)

        # step 2: Generate a random Content Encryption Key (CEK)
        # use enc_alg.generate_cek() in scope of upcoming .wrap or .generate_keys_and_prepare_headers call

        # step 3: Encrypt the CEK with the recipient's public key
        if isinstance(alg, JWEAlgorithmWithTagAwareKeyAgreement) and alg.key_size is not None:
            # For a JWE algorithm with tag-aware key agreement in case key agreement with key wrapping mode is used:
            # Defer key agreement with key wrapping until authentication tag is computed
            prep = alg.generate_keys_and_prepare_headers(enc, key, sender_key)
            epk = prep['epk']
            cek = prep['cek']
            protected.update(prep['header'])
        else:
            # In any other case:
            # Keep the normal steps order defined by RFC 7516
            if isinstance(alg, JWEAlgorithmWithTagAwareKeyAgreement):
                wrapped = alg.wrap(enc, protected, key, sender_key)
            else:
                wrapped = alg.wrap(enc, protected, key)
            cek = wrapped['cek']
            ek = wrapped['ek']
            if 'header' in wrapped:
                protected.update(wrapped['header'])

        # step 4: Generate a random JWE Initialization Vector
        iv = enc.generate_iv()

        # step 5: Let the Additional Authenticated Data encryption parameter
        # be ASCII(BASE64URL(UTF8(JWE Protected Header)))
        protected_segment = json_b64encode(protected)
        aad = to_bytes(protected_segment, 'ascii')

        # step 6: compress message if required
        if zip_alg:
            msg = zip_alg.compress(to_bytes(payload))
        else:
            msg = to_bytes(payload)

        # step 7: perform encryption
        ciphertext, tag = enc.encrypt(msg, aad, iv, cek)

        if isinstance(alg, JWEAlgorithmWithTagAwareKeyAgreement) and alg.key_size is not None:
            # For a JWE algorithm with tag-aware key agreement in case key agreement with key wrapping mode is used:
            # Perform key agreement with key wrapping deferred at step 3
            wrapped = alg.agree_upon_key_and_wrap_cek(enc, protected, key, sender_key, epk, cek, tag)
            ek = wrapped['ek']

        # step 8: build resulting message
        return b'.'.join([
            protected_segment,
            urlsafe_b64encode(ek),
            urlsafe_b64encode(iv),
            urlsafe_b64encode(ciphertext),
            urlsafe_b64encode(tag)
        ])
コード例 #18
0
ファイル: jwe.py プロジェクト: azmeuk/authlib
    def serialize_json(self, header_obj, payload, keys, sender_key=None):
        """Generate a JWE JSON Serialization (in fully general syntax).

        The JWE JSON Serialization represents encrypted content as a JSON
        object.  This representation is neither optimized for compactness nor
        URL safe.

        The following members are defined for use in top-level JSON objects
        used for the fully general JWE JSON Serialization syntax:

        protected
            The "protected" member MUST be present and contain the value
            BASE64URL(UTF8(JWE Protected Header)) when the JWE Protected
            Header value is non-empty; otherwise, it MUST be absent.  These
            Header Parameter values are integrity protected.

        unprotected
            The "unprotected" member MUST be present and contain the value JWE
            Shared Unprotected Header when the JWE Shared Unprotected Header
            value is non-empty; otherwise, it MUST be absent.  This value is
            represented as an unencoded JSON object, rather than as a string.
            These Header Parameter values are not integrity protected.

        iv
            The "iv" member MUST be present and contain the value
            BASE64URL(JWE Initialization Vector) when the JWE Initialization
            Vector value is non-empty; otherwise, it MUST be absent.

        aad
            The "aad" member MUST be present and contain the value
            BASE64URL(JWE AAD)) when the JWE AAD value is non-empty;
            otherwise, it MUST be absent.  A JWE AAD value can be included to
            supply a base64url-encoded value to be integrity protected but not
            encrypted.

        ciphertext
            The "ciphertext" member MUST be present and contain the value
            BASE64URL(JWE Ciphertext).

        tag
            The "tag" member MUST be present and contain the value
            BASE64URL(JWE Authentication Tag) when the JWE Authentication Tag
            value is non-empty; otherwise, it MUST be absent.

        recipients
            The "recipients" member value MUST be an array of JSON objects.
            Each object contains information specific to a single recipient.
            This member MUST be present with exactly one array element per
            recipient, even if some or all of the array element values are the
            empty JSON object "{}" (which can happen when all Header Parameter
            values are shared between all recipients and when no encrypted key
            is used, such as when doing Direct Encryption).

        The following members are defined for use in the JSON objects that
        are elements of the "recipients" array:

        header
            The "header" member MUST be present and contain the value JWE Per-
            Recipient Unprotected Header when the JWE Per-Recipient
            Unprotected Header value is non-empty; otherwise, it MUST be
            absent.  This value is represented as an unencoded JSON object,
            rather than as a string.  These Header Parameter values are not
            integrity protected.

        encrypted_key
            The "encrypted_key" member MUST be present and contain the value
            BASE64URL(JWE Encrypted Key) when the JWE Encrypted Key value is
            non-empty; otherwise, it MUST be absent.

        This implementation assumes that "alg" and "enc" header fields are
        contained in the protected or shared unprotected header.

        :param header_obj: A dict of headers (in addition optionally contains JWE AAD)
        :param payload: Payload (bytes or a value convertible to bytes)
        :param keys: Public keys (or a single public key) used to encrypt payload
        :param sender_key: Sender's private key in case
            JWEAlgorithmWithTagAwareKeyAgreement is used
        :return: JWE JSON serialization (in fully general syntax) as dict

        Example of `header_obj`::

            {
                "protected": {
                    "alg": "ECDH-1PU+A128KW",
                    "enc": "A256CBC-HS512",
                    "apu": "QWxpY2U",
                    "apv": "Qm9iIGFuZCBDaGFybGll"
                },
                "unprotected": {
                    "jku": "https://alice.example.com/keys.jwks"
                },
                "recipients": [
                    {
                        "header": {
                            "kid": "bob-key-2"
                        }
                    },
                    {
                        "header": {
                            "kid": "2021-05-06"
                        }
                    }
                ],
                "aad": b'Authenticate me too.'
            }
        """
        if not isinstance(keys, list):  # single key
            keys = [keys]

        if not keys:
            raise ValueError("No keys have been provided")

        header_obj = deepcopy(header_obj)

        shared_header = JWESharedHeader.from_dict(header_obj)

        recipients = header_obj.get('recipients')
        if recipients is None:
            recipients = [{} for _ in keys]
        for i in range(len(recipients)):
            if recipients[i] is None:
                recipients[i] = {}
            if 'header' not in recipients[i]:
                recipients[i]['header'] = {}

        jwe_aad = header_obj.get('aad')

        if len(keys) != len(recipients):
            raise ValueError("Count of recipient keys {} does not equal to count of recipients {}"
                             .format(len(keys), len(recipients)))

        # step 1: Prepare algorithms & key
        alg = self.get_header_alg(shared_header)
        enc = self.get_header_enc(shared_header)
        zip_alg = self.get_header_zip(shared_header)

        self._validate_sender_key(sender_key, alg)
        self._validate_private_headers(shared_header, alg)
        for recipient in recipients:
            self._validate_private_headers(recipient['header'], alg)

        for i in range(len(keys)):
            keys[i] = prepare_key(alg, recipients[i]['header'], keys[i])
        if sender_key is not None:
            sender_key = alg.prepare_key(sender_key)

        # self._post_validate_header(protected, algorithm)

        # step 2: Generate a random Content Encryption Key (CEK)
        # use enc_alg.generate_cek() in scope of upcoming .wrap or .generate_keys_and_prepare_headers call

        # step 3: Encrypt the CEK with the recipient's public key
        preset = alg.generate_preset(enc, keys[0])
        if 'cek' in preset:
            cek = preset['cek']
        else:
            cek = None
        if len(keys) > 1 and cek is None:
            raise InvalidAlgorithmForMultipleRecipientsMode(alg.name)
        if 'header' in preset:
            shared_header.update_protected(preset['header'])

        if isinstance(alg, JWEAlgorithmWithTagAwareKeyAgreement) and alg.key_size is not None:
            # For a JWE algorithm with tag-aware key agreement in case key agreement with key wrapping mode is used:
            # Defer key agreement with key wrapping until authentication tag is computed
            epks = []
            for i in range(len(keys)):
                prep = alg.generate_keys_and_prepare_headers(enc, keys[i], sender_key, preset)
                if cek is None:
                    cek = prep['cek']
                epks.append(prep['epk'])
                recipients[i]['header'].update(prep['header'])
        else:
            # In any other case:
            # Keep the normal steps order defined by RFC 7516
            for i in range(len(keys)):
                if isinstance(alg, JWEAlgorithmWithTagAwareKeyAgreement):
                    wrapped = alg.wrap(enc, shared_header, keys[i], sender_key, preset)
                else:
                    wrapped = alg.wrap(enc, shared_header, keys[i], preset)
                if cek is None:
                    cek = wrapped['cek']
                recipients[i]['encrypted_key'] = wrapped['ek']
                if 'header' in wrapped:
                    recipients[i]['header'].update(wrapped['header'])

        # step 4: Generate a random JWE Initialization Vector
        iv = enc.generate_iv()

        # step 5: Compute the Encoded Protected Header value
        # BASE64URL(UTF8(JWE Protected Header)). If the JWE Protected Header
        # is not present, let this value be the empty string.
        # Let the Additional Authenticated Data encryption parameter be
        # ASCII(Encoded Protected Header). However, if a JWE AAD value is
        # present, instead let the Additional Authenticated Data encryption
        # parameter be ASCII(Encoded Protected Header || '.' || BASE64URL(JWE AAD)).
        aad = json_b64encode(shared_header.protected) if shared_header.protected else b''
        if jwe_aad is not None:
           aad += b'.' + urlsafe_b64encode(jwe_aad)
        aad = to_bytes(aad, 'ascii')

        # step 6: compress message if required
        if zip_alg:
            msg = zip_alg.compress(to_bytes(payload))
        else:
            msg = to_bytes(payload)

        # step 7: perform encryption
        ciphertext, tag = enc.encrypt(msg, aad, iv, cek)

        if isinstance(alg, JWEAlgorithmWithTagAwareKeyAgreement) and alg.key_size is not None:
            # For a JWE algorithm with tag-aware key agreement in case key agreement with key wrapping mode is used:
            # Perform key agreement with key wrapping deferred at step 3
            for i in range(len(keys)):
                wrapped = alg.agree_upon_key_and_wrap_cek(enc, shared_header, keys[i], sender_key, epks[i], cek, tag)
                recipients[i]['encrypted_key'] = wrapped['ek']

        # step 8: build resulting message
        obj = OrderedDict()

        if shared_header.protected:
            obj['protected'] = to_unicode(json_b64encode(shared_header.protected))

        if shared_header.unprotected:
            obj['unprotected'] = shared_header.unprotected

        for recipient in recipients:
            if not recipient['header']:
                del recipient['header']
            recipient['encrypted_key'] = to_unicode(urlsafe_b64encode(recipient['encrypted_key']))
            for member in set(recipient.keys()):
                if member not in {'header', 'encrypted_key'}:
                    del recipient[member]
        obj['recipients'] = recipients

        if jwe_aad is not None:
            obj['aad'] = to_unicode(urlsafe_b64encode(jwe_aad))

        obj['iv'] = to_unicode(urlsafe_b64encode(iv))

        obj['ciphertext'] = to_unicode(urlsafe_b64encode(ciphertext))

        obj['tag'] = to_unicode(urlsafe_b64encode(tag))

        return obj
コード例 #19
0
ファイル: _jwk_cryptography.py プロジェクト: vepry/authlib
 def dumps_private_key(key):
     obj = OKPAlgorithm.dumps_public_key(key.public_key())
     d_bytes = key.private_bytes(Encoding.Raw, PrivateFormat.Raw,
                                 NoEncryption())
     obj['d'] = to_unicode(urlsafe_b64encode(d_bytes))
     return obj
コード例 #20
0
ファイル: _jwk_cryptography.py プロジェクト: vepry/authlib
 def dumps_public_key(key):
     x_bytes = key.public_bytes(Encoding.Raw, PublicFormat.Raw)
     return {'x': to_unicode(urlsafe_b64encode(x_bytes))}
コード例 #21
0
ファイル: challenge.py プロジェクト: Jay-Shah10/FSND-catalog
def create_s256_code_challenge(code_verifier):
    """Create S256 code_challenge with the given code_verifier."""
    data = hashlib.sha256(to_bytes(code_verifier, 'ascii')).digest()
    return to_unicode(urlsafe_b64encode(data))
コード例 #22
0
 def jwt_encode(d: dict) -> str:
     from authlib.common.encoding import json_dumps, urlsafe_b64encode
     return urlsafe_b64encode(json_dumps(d).encode('ascii')).decode('ascii')
コード例 #23
0
 def dumps(self, s):
     return {'k': to_unicode(urlsafe_b64encode(to_bytes(s))), 'kty': 'oct'}
コード例 #24
0
ファイル: oct_key.py プロジェクト: imfht/flaskapps
 def load_dict_key(self):
     k = to_unicode(urlsafe_b64encode(self.raw_key))
     self._dict_data = {'kty': self.kty, 'k': k}
コード例 #25
0
    def serialize_compact(self, protected, payload, key):
        """Generate a JWE Compact Serialization. The JWE Compact Serialization
        represents encrypted content as a compact, URL-safe string.  This
        string is:

            BASE64URL(UTF8(JWE Protected Header)) || '.' ||
            BASE64URL(JWE Encrypted Key) || '.' ||
            BASE64URL(JWE Initialization Vector) || '.' ||
            BASE64URL(JWE Ciphertext) || '.' ||
            BASE64URL(JWE Authentication Tag)

        Only one recipient is supported by the JWE Compact Serialization and
        it provides no syntax to represent JWE Shared Unprotected Header, JWE
        Per-Recipient Unprotected Header, or JWE AAD values.

        :param protected: A dict of protected header
        :param payload: A string/dict of payload
        :param key: Private key used to generate signature
        :return: byte
        """

        # step 1: Prepare algorithms & key
        alg = self.get_header_alg(protected)
        enc = self.get_header_enc(protected)
        zip_alg = self.get_header_zip(protected)
        self._validate_private_headers(protected, alg)

        key = prepare_key(alg, protected, key)

        # self._post_validate_header(protected, algorithm)

        # step 2: Generate a random Content Encryption Key (CEK)
        # use enc_alg.generate_cek() in .wrap method

        # step 3: Encrypt the CEK with the recipient's public key
        wrapped = alg.wrap(enc, protected, key)
        cek = wrapped['cek']
        ek = wrapped['ek']
        if 'header' in wrapped:
            protected.update(wrapped['header'])

        # step 4: Generate a random JWE Initialization Vector
        iv = enc.generate_iv()

        # step 5: Let the Additional Authenticated Data encryption parameter
        # be ASCII(BASE64URL(UTF8(JWE Protected Header)))
        protected_segment = json_b64encode(protected)
        aad = to_bytes(protected_segment, 'ascii')

        # step 6: compress message if required
        if zip_alg:
            msg = zip_alg.compress(to_bytes(payload))
        else:
            msg = to_bytes(payload)

        # step 7: perform encryption
        ciphertext, tag = enc.encrypt(msg, aad, iv, cek)
        return b'.'.join([
            protected_segment,
            urlsafe_b64encode(ek),
            urlsafe_b64encode(iv),
            urlsafe_b64encode(ciphertext),
            urlsafe_b64encode(tag)
        ])