Exemple #1
0
def decrypt_multi(JWE, keys):
    """
    Decrypt and verify a multi-recipient JWE object

    B{You should not have to use this method directly, since the L{decrypt} method
    will transparently handle multiple-recipient objects.}

    To decrypt a multi-recipient JWE object, we require two inputs: 
      1. The JWE object to be decrypted
      2. A set of keys from which to draw the public key or shared key

    This method identifies whether it can use one of the per-recipient 
    structures in the JWE to decrypt the object.  If so, it performs the
    decryption and returns the results as a dictionary of the same form 
    as the L{decrypt} method.

    If the verification succeeds, the "result" field will be set to True, and 
    the "protected" and "payload" fields will be populated.  If verification
    fails, then the "plaintext" field will be set to False, and the other two
    fields will not be present.

    @type  JWE : dict
    @param JWE : Unserialized JWS object 
    @type  keys: list or set of JWK
    @param keys: Set of keys from which the decryption key will be selected
    @rtype: dict
    @return: Decryption results, including the boolean result and, if succesful,
      the signed header parameters and payload
    """
    if not isJOSE(JWE):
        raise Exception("Cannot process something that's not a JOSE object")
    elif isJOSE_serialized(JWE):
        JWE = serialize.deserialize(JWE)

    if not isJWE_unserialized_multi(JWE):
        raise Exception("decrypt_multi called on a non-multi-recipient JWE")

    # Copy most of the JWE into a new object
    single = copy(JWE)
    del single["recipients"]

    # Find something we can use to decrypt
    selectedRecipient = None
    for r in JWE["recipients"]:
        try:
            key = josecrypto.findKey(r["header"], keys, allowDefault=False)
            selectedRecipient = r
            break
        except:
            pass
    if selectedRecipient == None:
        raise Exception("Unable to locate a usable key in multi-recipient JWE")

    # Construct a standard JWE and decrypt
    if "unprotected" not in single:
        single["unprotected"] = {}
    single["unprotected"] = joinHeader(JWE["unprotected"],
                                       selectedRecipient["header"])
    single["encrypted_key"] = selectedRecipient["encrypted_key"]
    return decrypt(single, keys)
Exemple #2
0
def retrieve_teacher():
	serialized_teacher= session.get("teacher")
	if serialized_teacher is None:
		serialized_teacher= request.cookies.get('teacher')
	if serialized_teacher is not None:
		return deserialize(serialized_teacher)
	return None
Exemple #3
0
 def read_records(self, file):
     """return log record as (index, (tid, op)) list"""
     verbose = self.verbose
     if verbose:
         print "reading log records to error"
     records = {}
     count = 0
     while 1:
         try:
             data = checksum_undump(file)
         except:
             if verbose:
                 print "record read terminated with error", len(records)
                 print sys.exc_type, sys.exc_value
             break
         (transactionid, serial) = data
         operation = serialize.deserialize(serial)
         records[count] = (transactionid, operation)
         if verbose:
             print count, ": read for", transactionid
             print operation
         count = count + 1
     if verbose:
         print len(records), "records total"
     records = records.items()
     records.sort()
     return records
Exemple #4
0
 def read_records(self, file):
     """return log record as (index, (tid, op)) list"""
     verbose = self.verbose
     if verbose: print "reading log records to error"
     records = {}
     count = 0
     while 1:
         try:
             data = checksum_undump(file)
         except:
             if verbose:
                 print "record read terminated with error", len(records)
                 print sys.exc_type, sys.exc_value
             break
         (transactionid, serial) = data
         operation = serialize.deserialize(serial)
         records[count] = (transactionid, operation)
         if verbose:
             print count, ": read for", transactionid
             print operation
         count = count + 1
     if verbose: print len(records), "records total"
     records = records.items()
     records.sort()
     return records
