Exemplo n.º 1
0
    def encrypt(self, plain: bytes):
        self.__bit_array = to_bit_array(plain)
        self.__bit_array = substitute(self.__bit_array, ip_sub)

        for round in range(round_count):
            l, r = self.__bit_array[:32], self.__bit_array[32:]
            key = self.__enc_keys.get_i_key(round)
            expanded = substitute(r, expansion)
            xor_k_e = list_xor(key, expanded)
            sbox_subed = []
            for i in range(8):
                six_bits = xor_k_e[i * 6:(i + 1) * 6]
                sb_row = six_bits[5] + (six_bits[0] << 1)
                sb_col = (six_bits[1] << 3) + (six_bits[2] << 2) + (
                    six_bits[3] << 1) + six_bits[4]
                res = int_to_bit_array(sbox[i][sb_row][sb_col], 4)
                sbox_subed += res
            res = substitute(sbox_subed, p_out)
            xored = list_xor(l, res)
            print(xored)
            self.__bit_array = r + xored if round < round_count - 1 else xored + r

        self.__bit_array = substitute(self.__bit_array, ip_sub_inv)

        return bit_array_to_bytes(self.__bit_array)
Exemplo n.º 2
0
def gen_sygus_for_pair(result_dir, template, l_name_1, l1, SC1, l_name_2, l2,
                       SC2):

    #keep essense of names:
    l_name_1 = fix_name(l_name_1)
    l_name_2 = fix_name(l_name_2)
    l_name = l_name_1 + "_" + l_name_2

    #define the substitutions
    base_substitutions = {}
    base_substitutions[L1_PH] = l1
    base_substitutions[L2_PH] = l2
    base_substitutions[SC1_PH] = SC1
    base_substitutions[SC2_PH] = SC2
    base_sy = utils.substitute(template, base_substitutions)

    #generate the sygus queries
    #s1, s2, t1, t2 may or may not be equal
    plain_sy = utils.substitute(base_sy, {EQUALITY_ASSUMPTIONS_PH: "true"})
    #s1=s2
    s_sy = utils.substitute(base_sy, {EQUALITY_ASSUMPTIONS_PH: "(= s1 s2)"})
    #t1=t2
    t_sy = utils.substitute(base_sy, {EQUALITY_ASSUMPTIONS_PH: "(= t1 t2)"})
    #s1=s2 and t1=t2
    st_sy = utils.substitute(
        base_sy, {EQUALITY_ASSUMPTIONS_PH: "(and (= s1 s2) (= t1 t2))"})
    #save
    save_string_to_file_in_dir(plain_sy, l_name + "_plain.sy", result_dir)
    save_string_to_file_in_dir(s_sy, l_name + "_s.sy", result_dir)
    save_string_to_file_in_dir(t_sy, l_name + "_t.sy", result_dir)
    save_string_to_file_in_dir(st_sy, l_name + "_st.sy", result_dir)
Exemplo n.º 3
0
def make_substitutions(l_name_to_l_sc):
    result = {}
    for name in l_name_to_l_sc.keys():
        l, sc = l_name_to_l_sc[name]
        l = utils.substitute(l, substitutions)
        #some side conditions include a big disjunction. This should be transform to existential
        if "bv2" in sc:
            sc = replace_disj_with_exists(sc)
        sc = utils.substitute(sc, substitutions)
        if l is not None and sc is not None:
            result[name] = [l, sc]
    return result
Exemplo n.º 4
0
    def __init__(self, key: bytes) -> None:
        self.__keys = []
        self.__bit_array = to_bit_array(key)
        res = substitute(self.__bit_array, pc1)
        c, d = res[:28], res[28:]
        for i in range(16):
            if i in [0, 1, 8, 15]:
                c = c[1:] + c[:1]
                d = d[1:] + d[:1]
            else:
                c = c[2:] + c[:2]
                d = d[2:] + d[:2]

            k = substitute(c + d, pc2)
            self.__keys.append(k)
