Example #1
0
def do_decypher(text, codec=DEFAULT, length=8):
    """
    Function to convert Gray code into text.
    Note: expect "unspaced" binary text as input!
    """
    mapp = gray2bin_n(length)

    bytes = "".join(mapp[chunk] for chunk in utils.grouper2(text, length))
    # We want to get back to real bytes, hence stripping down dummy '0' we
    # added at encode time to get an integer number of length-words.
    new_len = len(bytes)
    new_len -= new_len % 8
    bytes = bytes[:new_len]
    # And now, convert those textual bytes back to real bytes!
    bytes = utils.int8_to_bytes(int(c, 2) for c in utils.grouper2(bytes, 8))
    return bytes.decode(codec)
Example #2
0
def decypher(text, o_stght=True, o_rev=False):
    """Wrapper around do_decypher, making some checks."""
    if not text:
        raise Exception("No text given!")
    # Check length...
    if ((len(text) + 1) % 7):
        raise Exception("Text has a wrong length (must be a multiple of "
                        "seven minus one (current length: {})."
                        "".format(len(text)))
    # Check for unallowed chars...
    c_text = set(text)
    c_allowed1 = {CHAR1, CHAR2, ' '}
    c_allowed2 = {CHAR1, CHAR3, ' '}
    if not (c_text <= c_allowed1 or c_text <= c_allowed2):
        raise Exception("Text contains unallowed chars (only pipes and "
                        "spaces/dots chars are allowed): '{}' or '{}'!"
                        "".format("', '".join(sorted(c_text - c_allowed1)),
                                  "', '".join(sorted(c_text - c_allowed2))))
    # Check for invalid codes...
    c_text = set(utils.grouper2(text, 6, 1))
    if CHAR2 in text:
        c_allowed = set(RO_MAP.keys())
    else:
        c_allowed = set(RC_MAP.keys())
    if not (c_text <= c_allowed):
        raise Exception("Text contains unknown codes: '{}'!"
                        "".format("', '".join(sorted(c_text - c_allowed))))
    return do_decypher(text, o_stght=o_stght, o_rev=o_rev)
Example #3
0
def decypher(text, o_stght=True, o_rev=False):
    """Wrapper around do_decypher, making some checks."""
    if not text:
        raise Exception("No text given!")
    # Check length...
    if ((len(text) + 1) % 7):
        raise Exception("Text has a wrong length (must be a multiple of "
                        "seven minus one (current length: {})."
                        "".format(len(text)))
    # Check for unallowed chars...
    c_text = set(text)
    c_allowed1 = {CHAR1, CHAR2, ' '}
    c_allowed2 = {CHAR1, CHAR3, ' '}
    if not (c_text <= c_allowed1 or c_text <= c_allowed2):
        raise Exception("Text contains unallowed chars (only pipes and "
                        "spaces/dots chars are allowed): '{}' or '{}'!"
                        "".format("', '".join(sorted(c_text - c_allowed1)),
                                  "', '".join(sorted(c_text - c_allowed2))))
    # Check for invalid codes...
    c_text = set(utils.grouper2(text, 6, 1))
    if CHAR2 in text:
        c_allowed = set(RO_MAP.keys())
    else:
        c_allowed = set(RC_MAP.keys())
    if not (c_text <= c_allowed):
        raise Exception("Text contains unknown codes: '{}'!"
                        "".format("', '".join(sorted(c_text - c_allowed))))
    return do_decypher(text, o_stght=o_stght, o_rev=o_rev)
Example #4
0
File: gray.py Project: 47-/Cyprium
def do_decypher(text, codec=DEFAULT, length=8):
    """
    Function to convert Gray code into text.
    Note: expect "unspaced" binary text as input!
    """
    mapp = gray2bin_n(length)

    bytes = "".join(mapp[chunk] for chunk in utils.grouper2(text, length))
    # We want to get back to real bytes, hence stripping down dummy '0' we
    # added at encode time to get an integer number of length-words.
    new_len = len(bytes)
    new_len -= new_len % 8
    bytes = bytes[:new_len]
    # And now, convert those textual bytes back to real bytes!
    bytes = utils.int8_to_bytes(int(c, 2) for c in utils.grouper2(bytes, 8))
    return bytes.decode(codec)