Exemple #5
0
def decrypt_multi(JWE, keys):
    """
    Decrypt and verify a multi-recipient JWE object

    B{You should not have to use this method directly, since the L{decrypt} method
    will transparently handle multiple-recipient objects.}

    To decrypt a multi-recipient JWE object, we require two inputs: 
      1. The JWE object to be decrypted
      2. A set of keys from which to draw the public key or shared key

    This method identifies whether it can use one of the per-recipient 
    structures in the JWE to decrypt the object.  If so, it performs the
    decryption and returns the results as a dictionary of the same form 
    as the L{decrypt} method.

    If the verification succeeds, the "result" field will be set to True, and 
    the "protected" and "payload" fields will be populated.  If verification
    fails, then the "plaintext" field will be set to False, and the other two
    fields will not be present.

    @type  JWE : dict
    @param JWE : Unserialized JWS object 
    @type  keys: list or set of JWK
    @param keys: Set of keys from which the decryption key will be selected
    @rtype: dict
    @return: Decryption results, including the boolean result and, if succesful,
      the signed header parameters and payload
    """
    if not isJOSE(JWE):
        raise Exception("Cannot process something that's not a JOSE object")
    elif isJOSE_serialized(JWE):
        JWE = serialize.deserialize(JWE)

    if not isJWE_unserialized_multi(JWE):
        raise Exception("decrypt_multi called on a non-multi-recipient JWE")

    # Copy most of the JWE into a new object
    single = copy(JWE)
    del single["recipients"]

    # Find something we can use to decrypt
    selectedRecipient = None
    for r in JWE["recipients"]:
        try:
            key = josecrypto.findKey(r["header"], keys, allowDefault=False)
            selectedRecipient = r
            break
        except:
            pass
    if selectedRecipient == None:
        raise Exception("Unable to locate a usable key in multi-recipient JWE")

    # Construct a standard JWE and decrypt
    if "unprotected" not in single:
        single["unprotected"] = {}
    single["unprotected"] = joinHeader(JWE["unprotected"], selectedRecipient["header"])
    single["encrypted_key"] = selectedRecipient["encrypted_key"]
    return decrypt(single, keys)
Exemple #6
0
 def loadPressed(self):
     filetypes = [('ttt files', '.ttt'), ('all files', '.*')]
     filename = tkFileDialog.askopenfilename(filetypes=filetypes)
     if filename == "":
         return
     data = open(filename).read()
     state = deserialize(data)
     self.startGame(state)
Exemple #7
0
 def listen(self):
     while not rospy.is_shutdown():
         try:
             channel, bytes_data = self.pull.recv_multipart()
             data = osgar_serialize.deserialize(bytes_data)
             return channel.decode('ascii'), data
         except zmq.ZMQError as e:
             if e.errno != zmq.EAGAIN:
                 rospy.logerr("zmq error")
                 sys.exit("zmq error")
     rospy.loginfo("done")
     sys.exit()
Exemple #8
0
def unbundle(JWP):
    """
    Unbundle a JWP object

    Also performs decompression if required by "zip", and verification of
    support for fields in the "crit" header.

    @type  JWP : dict
    @param JWP : Unserialized JWP object 
    @rtype: dict
    @return: Verification results, including the boolean result and, if succesful,
      the signed header parameters and payload
    """

    # Deserialize if necessary
    if not isJOSE(JWP):
        raise Exception("Cannot process something that's not a JOSE object")
    elif isJOSE_serialized(JWP):
        JWP = serialize.deserialize(JWP)

    # Make sure we have a JWP
    if not isJWP_unserialized(JWP):
        raise Exception("decrypt() called with something other than a JWP")

    # Capture the payload and header
    JWPHeader = JWP["unprotected"]
    JWPPayload = JWP["payload"]
    
    # Verify that if "alg" is present, it is set to "none"
    if "alg" not in JWPHeader or JWPHeader["alg"] != "none":
        raise Exception("'alg' value in JWP header must be 'none'")

    # Check that we support everything critical
    if not criticalParamsSupported(JWPHeader, supported_hdr_ext):
        raise Exception("Unsupported critical fields")

    # Decompress if required
    if "zip" in JWPHeader and JWPHeader["zip"] == "DEF":
        JWPPayload = zlib.decompress(JWPPayload)
    
    # Return the verified payload and headers 
    return {
        "unprotected": JWPHeader,
        "payload": JWPPayload
    }
Exemple #9
0
    def loadPackage(self, name, loc):
        self.ensurePackageInfo()
        if name not in self.packageInfoByName:
            raise errors.PackageException(loc, "%s: could not find package" % str(name))

        info = self.packageInfoByName[name]
        if info.package is not None:
            return info.package
        fileName = self.packageInfoByName[name].fileName
        package = serialize.deserialize(fileName)
        info.package = package
        self.packageInfoById[package.id] = info

        for dep in package.dependencies:
            dep.package = self.loadPackage(dep.name, loc)

        self.runLoadHooks(package)
        return package
