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})
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))
def substitution(request): form = Substitution() if request.method == 'POST': form = Substitution(request.POST) if form.is_valid(): cipher = request.POST['input'] key = request.POST['key'] cipher = str(cipher) key = str(key) ss = SimpleSubstitution(key) plain = ss.decipher(cipher) return render(request, 'dwk/substitution.html', { 'form': form, 'plain': plain }) # return HttpResponse("Plain Text: %s" % plain) else: form = Substitution() return render(request, 'dwk/substitution.html', {'form': form})
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))
i = 0 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[:] # 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)
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 count = count + 1 # keep track of best score seen so far if parent_score > max_score: max_score, max_key = parent_score, parent_key[:] print '\nbest score so far:', max_score, 'on iteration', i ss = SimpleSub(max_key) print ' best key: ' + ''.join(max_key) print ' plaintext: ' + ss.decipher(ctext)
start_time = time.time() i = 0 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[:] # Swap 2 characters in the Child Key and calculate the fitness score of deciphered text using this key child[a], child[b] = child[b], child[a] deciphered = SimpleSub(child).decipher(ctext) score = fitness.score(deciphered) # If the child has a better score - replace the parent if score > parentscore: parentscore = score parentkey = child[:] count = 0 count = count + 1 # Print out the best score gotten after this iteration if parentscore > maxscore: maxscore, maxkey = parentscore, parentkey[:] print "\nBest fitness score so far: ", maxscore, " on iteration ", i ss = SimpleSub(maxkey) print " Best Key: " + "".join(maxkey) print " Best Plaintext: " + ss.decipher(ctext) print " Time Taken: %f s" % (time.time() - start_time)
# Keep going until the program is killed start_time = time.time() i = 0 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[:] # Swap 2 characters in the Child Key and calculate the fitness score of deciphered text using this key child[a], child[b] = child[b], child[a] deciphered = SimpleSub(child).decipher(ctext) score = fitness.score(deciphered) # If the child has a better score - replace the parent if score > parentscore: parentscore = score parentkey = child[:] count = 0 count = count + 1 # Print out the best score gotten after this iteration if parentscore > maxscore: maxscore, maxkey = parentscore, parentkey[:] print '\nBest fitness score so far: ', maxscore, ' on iteration ', i ss = SimpleSub(maxkey) print ' Best Key: ' + ''.join(maxkey) print ' Best Plaintext: ' + ss.decipher(ctext) print ' Time Taken: %f s' % (time.time() - start_time)
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
def simple_sub_decipher(cipher_text): # the english_quadrams text file contains 4-count letter words with their score # their score is based on their frequency in the English language ng = ngram_score('english_quadgrams.txt') input( "The simple substitution decipher will take a while to complete. The program will terminate at a certain point. " "Please be patient\n" "Press ENTER to begin: ") cipher_text.upper() max_key = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ') # the default score max_score = -99e9 parent_key = max_key # list to store keys already used discarded_keys = [] i = 0 while True: # get a random key random.shuffle(parent_key) # use that key to decipher the ciphertext deciphered_text = SS(parent_key).decipher(cipher_text) # get the score from the deciphered text parent_score = ng.score(deciphered_text) # generate a new key new_key = parent_key[:] random.shuffle(new_key) # if a generated key was used before, then another one will be generated if new_key in discarded_keys: flag = True while flag: # the loop will continue to generate a unique key that is not already used before random.shuffle(new_key) if new_key not in discarded_keys: flag = False # new deciphered text using the new key deciphered_text = SS(new_key).decipher(cipher_text) # get the score from the new deciphered text using the new key child_score = ng.score(deciphered_text) # if the score is an improvement on the previous score if child_score > parent_score: parent_score = child_score # used keys will be put in the discarded keys list so they wouldn't be used anymore discarded_keys.append(new_key) discarded_keys.append(parent_key) # if the score is greater than the max score, then the key used is more likely to decipher the cipher text if parent_score > max_score: max_score = parent_score max_key = new_key ss = SS(max_key) print('---------------------------------------------' '\nSCORE:', max_score) print('KEY:', list_to_string(max_key)) print('DECIPHERED TEXT:', ss.decipher(cipher_text)) i += 1 # statement for ending the program after certain number of iterations if i == 50000: print('The program has run for long enough. Terminating...') break
init_time = time.time() i = 0 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[:] # 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 possible key: '+''.join(maxkey) print ' candidate plaintext: '+ss.decipher(ctext) print ' time taken to break: %fs' % (time.time() - init_time)