X-Git-Url: https://git.njae.me.uk/?a=blobdiff_plain;f=cipherbreak.py;h=f1ab58e50a4f293368ef9d5382aef9dabf590420;hb=45be1fdb2cb9ca43cdd896f771a9e830542e2325;hp=d5d3aa76422c6b0109ee91d55b482d87c66c97a0;hpb=f4abb99c8506fa85440d3ed47e8c3c0b1f9fb928;p=cipher-tools.git diff --git a/cipherbreak.py b/cipherbreak.py index d5d3aa7..f1ab58e 100644 --- a/cipherbreak.py +++ b/cipherbreak.py @@ -569,6 +569,43 @@ def hill_break_worker(message, matrix, fitness): fit, sanitise(plaintext)[:50])) return matrix, fit +def bifid_break_mp(message, wordlist=keywords, fitness=Pletters, max_period=10, + number_of_solutions=1, chunksize=500): + """Breaks a keyword substitution cipher using a dictionary and + frequency analysis + + >>> bifid_break_mp(bifid_encipher('this is a test message for the ' \ + 'keyword decipherment', 'elephant', wrap_alphabet=KeywordWrapAlphabet.from_last), \ + wordlist=['cat', 'elephant', 'kangaroo']) # doctest: +ELLIPSIS + (('elephant', , 0), -52.834575011...) + >>> bifid_break_mp(bifid_encipher('this is a test message for the ' \ + 'keyword decipherment', 'elephant', wrap_alphabet=KeywordWrapAlphabet.from_last), \ + wordlist=['cat', 'elephant', 'kangaroo'], \ + number_of_solutions=2) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE + [(('elephant', , 0), -52.834575011...), + (('elephant', , 0), -52.834575011...)] + """ + with Pool() as pool: + helper_args = [(message, word, wrap, period, fitness) + for word in wordlist + for wrap in KeywordWrapAlphabet + for period in range(max_period+1)] + # Gotcha: the helper function here needs to be defined at the top level + # (limitation of Pool.starmap) + breaks = pool.starmap(bifid_break_worker, helper_args, chunksize) + if number_of_solutions == 1: + return max(breaks, key=lambda k: k[1]) + else: + return sorted(breaks, key=lambda k: k[1], reverse=True)[:number_of_solutions] + +def bifid_break_worker(message, keyword, wrap_alphabet, period, fitness): + plaintext = bifid_decipher(message, keyword, wrap_alphabet, period=period) + fit = fitness(plaintext) + logger.debug('Keyword break attempt using key {0} (wrap={1}) gives fit of ' + '{2} and decrypt starting: {3}'.format(keyword, + wrap_alphabet, fit, sanitise(plaintext)[:50])) + return (keyword, wrap_alphabet, period), fit + def pocket_enigma_break_by_crib(message, wheel_spec, crib, crib_position): """Break a pocket enigma using a crib (some plaintext that's expected to