Exemple #10
0
def ingest_data(fo):
    data = {}
    for obj in serialize.deserialize(fo.read()):
        for k, v in obj.items():
            if k not in data.keys():
                if isinstance(v, edn_format.ImmutableList):
                    data[k] = list(v)
                elif isinstance(v, edn_format.ImmutableDict):
                    data[k] = dict(v)
                else:
                    data[k] = v
            else:
                if isinstance(v, edn_format.ImmutableList):
                    data[k].extend(v)
                elif isinstance(v, edn_format.ImmutableDict):
                    data[k].update(v)
                else:
                    raise TypeError(f"Key {k} has an unsupported value type {type(v)}")
    return data
Exemple #11
0
def unbundle(JWP):
    """
    Unbundle a JWP object

    Also performs decompression if required by "zip", and verification of
    support for fields in the "crit" header.

    @type  JWP : dict
    @param JWP : Unserialized JWP object 
    @rtype: dict
    @return: Verification results, including the boolean result and, if succesful,
      the signed header parameters and payload
    """

    # Deserialize if necessary
    if not isJOSE(JWP):
        raise Exception("Cannot process something that's not a JOSE object")
    elif isJOSE_serialized(JWP):
        JWP = serialize.deserialize(JWP)

    # Make sure we have a JWP
    if not isJWP_unserialized(JWP):
        raise Exception("decrypt() called with something other than a JWP")

    # Capture the payload and header
    JWPHeader = JWP["unprotected"]
    JWPPayload = JWP["payload"]

    # Verify that if "alg" is present, it is set to "none"
    if "alg" not in JWPHeader or JWPHeader["alg"] != "none":
        raise Exception("'alg' value in JWP header must be 'none'")

    # Check that we support everything critical
    if not criticalParamsSupported(JWPHeader, supported_hdr_ext):
        raise Exception("Unsupported critical fields")

    # Decompress if required
    if "zip" in JWPHeader and JWPHeader["zip"] == "DEF":
        JWPPayload = zlib.decompress(JWPPayload)

    # Return the verified payload and headers
    return {"unprotected": JWPHeader, "payload": JWPPayload}
def main():
    """Main program."""
    site = crawler.Site()
    # parse command-line arguments
    parse_args(site)
    # read serialized file
    if config.CONTINUE:
        fname = os.path.join(config.OUTPUT_DIR, 'webcheck.dat')
        debugio.info('reading stored crawler data....')
        try:
            fp = open(fname, 'r')
            site = serialize.deserialize(fp)
            fp.close()
        except IOError, (errno, strerror):
            debugio.error('%(fname)s: %(strerror)s' % {
                'fname': fname,
                'strerror': strerror
            })
            sys.exit(1)
        debugio.info('done.')
Exemple #13
0
    def serve_forever(self):
        '''listen for incoming (serialized) initial ChromaPhotonLists,
        propagate photons in chroma, and reply with final photon list
        '''
        while True:
            msg = self.socket.recv(copy=False)

            # parse ChromaPhotonList
            cpl = serialize.deserialize(msg.bytes)
            if not cpl:
                print 'Error deserializing message data'
                continue

            photons_in = photons.photons_from_cpl(cpl)
            print 'processing', len(photons_in), 'photons'

            # propagate photons in chroma simulation
            event = self.sim.simulate(photons_in, keep_photons_end=True).next()

            # return final (detected) photons to client
            photons_out = event.photons_end
            cpl = photons.cpl_from_photons(photons_out, process_mask=SURFACE_DETECT, detector=self.detector)
            msg = serialize.serialize(cpl)
            self.socket.send(msg)
Exemple #14
0
    def loadPackage(self, name, loc=NoLoc):
        """Loads a package by name.

        Calls `ensurePackageInfo` internally. If the package is already loaded, it will be
        returned instead of being loaded again. Dependencies of the loaded package will be
        loaded recursively. Load hooks will be called for each newly loaded package.

        Args:
            name (Name): the name of the package.
            loc (Location): used for error messages.

        Returns:
            (Package): the loaded package.

        Raises:
            PackageException: if the package cannot be located or its metadata does not match
                its filename.
            OSError: if there is an I/O error loading the package.
        """
        self.ensurePackageInfo()
        if name not in self.packageInfoByName:
            raise errors.PackageException(loc, "%s: could not find package" % str(name))

        info = self.packageInfoByName[name]
        if info.package is not None:
            return info.package
        fileName = self.packageInfoByName[name].fileName
        package = serialize.deserialize(fileName, self)
        info.package = package
        self.packageInfoById[package.id] = info

        for dep in package.dependencies:
            dep.package = self.loadPackage(dep.name, loc)

        self._runLoadHooks(package)
        return package
