def encrypt(claims, jwk, adata='', add_header=None, alg='RSA-OAEP', enc='A128CBC-HS256', rng=get_random_bytes, compression=None): """ Encrypts the given claims and produces a :class:`~jose.JWE` :param claims: A `dict` representing the claims for this :class:`~jose.JWE`. :param jwk: A `dict` representing the JWK to be used for encryption of the CEK. This parameter is algorithm-specific. :param adata: Arbitrary string data to add to the authentication (i.e. HMAC). The same data must be provided during decryption. :param add_header: Additional items to be added to the header. Additional headers *will* be authenticated. :param alg: The algorithm to use for CEK encryption :param enc: The algorithm to use for claims encryption :param rng: Random number generator. A string of random bytes is expected as output. :param compression: The compression algorithm to use. Currently supports `'DEF'`. :rtype: :class:`~jose.JWE` """ header = dict((add_header or {}).items() + [('enc', enc), ('alg', alg)]) plaintext = json_encode(claims) # compress (if required) if compression is not None: header['zip'] = compression try: (compress, _) = COMPRESSION[compression] except KeyError: raise ValueError( 'Unsupported compression algorithm: {}'.format(compression)) plaintext = compress(plaintext) # body encryption/hash ((cipher, _), key_size), ((hash_fn, _), hash_mod) = JWA[enc] iv = rng(AES.block_size) encryption_key = rng((key_size // 8) + hash_mod.digest_size) ciphertext = cipher(plaintext, encryption_key[:-hash_mod.digest_size], iv) hash = hash_fn(_jwe_hash_str(plaintext, iv, adata), encryption_key[-hash_mod.digest_size:], hash_mod) # cek encryption (cipher, _), _ = JWA[alg] encryption_key_ciphertext = cipher(encryption_key, jwk) return JWE( *map(b64encode_url, (json_encode(header), encryption_key_ciphertext, iv, ciphertext, auth_tag(hash))))
def encrypt(claims, jwk, adata='', add_header=None, alg='RSA-OAEP', enc='A128CBC-HS256', rng=get_random_bytes, compression=None): """ Encrypts the given claims and produces a :class:`~jose.JWE` :param claims: A `dict` representing the claims for this :class:`~jose.JWE`. :param jwk: A `dict` representing the JWK to be used for encryption of the CEK. This parameter is algorithm-specific. :param adata: Arbitrary string data to add to the authentication (i.e. HMAC). The same data must be provided during decryption. :param add_header: Additional items to be added to the header. Additional headers *will* be authenticated. :param alg: The algorithm to use for CEK encryption :param enc: The algorithm to use for claims encryption :param rng: Random number generator. A string of random bytes is expected as output. :param compression: The compression algorithm to use. Currently supports `'DEF'`. :rtype: :class:`~jose.JWE` :raises: :class:`~jose.Error` if there is an error producing the JWE """ header = dict((add_header or {}).items() + [ ('enc', enc), ('alg', alg)]) plaintext = json_encode(claims) # compress (if required) if compression is not None: header['zip'] = compression try: (compress, _) = COMPRESSION[compression] except KeyError: raise Error( 'Unsupported compression algorithm: {}'.format(compression)) plaintext = compress(plaintext) # body encryption/hash ((cipher, _), key_size), ((hash_fn, _), hash_mod) = JWA[enc] iv = rng(AES.block_size) encryption_key = rng((key_size // 8) + hash_mod.digest_size) ciphertext = cipher(plaintext, encryption_key[:-hash_mod.digest_size], iv) hash = hash_fn(_jwe_hash_str(plaintext, iv, adata), encryption_key[-hash_mod.digest_size:], hash_mod) # cek encryption (cipher, _), _ = JWA[alg] encryption_key_ciphertext = cipher(encryption_key, jwk) return JWE(*map(b64encode_url, (json_encode(header), encryption_key_ciphertext, iv, ciphertext, auth_tag(hash))))
def json_application(self, http, about, json): u"try to dispatch requests to actions, produce a JSON object" try: status = self.json_actions.get(http.uri_about[-1], json_noop)(self, http, about, json) except: json[u"exception"] = self.loginfo_traceback() return http(500, CONTENT_TYPE_JSON, producer.Simple(json_encode(json))) return http(status, CONTENT_TYPE_JSON, producer.Simple(json_encode(json)))
def test_create_retval_dup(self): code = 200 data = dict(key_a="value_a") data[u"中文键"] = u"中文值" url_access(self.base + "/node/test/table/dup", json_encode(data), "PUT") try: ret = url_access(self.base + "/node/test/table/dup", json_encode(data), "PUT").read() except urllib2.HTTPError as e: code = e.code ret = e.read() self.assertEqual(code, 400) self.assertTrue(ret.find("dup") > -1) self.assertTrue(ret.find("already exists") > -1)
def to_json(self): """ Copy the settings to a JSON encoded dictionary. :returns: Settings as a JSON encoded dictionary. :rtype: str """ # Extract the settings to a dictionary and encode it with JSON. return json_encode( self.to_dictionary() )
def json_application (self, http, about, json): u"try to dispatch requests to actions, produce a JSON object" try: status = self.json_actions.get( http.uri_about[-1], json_noop ) (self, http, about, json) except: json[u"exception"] = self.loginfo_traceback () return http ( 500, CONTENT_TYPE_JSON, producer.Simple ( json_encode (json) ) ) return http ( status, CONTENT_TYPE_JSON, producer.Simple ( json_encode (json) ) )
def to_json(self): """ Copy the settings to a JSON encoded dictionary. :returns: Settings as a JSON encoded dictionary. :rtype: str """ # Extract the settings to a dictionary and encode it with JSON. return json_encode(self.to_dictionary())
def test_create_dbval(self): cursor = self.conn.cursor() data = dict(key_a="value_a") data[u"中文键"] = u"中文值" url_access(self.base + "/node/test/table/dbval", json_encode(data), method="PUT").read() cursor.execute("SELECT node_value FROM test.table \ WHERE node_path='dbval' LIMIT 1") data = cursor.fetchall() self.assertEqual(data[0][0], '"key_a"=>"value_a", "中文键"=>"中文值"')
def test_create_retval_wrong_type_2(self): """list value should not be acceptable""" data = dict(key_a=[1, 2]) data[u"中文键"] = u"中文值" code = 200 try: ret = url_access(self.base + "/node/test/table/wrong_type2", json_encode(data), "PUT").read() except urllib2.HTTPError as e: code = e.code ret = e.read() self.assertTrue("error" in ret)
def setUpClass(cls): cls.base = os.environ["MINITREE_SERVER"] cls.conn = psycopg2.connect(os.environ["MINITREE_DSN"]) url_access(cls.base + "/node/test/table/", json_encode(dict(key1="value1-1", key4="value4-1", key5="value5", key6=u"中文测试")), method="PUT").read() url_access(cls.base + "/node/test/table/a", json_encode(dict(key1="value1-2", key2="value2-1", key4="value4-2")), method="PUT").read() url_access(cls.base + "/node/test/table/a/b", json_encode(dict(key1="value1-3", key2="value2-2", key3="value3")), method="PUT").read() url_access(cls.base + "/node/test/table/a/c", json_encode(dict(key1="value1-3", key2="value2-2", key3="value3")), method="PUT").read() url_access(cls.base + "/node/test/table/a/c/d", json_encode(dict(key1="value1-3", key2="value2-2", key3="value3")), method="PUT").read() url_access(cls.base + "/node/test/table/empty", json_encode(dict()), method="PUT").read()
def to_json(self): """ Copy the settings to a JSON encoded dictionary. :retruns: Settings as a JSON encoded dictionary. :rtype: str """ # Lazy import of the JSON encoder function. global json_encode if json_encode is None: try: # The fastest JSON parser available for Python. from cjson import encode as json_encode except ImportError: try: # Faster than the built-in module, usually found. from simplejson import dumps as json_encode except ImportError: # Built-in module since Python 2.6, very very slow! from json import dumps as json_encode # Extract the settings to a dictionary and encode it with JSON. return json_encode(self.to_dictionary())
def to_json(self): """ Copy the settings to a JSON encoded dictionary. :retruns: Settings as a JSON encoded dictionary. :rtype: str """ # Lazy import of the JSON encoder function. global json_encode if json_encode is None: try: # The fastest JSON parser available for Python. from cjson import encode as json_encode except ImportError: try: # Faster than the built-in module, usually found. from simplejson import dumps as json_encode except ImportError: # Built-in module since Python 2.6, very very slow! from json import dumps as json_encode # Extract the settings to a dictionary and encode it with JSON. return json_encode( self.to_dictionary() )
def test_create_retval_trailing(self): data = dict(key_a="value_a") data[u"中文键"] = u"中文值" ret = url_access(self.base + "/node/test/table/trailing", json_encode(data), "PUT").read() self.assertTrue("success" in ret)
def test_create_retval_success(self): data = dict(key_a="value_a", key_b="\"H\"'E'%l%@l@(e)") data[u"中文键"] = u"中文值" ret = url_access(self.base + "/node/test/table/success", json_encode(data), "PUT").read() self.assertTrue("success" in ret)
def serialize(cls, params, charset): callback = u'jsonp_callback' if request: callback = request.get.get('callback', callback) s = '%s(%s);' % (callback.encode(cls.charset), json_encode(params)) return (cls.charset, s)
def serialize(cls, params, charset): return (cls.charset, json_encode(params))
def encrypt(claims, jwk, adata='', add_header=None, alg='RSA-OAEP', enc='A128CBC-HS256', rng=get_random_bytes, compression=None): """ Encrypts the given claims and produces a :class:`~jose.JWE` :param claims: A `dict` representing the claims for this :class:`~jose.JWE`. :param jwk: A `dict` representing the JWK to be used for encryption of the CEK. This parameter is algorithm-specific. :param adata: Arbitrary string data to add to the authentication (i.e. HMAC). The same data must be provided during decryption. :param add_header: Additional items to be added to the header. Additional headers *will* be authenticated. :param alg: The algorithm to use for CEK encryption :param enc: The algorithm to use for claims encryption :param rng: Random number generator. A string of random bytes is expected as output. :param compression: The compression algorithm to use. Currently supports `'DEF'`. :rtype: :class:`~jose.JWE` :raises: :class:`~jose.Error` if there is an error producing the JWE """ # copy so the injected claim doesn't mutate the input claims # this is a temporary hack to allow for graceful deprecation of tokens, # ensuring that the library can still handle decrypting tokens issued # before the implementation of the fix claims = deepcopy(claims) assert _TEMP_VER_KEY not in claims claims[_TEMP_VER_KEY] = _TEMP_VER header = dict((add_header or {}).items() + [('enc', enc), ('alg', alg)]) # promote the temp key to the header assert _TEMP_VER_KEY not in header header[_TEMP_VER_KEY] = claims[_TEMP_VER_KEY] plaintext = json_encode(claims) # compress (if required) if compression is not None: header['zip'] = compression try: (compress, _) = COMPRESSION[compression] except KeyError: raise Error( 'Unsupported compression algorithm: {}'.format(compression)) plaintext = compress(plaintext) # body encryption/hash ((cipher, _), key_size), ((hash_fn, _), hash_mod) = JWA[enc] iv = rng(AES.block_size) encryption_key = rng(hash_mod.digest_size) ciphertext = cipher(plaintext, encryption_key[-hash_mod.digest_size / 2:], iv) hash = hash_fn(_jwe_hash_str(ciphertext, iv, adata), encryption_key[:-hash_mod.digest_size / 2], hash_mod) # cek encryption (cipher, _), _ = JWA[alg] encryption_key_ciphertext = cipher(encryption_key, jwk) return JWE( *map(b64encode_url, (json_encode(header), encryption_key_ciphertext, iv, ciphertext, auth_tag(hash))))
def encrypt(claims, jwk, adata='', add_header=None, alg='RSA-OAEP', enc='A128CBC-HS256', rng=get_random_bytes, compression=None, dir_key=""): """ Encrypts the given claims and produces a :class:`~jose.JWE` :param claims: A `dict` representing the claims for this :class:`~jose.JWE`. :param jwk: A `dict` representing the JWK to be used for encryption of the CEK. This parameter is algorithm-specific. :param adata: Arbitrary string data to add to the authentication (i.e. HMAC). The same data must be provided during decryption. :param add_header: Additional items to be added to the header. Additional headers *will* be authenticated. :param alg: The algorithm to use for CEK encryption :param enc: The algorithm to use for claims encryption :param rng: Random number generator. A string of random bytes is expected as output. :param compression: The compression algorithm to use. Currently supports `'DEF'`. :param dir_key: A symmetric key to be used for Direct Ciphertext Encryption. Defined in RFC 7518, Section 4.1 :rtype: :class:`~jose.JWE` :raises: :class:`~jose.Error` if there is an error producing the JWE """ # copy so the injected claim doesn't mutate the input claims # this is a temporary hack to allow for graceful deprecation of tokens, # ensuring that the library can still handle decrypting tokens issued # before the implementation of the fix claims = deepcopy(claims) #assert _TEMP_VER_KEY not in claims #claims[_TEMP_VER_KEY] = _TEMP_VER header = dict((add_header or {}).items() + [ ('enc', enc), ('alg', alg)]) # promote the temp key to the header #assert _TEMP_VER_KEY not in header #header[_TEMP_VER_KEY] = claims[_TEMP_VER_KEY] plaintext = json_encode(claims) # compress (if required) if compression is not None: header['zip'] = compression try: (compress, _) = COMPRESSION[compression] except KeyError: raise Error( 'Unsupported compression algorithm: {}'.format(compression)) plaintext = compress(plaintext) alg = header['alg'] if(alg == 'dir'): # body encryption/hash ((cipher, _), key_size), ((hash_fn, _), hash_mod) = JWA[enc] iv = rng(AES.block_size) # for Direct encryption, pre-shared symmetric key is used #CHECK SECOND VALUE ciphertext = cipher(plaintext, dir_key, iv) hash = hash_fn(_jwe_hash_str(ciphertext, iv, adata), dir_key, hash_mod) # cek encryption encryption_key_ciphertext = '' print "FINISHED ENCRYPTING" else: # body encryption/hash print "*****DIR*****: ", dir_key ((cipher, _), key_size), ((hash_fn, _), hash_mod) = JWA[enc] iv = rng(AES.block_size) encryption_key = rng(hash_mod.digest_size) ciphertext = cipher(plaintext, encryption_key[-hash_mod.digest_size/2:], iv) hash = hash_fn(_jwe_hash_str(ciphertext, iv, adata), encryption_key[:-hash_mod.digest_size/2], hash_mod) # cek encryption (cipher, _), _ = JWA[alg] encryption_key_ciphertext = cipher(encryption_key, jwk) return JWE(*map(b64encode_url, (json_encode(header), encryption_key_ciphertext, iv, ciphertext, auth_tag(hash))))