Exemplo n.º 5
0
 def run(self, env):
     if "SOCKET" in env:
         logging.error("SOCKET already defined, close prior connection first")
         raise TaskError("SOCKET already defined, close prior connection first")
     
     server = utils.substitute(self.server, env)
     port = utils.substitute(self.port, env) if isinstance(self.port, str) else self.port
     
     logging.info("Connecting to " + str(server) + ":" + str(port))
     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     s.connect((server, int(port)))
     env["SOCKET"] = s
     env["SOCKET_FILE"] = s.makefile()
     env["STDOUT"] = StringIO()
     logging.info("Successfully connected")
Exemplo n.º 6
0
def main():
    from docopt import docopt
    args = docopt(__doc__, version=__version__)

    args_exclude = args.get('--exclude')
    exclude = []
    if args_exclude:
        exclude = [os.path.realpath(e) for e in args_exclude]

    version = args.get('--go-version') if args.get('--go-version') is not None else default_version()

    gopath = find_for_gopath(substitute(args.get('--basedir')), exclude)

    # we should have _something_ in the GOPATH...
    if not gopath:
        gopath = [ os.getcwd() ]

    quiet = args.get('--quiet')
    ensure_paths(GOENV_CACHE_HOME, GOENV_CONFIG_HOME, GOLANG_DISTRIBUTIONS_DIR, quiet=quiet)

    platforms = {
            "linux": Linux,
            "darwin": MacOSX,
            "freebsd": FreeBSD
    }

    for key in platforms:
        if sys.platform.startswith(key):
            impl = platforms.get(key)
            break
    else:
        message("Your platform '{}' is not supported, sorry!".format(sys.platform), sys.stderr, quiet)

    install_only = args.get('--install-only')
    impl(version, *gopath, install_only=install_only, quiet=quiet).go()
Exemplo n.º 7
0
def generate_sygus(syntax, l, sc, constraint):
    substitutions = {}
    substitutions["<syntax>"] = syntax
    substitutions["<l>"] = l
    substitutions["<SC>"] = sc
    result = utils.substitute(skeleton, substitutions)
    result = result + constraint + "\n"
    result = result + check_synth + "\n"
    return result
Exemplo n.º 8
0
 def subst(self,v,a):
     if self == v:
         return a
     else:
         newargs = []
         for arg in self.comps.args:
             if arg == v: newargs.append(a)
             elif isinstance(arg,str): newargs.append(arg)
             else: newargs.append(substitute(arg,v,a))      #arg.subst(v,a))
         return PType(self.comps.pred,newargs)
Exemplo n.º 9
0
 def run(self, env):
     folder = env["WORK_DIR"]
     absfile = os.path.join(folder, self.file)
     
     logging.info("Creating file " + str(absfile))
     
     with open(absfile, 'w') as file:
         file.write(utils.substitute(self.content, env))
     
     logging.info("Successfully created file")
Exemplo n.º 10
0
 def run(self, env):
     if "SOCKET" not in env:
         logging.error("SOCKET not defined, call Connect first")
         raise TaskError("SOCKET not defined, call Connect first")
     
     s = env["SOCKET"]
     formatted_msg = utils.substitute(self.message, env)
     logging.info("Sending " + formatted_msg)
     s.sendall(formatted_msg)
     logging.info("Successfully sent message")
Exemplo n.º 11
0
 def subst(self, v, a):
     if self == v:
         return a
     else:
         newargs = []
         for arg in self.comps.args:
             if arg == v: newargs.append(a)
             elif isinstance(arg, str): newargs.append(arg)
             else: newargs.append(substitute(arg, v, a))  #arg.subst(v,a))
         return PType(self.comps.pred, newargs)
Exemplo n.º 12
0
 def subst(self,v,a):
     res = Rec()
     for l in self.__dict__.keys():
         lval = self.__getattribute__(l)
         if lval == v:
             res.addfield(l,a)
         elif isinstance(lval,str):
             res.addfield(l,lval)
         else: 
             res.addfield(l,substitute(lval,v,a))
     return res
Exemplo n.º 13
0
 def subst(self,v,a):
     res = RecType()
     for l in self.comps.__dict__.keys():
         if self.comps.__getattribute__(l) == v:
             res.addfield(l,a)
         elif isinstance(self.comps.__getattribute__(l),str):
             res.addfield(l,self.comps.__getattribute__(l))
         else: 
             res.addfield(l,substitute(self.comps.__getattribute__(l),v,a))
     #print(show(res))
     return res