Exemple #15
0
def verify(JWS, keys):
    """
    Verify a JWS object

    To verify a JWS object, we require two inputs: 
      1. The JWS object to be verified
      2. A set of keys from which to draw the public key or shared key

    (This implementation does not currently support using the "jwk" attribute
    for a public key, so the key must be provided.)

    This method returns verification results as a dictionary with the following
    fields:
      - "result": The boolean result of the verification
      - "protected": (optional) The protected headers, as a dictionary
      - "payload": (optional) The signed payload

    If the verification succeeds, the "result" field will be set to True, and 
    the "protected" and "payload" fields will be populated.  If verification
    fails, then the "result" field will be set to False, and the other two
    fields will not be present.

    @type  JWS : dict
    @param JWS : Unserialized JWS object 
    @type  keys: list or set of JWK
    @param keys: Set of keys from which the public/shared key will be selected (
      based on the header)
    @rtype: dict
    @return: Verification results, including the boolean result and, if succesful,
      the signed header parameters and payload
    """

    # Deserialize if necessary
    if not isJOSE(JWS):
        raise Exception("Cannot process something that's not a JOSE object")
    elif isJOSE_serialized(JWS):
        JWS = serialize.deserialize(JWS)

    # Make sure we have a JWS
    if not isJWS_unserialized(JWS):
        raise Exception("decrypt() called with something other than a JWS")
    
    # Handle multi-signature JWSs separately
    if isJWS_unserialized_multi(JWS):
        return verify_multi(JWS, keys)


    # Capture the payload
    JWSPayload = JWS["payload"]

    # Reassemble the header
    JWSUnprotectedHeader = JWS["unprotected"] if ("unprotected" in JWS) else {}
    if "protected" in JWS:
        SerializedJWSProtectedHeader = JWS["protected"]    
        JWSProtectedHeader = json.loads(SerializedJWSProtectedHeader)
    else:
        SerializedJWSProtectedHeader = ""
        JWSProtectedHeader = {}
    header = joinHeader(JWSUnprotectedHeader, JWSProtectedHeader)

    # Check that we support everything critical
    if not criticalParamsSupported(header, supported_hdr_ext):
        raise Exception("Unsupported critical fields")

    # Construct the JWS Signing Input
    JWSSigningInput = createSigningInput(SerializedJWSProtectedHeader, JWSPayload)

    # Look up the key
    key = josecrypto.findKey(header, keys)

    # Verify the signature
    JWSSignature = JWS["signature"]
    JWSVerificationResult = josecrypto.verify( \
        header["alg"], key, JWSSigningInput, JWSSignature )
    
    # Return the verified payload and headers 
    if JWSVerificationResult:
        return {
            "result": True,
            "payload": JWSPayload,
            "protected": JWSProtectedHeader
        }
    else: 
        return { "result": False }
#         self.left = None
#         self.right = None

class Solution:
    def deleteNode(self, root, key):
        """
        :type root: TreeNode
        :type key: int
        :rtype: TreeNode
        """
        if not root: return
        if root.val > key:
            self.deleteNode(root.left, key)
        elif root.val < key:
            self.deleteNode(root.right, key)
        else:
            if not root.left: return root.right
            if not root.right: return root.left
            prevpred = root
            pred = root.left
            while pred.right:
                prevpred = pred
                pred = pred.right
            root.val, pred.val = pred.val, root.val
            prevpred.left = self.deleteNode(pred, key)
        return root

import serialize
root = serialize.deserialize("5,3,6,2,4,null,7")
sol = Solution()
sol.deleteNode(root, 3)
Exemple #17
0
#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 整体策略说明
# - 对同一语言,从本地各仓库获取最新 merge 的项目为 v1.json,从 crowdIn 中获取的项目
# 为 v2
# - 序列化 v1.json 和 v2.json
# - 以 v1.json 作为基础,比较 v1.json 和 v2.json,
#     * 改动的:使用 v2 文件
#     * 相同的:跳过
#     * 新增的:跳过
# - 获取新的结果 result,并进行反序列化
# - 将反序列化的内容,输出到文件中,作为该翻译语种的最终版本 result.json