Example #5
0
def _process_hack_vigenere(text, algo, key_length, language,
                                        limit=10, ratio=0.75):
    '''return a possibly key for the given text,
    the key's length == key_length'''
    groups = list(utils.grouper2(text, key_length))
    if algo==ALGO_BEAUFORT:
        map = reverse_b_square
        _process = _process_beaufort
    elif algo==ALGO_GRONSFELD:
        map = reverse_g_square
        _process = _process_vigenere
    else:
        map = reverse_v_square
        _process = _process_vigenere
    keys = []
    result = []
    tmp_limit = limit
    for i in range(key_length):
        limit = tmp_limit
        char = []
        ls =  []
        for item in groups:
            if len(item)>i:
                ls.append(item[i])
        most_chars = order(ls, limit=26)
        vars = []
        #this tuple represents the probabilities:
        #use two times the first char, 1 time the second...
        probas = ((6, 0), (1, 1))
        for item in probas:
            for i in range(item[0]):
                vars.append( map[STATS[language][item[1]]][most_chars[i]])
        lst = []
        for k in vars:
            if (("J">= k and algo==ALGO_GRONSFELD) or algo!=ALGO_GRONSFELD):
                cur = "".join(_process(STATS[language][:limit], k))
                if get_ratio(cur, most_chars[:limit]) >= ratio:
                    if k not in char:
                        char.append(k)
        if not char:
            lst_keys = []
            limit = 10
            lst = _find_k(most_chars, language, limit, map)
            lst_keys.extend(lst)

            limit = 20
            lst = []
            for c in vars:
                lst.append((_count(c, most_chars, language, limit, map), c))
            lst = _get_mosts(lst)
            lst_keys.extend(lst)
            lst = []
            for c in set(lst_keys):
                lst.append((lst_keys.count(c), c))
            lst = _get_mosts(lst)
            char.append(lst[0])
        keys.append(vars)
        result.append(char)
    return result
Example #6
0
def do_decypher(text, base=1):
    """
    Decypher message to triliteral (with optional base, shift)
    ABA --> 'd' (base 0), ABA --> 'j' (base 7)
    """
    base -= 1
    R_MAP = {utils.num_to_base((k - base) % 26, ('A', 'B', 'C'), 3): v
                               for k, v in enumerate(CHARS)}
    return "".join((R_MAP[c] for c in utils.grouper2(text, 3)))
Example #7
0
def do_decypher(text, base=1):
    """
    Decypher message to triliteral (with optional base, shift)
    ABA --> 'd' (base 0), ABA --> 'j' (base 7)
    """
    base -= 1
    R_MAP = {
        utils.num_to_base((k - base) % 26, ('A', 'B', 'C'), 3): v
        for k, v in enumerate(CHARS)
    }
    return "".join((R_MAP[c] for c in utils.grouper2(text, 3)))
Example #8
0
def do_decypher(text, o_stght=True, o_rev=False):
    """Function to convert postal barcode text into clear text.
       Note that method (original or classical) is auto-detected,
       but you still need to provide the desired order(s).
       Returns a list of one or two decyphered texts:
           [o_stght, o_rev]
    """
    ret = []
    if CHAR2 in text:
        # Original method.
        m = RO_MAP
    else:
        # Classical method.
        m = RC_MAP
    lcar = []
    for code in utils.grouper2(text, 6, 1):
        lcar.append(m[code])
    if o_stght:
        ret.append("".join(lcar))
    if o_rev:
        ret.append("".join(reversed(lcar)))
    return ret
Example #9
0
def do_decypher(text, o_stght=True, o_rev=False):
    """Function to convert postal barcode text into clear text.
       Note that method (original or classical) is auto-detected,
       but you still need to provide the desired order(s).
       Returns a list of one or two decyphered texts:
           [o_stght, o_rev]
    """
    ret = []
    if CHAR2 in text:
        # Original method.
        m = RO_MAP
    else:
        # Classical method.
        m = RC_MAP
    lcar = []
    for code in utils.grouper2(text, 6, 1):
        lcar.append(m[code])
    if o_stght:
        ret.append("".join(lcar))
    if o_rev:
        ret.append("".join(reversed(lcar)))
    return ret