Exemplo n.º 14
0
 def subst(self,v,a):
     res = RecType()
     for l in self.comps.__dict__.keys():
         if self.comps.__getattribute__(l) == v:
             res.addfield(l,a)
         elif isinstance(self.comps.__getattribute__(l),str):
             res.addfield(l,self.comps.__getattribute__(l))
         else: 
             res.addfield(l,substitute(self.comps.__getattribute__(l),v,a))
     #print(show(res))
     return res
Exemplo n.º 15
0
 def subst(self, v, a):
     res = Rec()
     for l in self.__dict__.keys():
         lval = self.__getattribute__(l)
         if lval == v:
             res.addfield(l, a)
         elif isinstance(lval, str):
             res.addfield(l, lval)
         else:
             res.addfield(l, substitute(lval, v, a))
     return res
Exemplo n.º 16
0
 def run(self, env):
     if "STDIN" not in env:
         logging.error("STDIN not defined, run Execute first")
         raise TaskError("STDIN not defined, run Execute first")
     
     formatted_input = utils.substitute(self.input, env)
     
     logging.info("Sending input to stdin: " + formatted_input)
     stdin = env["STDIN"]
     stdin.write(formatted_input)
     stdin.flush()
Exemplo n.º 17
0
def get_rid_of_commands(prefixes, template):
    result = template
    for prefix in prefixes:
        parens = utils.find_parens(result)
        prefix_indexes = utils.find_all(result, prefix)
        subs = {}
        for index in prefix_indexes:
            start = index
            end = parens[start]
            command = result[start:end + 1]
            subs[command] = ""
        result = utils.substitute(result, subs)
    return result
Exemplo n.º 18
0
 def app(self,arg):
     if self.var == self.body: 
         return arg
     else: 
         res = substitute(self.body,self.var,arg)
         if 'cache' in dir(res) and not isinstance(arg,HypObj):
             return res.cache() #This conditional not used?
         elif 'eval' in dir(res):
             return res.eval()
         # elif isinstance(res,HypObj):
         #     res.depends_on.append(arg)
         #     return res
         else:
             return res
Exemplo n.º 19
0
 def app(self, arg):
     if self.var == self.body:
         return arg
     else:
         res = substitute(self.body, self.var, arg)
         if 'cache' in dir(res) and not isinstance(arg, HypObj):
             return res.cache()  #This conditional not used?
         elif 'eval' in dir(res):
             return res.eval()
         # elif isinstance(res,HypObj):
         #     res.depends_on.append(arg)
         #     return res
         else:
             return res
Exemplo n.º 20
0
def generate_content_rtl(name, template, new_l, new_SC, directory, ind):
    assertion = "assertion_rtl"
    if ind:
        assertion = assertion + "_ind"
    content = utils.substitute(template, {
        l_PH: new_l,
        SC_PH: new_SC,
        assertion_PH: assertion
    })
    content = remove_ltr_stuff(content)
    content = massage(content, new_l, new_SC, directory)
    content = set_logic(content, directory, "exists" not in new_SC)
    if is_rec(directory):
        content = massage_rec(content)
    return content
Exemplo n.º 21
0
 def run(self, env):
     import json
     sub_map = {}
     
     for key,value in self.json.iteritems():
         if isinstance(value, str):
             value = utils.substitute(value, env)
             
             if key in self.conversions:
                 value = self.conversions[key](value)
             
         sub_map[key] = value
         
     with open(self.filename, "w") as f:
         json.dump(sub_map, f)
Exemplo n.º 22
0
    def extract(self, content: str) -> List[str]:
        mrz_size: int = self.size()
        formatted: str = ''.join(content.split()).upper()
        preprocessed: str = self.preprocess(formatted)
        processed: str = substitute(preprocessed, mrz_size, _default_separator)

        output: list = []

        for index in range(self.lines):
            start: int = index * self.line_size
            end: int = start + self.line_size
            chunk: str = processed[start:end]

            while len(chunk) > 0 and chunk[0] == _default_separator:
                chunk = chunk[1:]

            if self.line_size - len(chunk) > 0:
                chunk: str = substitute(chunk, self.line_size, _default_separator)
                difference: int = self.line_size - len(chunk)
                chunk: str = chunk + (difference * _default_separator) if difference > 0 else chunk

            output.append(chunk)

        return output