import serialize as sl

v1 = sl.serialize('v1.json')
v2 = sl.serialize('v2.json')
result = sl.deserialize(sl.compare(v1, v2))
sl.write_to_file('./result.json', result)
Exemple #18
0
from __future__ import with_statement

import csv
import os

# this module is included as part of webcheck.
import serialize

FILENAME = 'my_site_links_as_csv.csv'
DATFILE = 'my_site/webcheck.dat'

if __name__ == '__main__':

    # using webcheck's serialize module to create a site object.
    site = serialize.deserialize(open(DATFILE, 'r'))

    with open(FILENAME, 'w') as sitecsv:
        writer = csv.writer(sitecsv)

        writer.writerow(("path", "extension", "internal", "errors"))
        writer.writerows(
                ((k,
                 os.path.splitext(v.path)[-1],
                 v.isinternal,
                 ' '.join(v.linkproblems))
                 
                 # the site object has a dictionary between URI and a link object.
                 for (k, v) in site.linkMap.iteritems()))
Exemple #19
0
def run(hostname, calculations=False, backtest=False, portfolio_manager=False, port=consts.PORT):
    from socket import socket, AF_INET, SOCK_STREAM
    from dataproviders import ClientDataProvider

    # import inspect
    import json

    # frm = inspect.stack()[1]
    # mod = inspect.getmodule(frm[0])
    # filepath = os.path.dirname(os.path.abspath(mod.__file__))
    projpath = os.getcwd()

    s = socket(AF_INET, SOCK_STREAM)
    s.connect((hostname, port))

    atexit.register(close_socket_connection, s)

    "signal to start execution"

    sendmsg = mlprotocol.create_message(
        json.dumps({"calculations": calculations, "backtest": backtest, "portfolio_manager": portfolio_manager})
    )
    s.send(sendmsg)

    userobj = None
    socket_dataprovider = ClientDataProvider(socket=s)

    "receive data"
    while True:
        data = mlprotocol.get_message(s)
        # data = s.recv(consts.BUFFER_SIZE)

        if data == consts.STOP_FLAG:
            print "STOPPED"
            break

        socket_dataprovider.reset_ack()

        params = deserialize(data, dotted=True)
        invocation = params.get("_invocation")
        method = invocation["method"]
        cls = invocation["class"]

        if method == "ping":
            return "PONG"
        elif method == "get_implementation_info":
            info = helpers.get_implementation_info(projpath)
            s_info = serialize(info)
            socket_dataprovider.ack_data(s_info)
            socket_dataprovider.send_ack()
            continue

        if not userobj:
            usercls = helpers.find_implementation(projpath, cls)
            userobj = usercls(data_provider=socket_dataprovider)

        helpers.attach_parameters(socket_dataprovider, params)
        invoke_method(userobj, method, params)

        "send acknowledgement to the server"
        socket_dataprovider.send_ack()
Exemple #20
0
from __future__ import with_statement

import csv
import os

# this module is included as part of webcheck.
import serialize

FILENAME = 'my_site_links_as_csv.csv'
DATFILE = 'my_site/webcheck.dat'

if __name__ == '__main__':

    # using webcheck's serialize module to create a site object.
    site = serialize.deserialize(open(DATFILE, 'r'))

    with open(FILENAME, 'w') as sitecsv:
        writer = csv.writer(sitecsv)

        writer.writerow(("path", "extension", "internal", "errors"))
        writer.writerows((
            (k, os.path.splitext(v.path)[-1], v.isinternal,
             ' '.join(v.linkproblems))

            # the site object has a dictionary between URI and a link object.
            for (k, v) in site.linkMap.iteritems()))
Exemple #21
0
        if upper[-1].left:
            node = upper[-1].left
            while node:
                upper.append(node)
                node = node.right
        else:
            node = upper.pop()
            while upper and upper[-1].left == node:
                node = upper.pop()

    def loweriscloser(self, upper, lower, target):
        if not upper: return True
        if not lower: return False
        return upper[-1].val - target > target - lower[-1].val

    def getpath(self, node, target):
        path = []
        while node:
            path.append(node)
            if node.val > target:
                node = node.left
            elif node.val < target:
                node = node.right
            else:
                break
        return path


