コード例 #1
0
ファイル: views.py プロジェクト: Shobhit-pandey/Kryptism
def substitution_cipher(request):
    from pycipher import SimpleSubstitution as SimpleSub
    import random
    import re
    from decryptionwithoutkey.ngram_score import ngram_score
    fitness = ngram_score('english_quadgrams.txt')  # load our quadgram statistics
    if request.method == 'POST':
        form = CryptoAnalysis(request.POST)
        if form.is_valid():
            cipher = request.POST['input']
            cipher = str(cipher)
            ctext = cipher.upper()
            ctext = re.sub('[^A-Z]', '', ctext.upper())
            maxkey = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
            maxscore = -99e9
            parentscore, parentkey = maxscore, maxkey[:]
            print("Substitution Cipher solver, you may have to wait several iterations")
            print("for the correct result. Press ctrl+c to exit program.")
            # keep going until we are killed by the user
            i = 0
            k = 0
            best_key = ''
            plaintext = ''
            while k < 30:
                i = i + 1
                random.shuffle(parentkey)
                deciphered = SimpleSub(parentkey).decipher(ctext)
                parentscore = fitness.score(deciphered)
                count = 0
                while count < 1000:
                    a = random.randint(0, 25)
                    b = random.randint(0, 25)
                    child = parentkey[:]
                    # swap two characters in the child
                    child[a], child[b] = child[b], child[a]
                    deciphered = SimpleSub(child).decipher(ctext)
                    score = fitness.score(deciphered)
                    # if the child was better, replace the parent with it
                    if score > parentscore:
                        parentscore = score
                        parentkey = child[:]
                        count = 0
                    count = count + 1
                # keep track of best score seen so far
                k += 1
                if parentscore > maxscore:
                    maxscore, maxkey = parentscore, parentkey[:]
                    print('\nbest score so far:', maxscore, 'on iteration', i)
                    ss = SimpleSub(maxkey)
                    best_key = ''.join(maxkey)
                    plaintext = ss.decipher(ctext)
                    # print('    best key: ' + ''.join(maxkey))
                    # print('    plaintext: ' + ss.decipher(ctext))
                    return render(request, 'dwok/substution.html', {'form': form,'key':best_key,'plain':plaintext})
            # return HttpResponse("KEY = " + str(best_key) + " \nPLAIN TEXT =   " + plaintext)
        else:
            return HttpResponse("Form is not valid")
    else:
        form = CryptoAnalysis()
    return render(request, 'dwok/substution.html', {'form': form})
コード例 #2
0
def test_substitution_cipher(text, max_iterations):
    fitness = ngram_score(
        'english_quadgrams.txt')  # load our quadgram statistics
    ctext = re.sub('[^A-Z]', '', text.upper())

    maxkey = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
    maxscore = -99e9
    parentscore, parentkey = maxscore, maxkey[:]
    for i in range(0, max_iterations):
        random.shuffle(parentkey)
        deciphered = SimpleSub(parentkey).decipher(ctext)
        parentscore = fitness.score(deciphered)
        count = 0
        while count < 1000:
            a = random.randint(0, 25)
            b = random.randint(0, 25)
            child = parentkey[:]
            # swap two characters in the child
            child[a], child[b] = child[b], child[a]
            deciphered = SimpleSub(child).decipher(ctext)
            score = fitness.score(deciphered)
            # if the child was better, replace the parent with it
            if score > parentscore:
                parentscore = score
                parentkey = child[:]
                count = 0
            count = count + 1
        # keep track of best score seen so far
        if parentscore > maxscore:
            maxscore, maxkey = parentscore, parentkey[:]
    return maxscore, maxkey, SimpleSub(maxkey).decipher(ctext)
コード例 #3
0
def hack(ctext):
    fitness = scorer.scorer('quads.txt')
    maxkey = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
    maxscore = -99999999999
    parentscore, parentkey = maxscore, maxkey[:]
    i = 0
    delta = 0.1
    while i < 1000:
        i = i + 1
        random.shuffle(parentkey)
        deciphered = SimpleSub(parentkey).decipher(ctext)
        parentscore = fitness.score(deciphered)
        count = 0
        while count < 1000:
            a = random.randint(0, 25)
            b = random.randint(0, 25)
            child = parentkey[:]
            # swap two characters in the child
            child[a], child[b] = child[b], child[a]
            deciphered = SimpleSub(child).decipher(ctext)
            score = fitness.score(deciphered)
            # if the child was better, replace the parent with it
            if score > parentscore:
                parentscore = score
                parentkey = child[:]
                count = 0
            count = count + 1
        # keep track of best score seen so far
        if parentscore > maxscore:
            maxscore, maxkey = parentscore, parentkey[:]
        if math.fabs(parentscore - maxscore) <= delta:
            break
    return maxkey