Exemplo n.º 23
0
def gen_no_inv(name, template, new_l, new_SC, directory, ind):
    assertion = "assertion_ltr"
    if ind:
        assertion = assertion + "_ind"
    l_part = EXISTENTIAL_L
    content = utils.substitute(template, {
        l_PH: new_l,
        SC_PH: new_SC,
        assertion_PH: assertion,
        l_part_PH: l_part
    })
    content = remove_rtl_stuff(content)
    content = set_logic(content, directory, False)
    content = massage(content, new_l, new_SC, directory)
    if is_rec(directory):
        content = massage_rec(content)
    return content
Exemplo n.º 24
0
def gen_with_inv(name, template, new_l, new_SC, inv, directory, ind):
    assertion = "assertion_ltr"
    if ind:
        assertion = assertion + "_ind"
    l_part, extra_definition = get_l_part_and_extra_definition(name, inv)
    content = utils.substitute(template, {
        l_PH: new_l,
        SC_PH: new_SC,
        assertion_PH: assertion,
        l_part_PH: l_part
    })
    content = add_extra_definition_to_content(content, extra_definition)
    content = remove_rtl_stuff(content)
    content = set_logic(content, directory, True)
    content = massage(content, new_l, new_SC, directory)
    if is_rec(directory):
        content = massage_rec(content)
    return content
Exemplo n.º 25
0
 def run(self, env):
     if "OCTAVE_ENGINE" not in env:
         logging.error("OCTAVE_ENGINE not defined")
         raise TaskError("OCTAVE_ENGINE not defined")
      
     engine = env["OCTAVE_ENGINE"]
     input_strs = []
     
     # If input argument is a variable, push into Octave's memory.
     # Otherwise, pass the input argument directly in the command.
     for arg in self.input:
         key = utils.get_substitution_key(arg, env)
         if key:
             engine.push(key, env[key])
             input_strs.append(key)
             logging.info("Pushing variable " + key + " to Octave with value " + str(env[key]))
         elif isinstance(arg, str) and arg in env:
             logging.info("Pushing variable " + arg + " to Octave with value " + str(env[arg]))
             engine.push(arg, env[arg])
             input_strs.append(arg)
         elif isinstance(arg, str):
             input_strs.append(utils.substitute(arg, env))
         else:
             input_strs.append(str(arg))
             
     # Build the command
     command = ""
     
     if len(self.output) > 0:
         command += "["
         command += ",".join(self.output)
         command += "] = "
         
     command += self.name
     command += "("
     command += ",".join(input_strs)
     command += ");"
     
     logging.info("Evaluating within Octave: " + command)
     engine.eval(command)
      
     for arg in self.output:
         env[arg] = engine.pull(arg)
         logging.info("Pulled variable " + arg + " from Octave with value " + str(env[arg]))
Exemplo n.º 26
0
    def run(self, env):
        command = utils.substitute(self.command, env)
        
        logging.info("Executing command " + command)
        process = subprocess.Popen(shlex.split(command),
                                   stdin=subprocess.PIPE,
                                   stdout=None if self.ignore_stdout else subprocess.PIPE,
                                   stderr=None if self.ignore_stderr else subprocess.PIPE)
        
        env["PROCESS"] = process
        env["STDIN"] = process.stdin
        
        if not self.ignore_stdout:
            env["STDOUT"] = process.stdout
            
        if not self.ignore_stderr:
            env["STDERR"] = process.stderr
        
        Thread(target=utils.process_monitor, args=(process,), kwargs={ "timeout":self.timeout }).start()

        logging.info("Successfully executed command")