root = serialize.deserialize("4,2,5,1,3")
sol = Solution()
sol.closestKValues(root, 3.75, 2)
Exemple #22
0
def run(hostname,
        calculations=False,
        backtest=False,
        portfolio_manager=False,
        port=consts.PORT):
    from socket import socket, AF_INET, SOCK_STREAM
    from dataproviders import ClientDataProvider
    # import inspect
    import json

    # frm = inspect.stack()[1]
    # mod = inspect.getmodule(frm[0])
    # filepath = os.path.dirname(os.path.abspath(mod.__file__))
    projpath = os.getcwd()

    s = socket(AF_INET, SOCK_STREAM)
    s.connect((hostname, port))

    atexit.register(close_socket_connection, s)

    "signal to start execution"

    sendmsg = mlprotocol.create_message(
        json.dumps({
            'calculations': calculations,
            'backtest': backtest,
            'portfolio_manager': portfolio_manager
        }))
    s.send(sendmsg)

    userobj = None
    socket_dataprovider = ClientDataProvider(socket=s)

    "receive data"
    while True:
        data = mlprotocol.get_message(s)
        # data = s.recv(consts.BUFFER_SIZE)

        if data == consts.STOP_FLAG:
            print 'STOPPED'
            break

        socket_dataprovider.reset_ack()

        params = deserialize(data, dotted=True)
        invocation = params.get('_invocation')
        method = invocation['method']
        cls = invocation['class']

        if method == 'ping':
            return 'PONG'
        elif method == 'get_implementation_info':
            info = helpers.get_implementation_info(projpath)
            s_info = serialize(info)
            socket_dataprovider.ack_data(s_info)
            socket_dataprovider.send_ack()
            continue

        if not userobj:
            usercls = helpers.find_implementation(projpath, cls)
            userobj = usercls(data_provider=socket_dataprovider)

        helpers.attach_parameters(socket_dataprovider, params)
        invoke_method(userobj, method, params)

        "send acknowledgement to the server"
        socket_dataprovider.send_ack()
Exemple #23
0
from node import TreeNode


def is_balanced(root: TreeNode) -> bool:
    if not root:
        return True

    def dfs(node: TreeNode) -> Tuple[int, bool]:
        """
        遍历返回节点的深度、是否平衡

        :type node: TreeNode
        :rtype: Tuple[int, bool]
        """
        depth_l, balance_l = dfs(node.left) if node.left else (0, True)
        depth_r, balance_r = dfs(node.right) if node.right else (0, True)
        depth = 1 + max(depth_l, depth_r)
        balance = balance_l and balance_r and abs(depth_l - depth_r) <= 1
        return depth, balance

    return dfs(root)[1]


if __name__ == "__main__":
    # test case
    from testcase import BalanceCase
    from serialize import deserialize
    for tc in BalanceCase.TEST:
        root = deserialize(tc[0])
        assert tc[1] == is_balanced(root)