Example #10
0
def decypher(text):
    """Just a wrapper around do_decypher, with some checks."""
    if not text:
        raise ValueError("No text given!")
    # Check for unallowed chars…
    c_text = set(text)
    c_allowed = {'A', 'B'}
    if not (c_text <= c_allowed):
        raise ValueError("Text contains unallowed chars (only A and B "
                         "are allowed): '{}'!"
                         "".format("', '".join(sorted(c_text - c_allowed))))
    # Check for length.
    if len(text) % 5:
        raise ValueError("Text must contains an integer number of groups of "
                         "five chars (current length: {})…"
                         "".format(len(text)))
    # Check for valid triliteral codes.
    c_text = {c for c in utils.grouper2(text, 5)}
    c_allowed = set(R_MAP.keys())
    if not (c_text <= c_allowed):
        raise ValueError("Text contains invalid biliteral codes: '{}'!"
                         "".format("', '".join(sorted(c_text - c_allowed))))
    return do_decypher(text)
Example #11
0
def decypher(text, base=1):
    """Just a wrapper around do_decypher, with some checks."""
    if not text:
        raise ValueError("No text given!")
    # Check for unallowed chars…
    c_text = set(text)
    c_allowed = {'A', 'B', 'C'}
    if not (c_text <= c_allowed):
        raise ValueError("Text contains unallowed chars (only A and B "
                         "are allowed): '{}'!"
                         "".format("', '".join(sorted(c_text - c_allowed))))
    # Check for length.
    if len(text) % 3:
        raise ValueError("Text must contains an integer number of groups of "
                         "three chars (current length: {})…"
                         "".format(len(text)))
    # Check for valid triliteral codes.
    c_text = {c for c in utils.grouper2(text, 3)}
    c_allowed = CODES
    if not (c_text <= c_allowed):
        raise ValueError("Text contains invalid triliteral codes: '{}'!"
                         "".format("', '".join(sorted(c_text - c_allowed))))
    return do_decypher(text, base=base)
Example #12
0
 def ook2opc(self, code):
     """Convert ook to opcode."""
     # Convert full ook to fast one.
     code = code.lower().replace("ook", '')
     code = code.replace(' ', '')
     return [(self.FROM_OOK[opc], None) for opc in utils.grouper2(code, 2)]
Example #13
0
def do_decypher(text):
    """
    Decypher message to triliteral (with optional base, shift)
    AAABB --> 'd'
    """
    return "".join((R_MAP[c] for c in utils.grouper2(text, 5)))
Example #14
0
def do_decypher(text):
    """
    Decypher message to triliteral (with optional base, shift)
    AAABB --> 'd'
    """
    return "".join((R_MAP[c] for c in utils.grouper2(text, 5)))
Example #15
0
def _process_hack_vigenere(text,
                           algo,
                           key_length,
                           language,
                           limit=10,
                           ratio=0.75):
    '''return a possibly key for the given text,
    the key's length == key_length'''
    groups = list(utils.grouper2(text, key_length))
    if algo == ALGO_BEAUFORT:
        map = reverse_b_square
        _process = _process_beaufort
    elif algo == ALGO_GRONSFELD:
        map = reverse_g_square
        _process = _process_vigenere
    else:
        map = reverse_v_square
        _process = _process_vigenere
    keys = []
    result = []
    tmp_limit = limit
    for i in range(key_length):
        limit = tmp_limit
        char = []
        ls = []
        for item in groups:
            if len(item) > i:
                ls.append(item[i])
        most_chars = order(ls, limit=26)
        vars = []
        #this tuple represents the probabilities:
        #use two times the first char, 1 time the second...
        probas = ((6, 0), (1, 1))
        for item in probas:
            for i in range(item[0]):
                vars.append(map[STATS[language][item[1]]][most_chars[i]])
        lst = []
        for k in vars:
            if (("J" >= k and algo == ALGO_GRONSFELD)
                    or algo != ALGO_GRONSFELD):
                cur = "".join(_process(STATS[language][:limit], k))
                if get_ratio(cur, most_chars[:limit]) >= ratio:
                    if k not in char:
                        char.append(k)
        if not char:
            lst_keys = []
            limit = 10
            lst = _find_k(most_chars, language, limit, map)
            lst_keys.extend(lst)

            limit = 20
            lst = []
            for c in vars:
                lst.append((_count(c, most_chars, language, limit, map), c))
            lst = _get_mosts(lst)
            lst_keys.extend(lst)
            lst = []
            for c in set(lst_keys):
                lst.append((lst_keys.count(c), c))
            lst = _get_mosts(lst)
            char.append(lst[0])
        keys.append(vars)
        result.append(char)
    return result