Exemplo n.º 27
0
 def run(self, env):
     if "OCTAVE_ENGINE" not in env:
         logging.error("OCTAVE_ENGINE not defined")
         raise TaskError("OCTAVE_ENGINE not defined")
      
     engine = env["OCTAVE_ENGINE"]
     env_key = utils.get_substitution_key(self.value, env)
     
     if env_key:
         engine.push(self.key, env[env_key])
         logging.info("Pushing variable " + self.key + " to Octave with value " + str(env[env_key]))
     elif isinstance(self.value, str) and self.value in env:
         engine.push(self.key, env[self.value])
         logging.info("Pushing variable " + self.key + " to Octave with value " + str(env[self.value]))
     elif isinstance(self.value, str):
         value = utils.substitute(self.value, env)
         engine.push(self.key, value)
         logging.info("Pushing variable " + self.key + " to Octave with value " + str(value))
     else:
         engine.push(self.key, self.value)
         logging.info("Pushing variable " + self.key + " to Octave with value " + str(self.value))
Exemplo n.º 28
0
 def subst(self,v,a):
     if self == v:
         return a
     else: return ListType(substitute(self.comps.base_type,v,a))
Exemplo n.º 29
0
 def subst(self, v, a):
     if self.var == v:
         return self  # v is bound and not replaced
     else:
         return Fun(self.var, substitute(self.domain_type, v, a),
                    substitute(self.body, v, a))
Exemplo n.º 30
0
    message = 'UBXBAGCXAZYHBAZHBYAGCXDBEFBA'
    print(frequency_analysis(message))
    print(frequency_analysis(message, pattern_length=2))
    print(message)
    message = substitute(
        message,
        get_reversed_dict({
            'H': 'X',
            'O': 'Z',
            'E': 'B',
            'N': 'A',
            # 'F': 'H',
            'A': 'G',
            'C': 'C',
            # 'Z': 'Z',
            # 'Y': 'Y',
            # 'L': 'L',
            # 'C': 'S',
            # 'E': 'E',
            'G': 'U',
            'R': 'Y',
            'D': 'H',
            'W': 'D',
            'S': 'E',
            'T': 'F',
        }))
    print(message)

    message = 'ELIERAMASSEMESFLEURS'
    print(message, "=>", CaesarCypher(-2).encrypt(message))
    message = 'CENESTPASMATASSEDETHE'
Exemplo n.º 31
0
 def subst(self, v, a):
     self.oplist = substitute(self.oplist, v, a)
     return self.eval()
Exemplo n.º 32
0
 def subst(self,v,a):
     self.oplist = substitute(self.oplist,v,a)
     return self.eval()
Exemplo n.º 33
0
 def subst(self, v, a):
     return AbsPath(substitute(self.rec, v, a), substitute(self.path, v, a))
Exemplo n.º 34
0
 def subst(self,v,a):
     if self.var == v:
         return self  # v is bound and not replaced
     else: return Fun(self.var,substitute(self.domain_type,v,a),substitute(self.body,v,a))
Exemplo n.º 35
0
 def subst(self,v,a):
     if self == v:
         return a
     else:
         return TTRStringType(substitute(self.comps.types,v,a))
Exemplo n.º 36
0
 def subst(self,v,a):
     if self == v:
         return a
     else:
         return KPlusStringType(substitute(self.comps.base_type,v,a))
Exemplo n.º 37
0
 def subst(self, v, a):
     if self == v:
         return a
     else:
         return SingletonType(substitute(self.comps.base_type, v, a),
                              substitute(self.comps.obj, v, a))
Exemplo n.º 38
0
 def subst(self, v, a):
     if self == v:
         return a
     else:
         return TTRStringType(substitute(self.comps.types, v, a))
Exemplo n.º 39
0
 def subst(self, v, a):
     if self == v:
         return a
     else:
         return KPlusStringType(substitute(self.comps.base_type, v, a))
Exemplo n.º 40
0
def translate(definition):
    return utils.substitute(definition, substitutions)
Exemplo n.º 41
0
 def subst(self,v,a):
     return AbsPath(substitute(self.rec,v,a),substitute(self.path,v,a))
Exemplo n.º 42
0
 def subst(self, v, a):
     if self == v:
         return a
     else:
         return ListType(substitute(self.comps.base_type, v, a))
Exemplo n.º 43
0
 def subst(self,v,a):
     if self == v:
         return a
     else: return SingletonType(substitute(self.comps.base_type,v,a),substitute(self.comps.obj,v,a))