コード例 #4
0
def decipher(ctext, flag, length, floor, which, dicnum):
    file = open('Plaintext/Result.txt', 'w')
    if (dicnum == '3'):
        ngram = trigram
    elif (dicnum == '4'):
        ngram = quadgram
    print("\nDeciphering^_^")
    t_Start = time.time()
    max_key = list(string.ascii_uppercase)
    max_score = -99e9
    while str(SimpleSub(max_key).decipher(flag)) != "TOLPKTEHDCISSZQ":
        max_key = list(string.ascii_uppercase)
        max_score = -99e9
        parentscore, parentkey = max_score, max_key[:]
        random.shuffle(parentkey)
        deciphering = SimpleSub(parentkey).decipher(ctext)
        parentscore = 0
        for x in range(len(deciphering) - length + 1):
            if deciphering[x:x + length] in ngram:
                parentscore += ngram[deciphering[x:x + length]]
            else:
                parentscore += floor
        cnt = 0
        while cnt < 1000:
            a = random.randint(0, 25)
            b = random.randint(0, 25)
            child = parentkey[:]
            child[a], child[b] = child[b], child[a]
            deciphering = SimpleSub(child).decipher(ctext)
            score = 0
            for x in range(len(deciphering) - length + 1):
                if deciphering[x:x + length] in ngram:
                    score += ngram[deciphering[x:x + length]]
                else:
                    score += floor
            if score > parentscore:
                parentscore = score
                parentkey = child[:]
                cnt = 0
            cnt = cnt + 1
        if parentscore > max_score:
            max_score, max_key = parentscore, parentkey[:]
    t_End = time.time()
    print("\nFinish Decipher ^_^\n")
    print("Total time:", int(t_End - t_Start), 's')
    print("\nSubsituition table:")
    print("==========================")
    print("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
    print('' + ''.join(max_key))
    print("==========================")
    print('Plain text of Cipher:' + which + ".txt is in Plaintext/Result.txt")
    file.write(SimpleSub(max_key).decipher(ctext))
    print('\nFlag of 105062226 ^_^: ' + SimpleSub(max_key).decipher(flag))
コード例 #5
0
def word_decrypt_sub(word):
    fitness = ngram_score('english_quadgrams.txt') # load our quadgram statistics

    ctext = word
    ctext = re.sub('[^A-Z]', '', ctext.upper())

    maxkey = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
    maxscore = -99e9 # First generated key will always replace this
    parentscore, parentkey = maxscore, maxkey[:]
    # keep going until we are killed by the user
    i = 0
    while (True):
        i = i + 1
        random.shuffle(parentkey)
        # SimpleSub will replace the 'abc...' with the key e.g 'dje...'
        deciphered = SimpleSub(parentkey).decipher(ctext)
        parentscore = fitness.score(deciphered)

        # If there are no improvement then we move to a different set of keys
        # Checking for improvements within 1000 iterations
        count = 0
        while count < 1000:
            a = random.randint(0, 25)
            b = random.randint(0, 25)
            child = parentkey[:]

            # swap two characters in the child
            child[a], child[b] = child[b], child[a]
            deciphered = SimpleSub(child).decipher(ctext)
            score = fitness.score(deciphered)
            # if the child was better, replace the parent with it
            if score > parentscore:
                parentscore = score
                parentkey = child[:]
                count = 0
            count = count + 1
        # keep track of best score seen so far
        if parentscore > maxscore:
            maxscore, maxkey = parentscore, parentkey[:]
            print ('\nbest score so far:',maxscore,'on iteration',i)
            ss = SimpleSub(maxkey)
            print ('    best key: ' + ''.join(maxkey))
            print ('    plaintext: ' + ss.decipher(ctext))
コード例 #6
0
def substitutionAttack(text_ut, ngrams_file, iter, x):
    global Ctext
    global bestIndv
    global maxscore
    Ctext = re.sub('[^A-Z]', '', text_ut.upper())
    ngrams(ngrams_file)
    for i in range(0, iter):
        currentKey, currentScore = StochasticHillClimbing(x)
        if currentScore > maxscore:
            maxkey = currentKey[:]
            maxscore = currentScore
            plainText = SimpleSub(maxkey).decipher(Ctext)
            print(maxscore)
            print(plainText)
コード例 #7
0
def SubsCracker(ctext, ngram):

    fitness = ngram_score(ngram)

    ctext = re.sub('[^A-Z]', '', ctext.upper())

    maxkey = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
    maxscore = -99e9
    parentscore, parentkey = maxscore, maxkey[:]
    i = 0
    print(
        '\033[1;34m[*]\033[0m Cracking the cipher. This might take a while...')
    while 1:
        i = i + 1
        random.shuffle(parentkey)
        deciphered = SimpleSub(parentkey).decipher(ctext)
        parentscore = fitness.score(deciphered)
        count = 0
        while count < 1000:
            a = random.randint(0, 25)
            b = random.randint(0, 25)
            child = parentkey[:]
            child[a], child[b] = child[b], child[a]
            deciphered = SimpleSub(child).decipher(ctext)
            score = fitness.score(deciphered)
            if score > parentscore:
                parentscore = score
                parentkey = child[:]
                count = 0
            count = count + 1
        if parentscore > maxscore:
            maxscore, maxkey = parentscore, parentkey[:]
            print('\n\033[1;34m[*]\033[0m Best score so far: ' +
                  str(maxscore) + ' on iteration ' + str(i))
            ss = SimpleSub(maxkey)
            print('    \033[1;32m[+]\033[0m Best key: ' + ''.join(maxkey))
            print('    \033[1;32m[+]\033[0m Plaintext: ' + ss.decipher(ctext))
コード例 #8
0
fitness = NgramScore('english_quadgrams.txt')

ctext = 'pmpafxaikkitprdsikcplifhwceigixkirradfeirdgkipgigudkcekiigpwrpucikceiginasikwduearrxiiqepcceindgmieinpwdfprduppcedoikiqiasafmfddfipfgmdafmfdteiki'

ctext = re.sub('[^A-Z]', '', ctext.upper())

max_key = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
max_score = -99e9
parent_score, parent_key = max_score, max_key[:]
print "Substitution Cipher solver, you may have to wait several iterations"
print "Press ctrl+c to exit program."
i = 0
while 1:
    i = i + 1
    random.shuffle(parent_key)
    deciphered = SimpleSub(parent_key).decipher(ctext)
    parent_score = fitness.score(deciphered)
    count = 0
    while count < 1000:
        a = random.randint(0, 25)
        b = random.randint(0, 25)
        child = parent_key[:]
        # swap two characters in the child
        child[a], child[b] = child[b], child[a]
        deciphered = SimpleSub(child).decipher(ctext)
        score = fitness.score(deciphered)
        # if the child was better, replace the parent with it
        if score > parent_score:
            parent_score = score
            parent_key = child[:]
            count = 0
コード例 #9
0
def getStateScore(key):
    plainText = SimpleSub(key).decipher(Ctext)
    return fitnessFunction(plainText)
コード例 #10
0
ファイル: decoder.py プロジェクト: grademacher/PrimeSteg
def brute_force(input_file, output_file, iterations):
    img = Image.open(input_file)

    alphabet = [
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
        "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"
    ]
    primes = [
        2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67,
        71, 73, 79, 83, 89, 97, 101
    ]

    ary = np.array(img)
    rows = ary.shape[0]
    cols = ary.shape[1]
    depth = ary.shape[2]

    hidden_message = []

    for i in range(0, rows):
        for j in range(0, cols):
            for k in range(0, depth):
                if ary[i, j, k] < 102:
                    if is_prime(ary[i, j, k]):
                        hidden_message.append(ary[i, j, k])

    encrypted_message = ""

    for prime in hidden_message:
        encrypted_message += (alphabet[primes.index(prime)])

    ctext = encrypted_message
    ctext = re.sub('[^A-Z]', '', ctext.upper())

    maxkey = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
    maxscore = -99e9
    parentscore, parentkey = maxscore, maxkey[:]

    # keep going until we are killed by the user
    return_ary = []
    file_out = open(output_file, "w")
    file_out.write('')
    for i in range(iterations):
        i = i + 1
        random.shuffle(parentkey)
        deciphered = SimpleSub(parentkey).decipher(ctext)
        parentscore = fitness.score(deciphered)
        count = 0
        while count < 1000:
            a = random.randint(0, 25)
            b = random.randint(0, 25)
            child = parentkey[:]
            # swap two characters in the child
            child[a], child[b] = child[b], child[a]
            deciphered = SimpleSub(child).decipher(ctext)
            score = fitness.score(deciphered)
            # if the child was better, replace the parent with it
            if score > parentscore:
                parentscore = score
                parentkey = child[:]
                count = 0
            count = count + 1
        # keep track of best score seen so far
        if parentscore > maxscore:
            maxscore, maxkey = parentscore, parentkey[:]
            ss = SimpleSub(maxkey)
            if len(output_file) > 1:
                file_out = open(output_file, "a")
                file_out.write('\n\nbest score so far: ' + str(maxscore) +
                               ' on iteration ' + str(i))
                file_out.write('\n    best key: ' + ''.join(maxkey))
                file_out.write('\n    plaintext: ' + ss.decipher(ctext))
                file_out.close()
            return_ary = [0, 0, 0, 0]
            return_ary[0] = maxscore
            return_ary[1] = maxkey
            return_ary[2] = ss.decipher(ctext)
            return_ary[3] = i

    return return_ary
コード例 #11
0
def translate(text, key):
    return SimpleSub(key).decipher(text)