Exemple #24
0
def decrypt(JWE, keys):
    """
    Decrypt and verify a JWE object

    To decrypt a JWE object, we require two inputs: 
      1. The JWE object to be decrypted
      2. A set of keys from which to draw the public key or shared key

    This function returns decryption/verification results as a 
    dictionary with the following fields:
      - "result": The boolean result of the verification
      - "protected": (optional) The protected headers, as a dictionary
      - "plaintext": (optional) The signed payload

    If the verification succeeds, the "result" field will be set to True, and 
    the "protected" and "payload" fields will be populated.  If verification
    fails, then the "plaintext" field will be set to False, and the other two
    fields will not be present.

    @type  JWE : dict
    @param JWE : Unserialized JWS object 
    @type  keys: list or set of JWK
    @param keys: Set of keys from which the decryption key will be selected
    @rtype: dict
    @return: Decryption results, including the boolean result and, if succesful,
      the signed header parameters and payload
    """

    # Deserialize if necessary
    if not isJOSE(JWE):
        raise Exception("Cannot process something that's not a JOSE object")
    elif isJOSE_serialized(JWE):
        JWE = serialize.deserialize(JWE)

    # Make sure we have a JWE
    if not isJWE_unserialized(JWE):
        raise Exception("decrypt() called with something other than a JWE")

    # Handle multi-recipient JWEs separately
    if isJWE_unserialized_multi(JWE):
        return decrypt_multi(JWE, keys)

    # Capture the crypto inputs
    JWECiphertext = JWE["ciphertext"]
    JWEInitializationVector = JWE["iv"] if "iv" in JWE else ""
    JWEAuthenticationTag = JWE["tag"] if "tag" in JWE else ""
    JWEAAD = JWE["aad"] if "aad" in JWE else ""

    # Reassemble the header
    JWEUnprotectedHeader = JWE["unprotected"] if ("unprotected" in JWE) else {}
    if "protected" in JWE:
        SerializedJWEProtectedHeader = JWE["protected"]
        JWEProtectedHeader = json.loads(SerializedJWEProtectedHeader)
    else:
        SerializedJWEProtectedHeader = ""
        JWEProtectedHeader = {}
    header = joinHeader(JWEUnprotectedHeader, JWEProtectedHeader)

    # Check that we support everything critical
    if not criticalParamsSupported(header, supported_hdr_ext):
        raise Exception("Unsupported critical fields")

    # Construct the AAD
    JWEAuthenticatedData = createSigningInput( \
        SerializedJWEProtectedHeader, JWEAAD, JWE=True)

    # Locate the key
    key = josecrypto.findKey(header, keys)

    # Unwrap or derive the key according to 'alg'
    JWEEncryptedKey = JWE["encrypted_key"] if "encrypted_key" in JWE else ""
    CEK = josecrypto.decryptKey(header["alg"], header["enc"], key,
                                JWEEncryptedKey, header)

    # Perform the decryption
    (JWEPlaintext, JWEVerificationResult) = josecrypto.decrypt( \
        header["enc"], CEK, JWEInitializationVector, JWEAuthenticatedData, \
            JWECiphertext, JWEAuthenticationTag )

    # Decompress the plaintext if necessary
    if "zip" in header and header["zip"] == "DEF":
        JWEPlaintext = zlib.decompress(JWEPlaintext)

    # Return the results of decryption
    if JWEVerificationResult:
        return {
            "result": JWEVerificationResult,
            "plaintext": JWEPlaintext,
            "protected": JWEProtectedHeader
        }
    else:
        return {"result": JWEVerificationResult}
Exemple #25
0
def verify_multi(JWS, keys):
    """
    Verify a multi-signer JWS object

    B{You should not have to use this method directly, since the L{verify} method
    will transparently handle multiple-signature objects.}

    To verify a JWS object, we require two inputs: 
      1. The JWS object to be verified
      2. A set of keys from which keys for verification will be drawn

    (This implementation does not currently support using the "jwk" attribute
    for a public key, so the key must be provided.)

    This method returns a dictionary describing the results of the validation,
    including the following fields
      - "payload": The payload used for verification
      - "results": The a list of results per signature, as a dictionary with
        the following fields:
          - "result": The boolean verification result
          - "unprotected": (optional) Unprotected headers for this signature
          - "protected": (optional) Protected headers for this signature

    Note that unlike the single-recipient L{verify} method, this method 
    returns the payload and headers regardless of whether any verification
    succeeded.  This allows applications to merge multiple signatures in
    several different possible ways.  Applications should be careful, however
    that they do not assume that just because a payload is present it is 
    verified.

    @type  JWS : dict
    @param JWS : Unserialized JWS object 
    @type  keys: list or set of JWK
    @param keys: Set of keys from which verification keys will be selected (
      based on the header)
    @rtype: list
    @return: Verification results, including for each signature the boolean 
      result and, if succesful, the signed header parameters and payload
    """

    
    if not isJOSE(JWS):
        raise Exception("Cannot process something that's not a JOSE object")
    elif isJOSE_serialized(JWS):
        JWS = serialize.deserialize(JWS)

    if not isJWS_unserialized_multi(JWS):
        raise Exception("decrypt_multi called on a non-multi-signature JWS")


    # Reconstruct and validte individual JWSs for each signer
    payload = JWS["payload"]
    results = {
        "payload": payload,
        "results": []
    }
    for s in JWS["signatures"]:
        # Make a JWS and validate it
        jws = copy(s)
        jws["payload"] = payload
        r = verify(jws, keys)

        # Add headers to the result 
        # ... so the app can tell who it's from
        if ("payload" in r):
            del  r["payload"]
        if ("unprotected" in s):
            r["unprotected"] = s["unprotected"]
        if ("protected" in s):
            r["protected"] = json.loads(s["protected"])
        results["results"].append(r)

    # Return the results array
    return results
Exemple #26
0
def decrypt(JWE, keys):
    """
    Decrypt and verify a JWE object

    To decrypt a JWE object, we require two inputs: 
      1. The JWE object to be decrypted
      2. A set of keys from which to draw the public key or shared key

    This function returns decryption/verification results as a 
    dictionary with the following fields:
      - "result": The boolean result of the verification
      - "protected": (optional) The protected headers, as a dictionary
      - "plaintext": (optional) The signed payload

    If the verification succeeds, the "result" field will be set to True, and 
    the "protected" and "payload" fields will be populated.  If verification
    fails, then the "plaintext" field will be set to False, and the other two
    fields will not be present.

    @type  JWE : dict
    @param JWE : Unserialized JWS object 
    @type  keys: list or set of JWK
    @param keys: Set of keys from which the decryption key will be selected
    @rtype: dict
    @return: Decryption results, including the boolean result and, if succesful,
      the signed header parameters and payload
    """

    # Deserialize if necessary
    if not isJOSE(JWE):
        raise Exception("Cannot process something that's not a JOSE object")
    elif isJOSE_serialized(JWE):
        JWE = serialize.deserialize(JWE)

    # Make sure we have a JWE
    if not isJWE_unserialized(JWE):
        raise Exception("decrypt() called with something other than a JWE")

    # Handle multi-recipient JWEs separately
    if isJWE_unserialized_multi(JWE):
        return decrypt_multi(JWE, keys)

    # Capture the crypto inputs
    JWECiphertext = JWE["ciphertext"]
    JWEInitializationVector = JWE["iv"] if "iv" in JWE else ""
    JWEAuthenticationTag = JWE["tag"] if "tag" in JWE else ""
    JWEAAD = JWE["aad"] if "aad" in JWE else ""

    # Reassemble the header
    JWEUnprotectedHeader = JWE["unprotected"] if ("unprotected" in JWE) else {}
    if "protected" in JWE:
        SerializedJWEProtectedHeader = JWE["protected"]     
        JWEProtectedHeader = json.loads(SerializedJWEProtectedHeader)
    else:
        SerializedJWEProtectedHeader = ""
        JWEProtectedHeader = {}
    header = joinHeader(JWEUnprotectedHeader, JWEProtectedHeader)

    # Check that we support everything critical
    if not criticalParamsSupported(header, supported_hdr_ext):
        raise Exception("Unsupported critical fields")    

    # Construct the AAD
    JWEAuthenticatedData = createSigningInput( \
        SerializedJWEProtectedHeader, JWEAAD, JWE=True)

    # Locate the key
    key = josecrypto.findKey(header, keys)

    # Unwrap or derive the key according to 'alg'
    JWEEncryptedKey = JWE["encrypted_key"] if "encrypted_key" in JWE else ""
    CEK = josecrypto.decryptKey(header["alg"], header["enc"], key, JWEEncryptedKey, header)

    # Perform the decryption
    (JWEPlaintext, JWEVerificationResult) = josecrypto.decrypt( \
        header["enc"], CEK, JWEInitializationVector, JWEAuthenticatedData, \
            JWECiphertext, JWEAuthenticationTag )
    
    # Decompress the plaintext if necessary
    if "zip" in header and header["zip"] == "DEF":
        JWEPlaintext = zlib.decompress(JWEPlaintext)

    # Return the results of decryption
    if JWEVerificationResult:
        return {
            "result": JWEVerificationResult,
            "plaintext": JWEPlaintext,
            "protected": JWEProtectedHeader
        }
    else:
        return { "result": JWEVerificationResult }
Exemple #27
0
 def spop(self, queue):
     msg = self._conn.spop(queue)
     return deserialize(msg) if msg else msg
Exemple #28
0
 def spop(self, queue):
     msg = self._conn.spop(queue)
     return deserialize(msg) if msg else msg
Exemple #29
0
 def _parse_params(self, data):
     params = deserialize(data, dotted=True)
     invocation = params.get('_invocation', {})
     method = invocation.get('method', '')
     cls = invocation.get('class', '')
     return method, cls, params