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 guess(self, text, n=3): result = [] for candidate in self.candidates[0:n]: key, score = candidate decryption = SimpleSubstitution(key).decipher(text) result.append((decryption, score, key)) return result
def break_substitution(plaintext, masker): # key1 = ['L', 'C', 'N', 'D', 'T', 'H', 'E', 'W', 'Z', 'S', 'A', 'R', 'X', # 'V', 'O', 'J', 'B', 'P', 'F', 'U', 'I', 'Q', 'M', 'K', 'G', 'Y'] # key1 = ['Y', 'B', 'X', 'O', 'N', 'G', 'S', 'W', 'K', 'C', 'P', 'Z', 'F', # 'M', 'T', 'D', 'H', 'R', 'Q', 'U', 'J', 'V', 'E', 'L', 'I', 'A'] # key1 = ['J', 'E', 'K', 'P', 'H', 'X', 'G', 'L', 'S', 'Z', 'R', 'T', 'C', # 'Y', 'W', 'A', 'D', 'B', 'F', 'M', 'Q', 'I', 'U', 'V', 'N', 'O'] key1 = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ') random.shuffle(key1) # print(key1) ciphertext = SimpleSubstitution(key1).encipher(plaintext) print("\nCiphertext:") print(masker.extend(ciphertext)) #print("---\n") print("\nProcessing...\n") scorer = NgramScorer(load_ngrams(1)) # breaker = SubstitutionBreak(scorer,seed = 42) breaker = SubstitutionBreak(scorer) # breaker.optimise(ciphertext, n=10) # for text # breaker.optimise(ciphertext, n=30) # for text breaker.optimise(ciphertext, n=3) # generate n local optima and choose the best decryption, score, key = breaker.guess(ciphertext)[ 0] # get the best local optima print("Substitution decryption (key={}, score={}):\n---\nPlaintext:\n{}". format(key, score, masker.extend(decryption)))
def getIteration(self, text): key = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ') random.shuffle(key) score = self.scorer.score(SimpleSubstitution(key).decipher(text)) count = 0 while count < 1000: newKey = self.swap(key) newScore = self.scorer.score( SimpleSubstitution(newKey).decipher(text)) if newScore > score: key = newKey score = newScore count = 0 else: count += 1 return key, score
def decrypt(self, cipherText, keys): plainWordList = list() for i in range(len(keys)): k = keys[i] pword = SimpleSubstitution(k).decipher(cipherText) plainWordList.append(pword) return plainWordList
def subDecode(text): maxscore = -99999999999 ctext = text ctext = ctext.replace(" ","").upper() print("Adjusted Text: " + ctext) maxkey = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' pText, pKey = ctext,maxkey decipher = SimpleSubstitution(pKey).decipher(pText) pscore = fitness.score(decipher) print("Deciphered: " + decipher) print("Score: " + str(pscore)) i = 0 while 1: i = i + 1 pKeyL = list(pKey) random.shuffle(pKeyL) pKey = ''.join(pKeyL) decipher = SimpleSubstitution(pKey).decipher(ctext) pscore = fitness.score(decipher) count = 0 while count < 1000: cKey = pKey x = random.randint(0,25) y = random.randint(0,25) cKeyL = list(cKey) cKeyL[x] = pKey[y] cKeyL[y] = pKey[x] cKey = ''.join(cKeyL) #print("Key swapped") decipher = SimpleSubstitution(cKey).decipher(pText) score = fitness.score(decipher) #print("Attempt: " + decipher) #print("Score: " + str(score)) if score > pscore: pscore = score pKey = cKey count = 0 count = count + 1 if(pScore > maxscore): maxscore = pScore maxkey = pKey ss = SimpleSubstitution(maxkey).decipher(ctext) print("Best Key: "+maxkey) print("plaintext: "+ss)
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 substitution(request): form = Substitution() if request.method == 'POST': form = Substitution(request.POST) if form.is_valid(): plain = request.POST['input'] key = request.POST['key'] plain = str(plain) key = str(key) ss = SimpleSubstitution(key) cipher = ss.encipher(plain) return render(request, 'en/substitution.html', { 'form': form, 'cipher': cipher }) # return HttpResponse("Encrypted Text: %s" % cipher) else: form = Substitution() return render(request, 'en/substitution.html', {'form': form})
def SimpleSubstitutionBF(ctext, dictionary): f = open(dictionary, 'r') keys = f.readlines() for i in keys: i = i[:-1] out = SimpleSubstitution(i).decipher(ctext) print('\033[1;34m[*]\033[0m Key = ' + i + ' ; Out = ' + out) print('\033[1;32m[+]\033[0m Brute Force finished.')
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))
def break_substitution_example(plaintext, masker): print("#############################################") print("######## Substitution cipher example ########") print("#############################################") key = [ 'L', 'C', 'N', 'D', 'T', 'H', 'E', 'W', 'Z', 'S', 'A', 'R', 'X', 'V', 'O', 'J', 'B', 'P', 'F', 'U', 'I', 'Q', 'M', 'K', 'G', 'Y' ] ciphertext = SimpleSubstitution(key).encipher(plaintext) print("\nCiphertext:\n---") print(masker.extend(ciphertext)) print("---\n") print("\nCracking...\n") scorer = NgramScorer(load_ngrams(4)) breaker = SubstitutionBreak(scorer, seed=42) breaker.optimise(ciphertext, n=3) decryption, score, key = breaker.guess(ciphertext)[0] print("Substitution decryption (key={}, score={}):\n---\n{}---\n".format( key, score, masker.extend(decryption)))
def encrypt(keycodeLines, encryptionDirection, plaintextContents): for i in range(len(keycodeLines)): #Iterate over the keycode. if (encryptionDirection == "encrypt"): splitLine = keycodeLines[i].split() else: splitLine = keycodeLines[len(keycodeLines) - 1 - i].split( ) #This ensures that if the encryption direction is set to decrypt, that this for loop reads the keycode.txt from end to beginning. # print("Line " + str(i) + " is " + keycodeLines[i] + " and the split line is: " + str(splitLine)) # This was an old debugging line that may be useful in the future. if (splitLine[0] == "caesar"): if (int(splitLine[1]) > 25 or int(splitLine[1]) < 1): print("Keycode line: " + str(i + 1) + ": Caesar shift detected on keycode line " + str(i) + " attempting to shift by value " + splitLine[1] + ".") sys.exit() else: originalPlaintext = plaintextContents if (debug): print("Keycode line: " + str(i + 1) + ": Caesar shift detected with an argument of " + splitLine[1] + ".") if (encryptionDirection == "encrypt"): plaintextContents = Caesar(int( splitLine[1])).encipher(plaintextContents) else: plaintextContents = Caesar(int( splitLine[1])).decipher(plaintextContents) if (debug): print("Keycode line: " + str(i + 1) + ": Caesar shifted " + originalPlaintext + " by " + splitLine[1] + " with a result of " + plaintextContents + ".") elif (splitLine[0] == "vigenere"): if (type(splitLine[1] != str)): originalPlaintext = plaintextContents if (debug): print("Keycode line: " + str(i + 1) + ": Vigenère shift detected with an argument of " + splitLine[1] + ".") if (encryptionDirection == "encrypt"): plaintextContents = Vigenere( splitLine[1]).encipher(plaintextContents) else: plaintextContents = Vigenere( splitLine[1]).decipher(plaintextContents) if (debug): print("Keycode line: " + str(i + 1) + ": Vigenère shifted " + originalPlaintext + " by " + splitLine[1] + " with a result of " + plaintextContents + ".") else: print("Keycode line: " + str(i + 1) + ": Vigenère shift detected on keycode line " + str(i) + " attempting to use key that is not a string.") elif (splitLine[0] == "porta"): if (type(splitLine[1] != str)): originalPlaintext = plaintextContents if (debug): print("Keycode line: " + str(i + 1) + ": Porta cipher detected with an argument of " + splitLine[1] + ".") if (encryptionDirection == "encrypt"): plaintextContents = Porta( splitLine[1]).encipher(plaintextContents) else: plaintextContents = Porta( splitLine[1]).decipher(plaintextContents) if (debug): print("Keycode line: " + str(i + 1) + ": Vigenère shifted " + originalPlaintext + " by " + splitLine[1] + " with a result of " + plaintextContents + ".") else: print("Keycode line: " + str(i + 1) + ": Vigenère shift detected on keycode line " + str(i) + " attempting to use key that is not a string.") elif (splitLine[0] == "adfgx"): if ( len(splitLine[1]) != 25 ): # This makes sure that the keysquare's length is exactly 25. print( "Keycode line: " + str(i + 1) + ": ADFGX cipher detected on keycode line " + str(i) + " attempting to use keysquare that is not 25 characters long." ) sys.exit() else: originalPlaintext = plaintextContents if (debug): print("Keycode line: " + str(i + 1) + ": ADFGX cipher detected with a keysquare of " + splitLine[1] + " and a keyword of " + splitLine[2] + ".") if (encryptionDirection == "encrypt"): plaintextContents = ADFGX( splitLine[1], splitLine[2]).encipher(plaintextContents) else: plaintextContents = ADFGX( splitLine[1], splitLine[2]).decipher(plaintextContents) if (debug): print("Keycode line: " + str(i + 1) + ": ADFGX ciphered " + originalPlaintext + " by a keysquare of " + splitLine[1] + " and a keyword of " + splitLine[2] + " with a result of " + plaintextContents + ".") elif ( splitLine[0] == "adfgvx" ): #The first argument is the keysquare, and the second argument is the keyword. if ( len(splitLine[1]) != 36 ): # This makes sure that the keysquare's length is exactly 36. print( "Keycode line: " + str(i) + ": ADFGVX cipher detected on keycode line " + str(i) + " attempting to use keysquare that is not 25 characters long, but is instead " + str(len(splitLine[1])) + " characters long.") sys.exit() else: originalPlaintext = plaintextContents if (debug): print("Keycode line: " + str(i + 1) + ": ADFGVX cipher detected with a keysquare of " + splitLine[1] + " and a keyword of " + splitLine[2] + ".") if (encryptionDirection == "encrypt"): plaintextContents = ADFGVX( splitLine[1], splitLine[2]).encipher(plaintextContents) else: plaintextContents = ADFGVX( splitLine[1], splitLine[2]).decipher(plaintextContents) if (debug): print("Keycode line: " + str(i + 1) + ": ADFGVX ciphered " + originalPlaintext + " by a keysquare of " + splitLine[1] + " and a keyword of " + splitLine[2] + " with a result of " + plaintextContents + ".") elif (splitLine[0] == "affine"): if ((int(splitLine[2]) < 1) or (int(splitLine[2]) > 25)): print( "Keycode line: " + str(i + 1) + ": Affine cipher detected on keycode line " + str(i) + " attempting to use b value outside of the range of 1-25.") sys.exit() elif ((int(splitLine[1]) == 13) or (int(splitLine[1]) % 2 != 1) or (int(splitLine[1]) > 25) or (int(splitLine[1]) < 1)): print( "Keycode line: " + str(i + 1) + ": Affine cipher detected on keycode line " + str(i) + " attempting to use an a value outside of the range of 1-25, that is even, or that is 13, all of which are not permitted." ) sys.exit() else: originalPlaintext = plaintextContents if (debug): print("Keycode line: " + str(i + 1) + ": Affine cipher detected with an a value of " + splitLine[1] + " and a b value of " + splitLine[2] + ".") if (encryptionDirection == "encrypt"): plaintextContents = Affine( int(splitLine[1]), int(splitLine[2])).encipher(plaintextContents) else: plaintextContents = Affine( int(splitLine[1]), int(splitLine[2])).decipher(plaintextContents) if (debug): print("Keycode line: " + str(i + 1) + ": Affine ciphered " + originalPlaintext + " by value a " + splitLine[1] + " and value b " + splitLine[2] + " with a result of " + plaintextContents + ".") elif ( splitLine[0] == "autokey" ): #TODO: The autokey cipher actually doesn't have any requirements for the key, but will be configured to set off a ton of warnings assuming the config flags allow for it. originalPlaintext = plaintextContents if (debug): print("Keycode line: " + str(i + 1) + ": Autokey cipher detected with an key of " + splitLine[1] + ".") if (encryptionDirection == "encrypt"): plaintextContents = Autokey( splitLine[1]).encipher(plaintextContents) else: plaintextContents = Autokey( splitLine[1]).decipher(plaintextContents) if (debug): print("Keycode line: " + str(i + 1) + ": Autokey ciphered " + originalPlaintext + " by key of " + splitLine[1] + " for a result of " + plaintextContents + ".") elif (splitLine[0] == "atbash"): originalPlaintext = plaintextContents if (debug): print("Keycode line: " + str(i + 1) + ": Autokey cipher detected.") if (encryptionDirection == "encrypt"): plaintextContents = Affine(25, 25).encipher(plaintextContents) else: plaintextContents = Affine(25, 25).decipher(plaintextContents) if (debug): print("Keycode line: " + str(i + 1) + ": Atbash ciphered " + originalPlaintext + " for a result of " + plaintextContents + ".") elif (splitLine[0] == "beaufort"): if (type(splitLine[1] == str)): originalPlaintext = plaintextContents if (debug): print("Keycode line: " + str(i + 1) + ": Beaufort shift detected with an argument of " + splitLine[1] + ".") if (encryptionDirection == "encrypt"): plaintextContents = Beaufort( splitLine[1]).encipher(plaintextContents) else: plaintextContents = Beaufort( splitLine[1]).decipher(plaintextContents) if (debug): print("Keycode line: " + str(i + 1) + ": Beaufort shifted " + originalPlaintext + " by " + splitLine[1] + " with a result of " + plaintextContents + ".") else: print("Keycode line: " + str(i + 1) + ": Beaufort shift detected on keycode line " + str(i) + " attempting to use key that is not a string.") elif (splitLine[0] == "bifid"): if ( len(splitLine[1]) != 25 ): # This makes sure that the keysquare's length is exactly 25. print( "Keycode line: " + str(i + 1) + ": Bifid cipher detected on keycode line " + str(i) + " attempting to use keysquare that is not 25 characters long." ) sys.exit() else: originalPlaintext = plaintextContents if (debug): print("Keycode line: " + str(i + 1) + ": Bifid cipher detected with a keysquare of " + splitLine[1] + " and a keyword of " + splitLine[2] + ".") if (encryptionDirection == "encrypt"): plaintextContents = Bifid(splitLine[1], int( splitLine[2])).encipher(plaintextContents) else: plaintextContents = Bifid(splitLine[1], int( splitLine[2])).decipher(plaintextContents) if (debug): print("Keycode line: " + str(i + 1) + ": Bifid ciphered " + originalPlaintext + " by a keysquare of " + splitLine[1] + " and a keyword of " + splitLine[2] + " with a result of " + plaintextContents + ".") elif (splitLine[0] == "coltrans"): if (type(splitLine[1] != str) ): # Check that the encryption key is a string. originalPlaintext = plaintextContents if (debug): print( "Keycode line: " + str(i + 1) + ": Columnar transposition shift detected with an argument of " + splitLine[1] + ".") if (encryptionDirection == "encrypt"): plaintextContents = ColTrans( splitLine[1]).encipher(plaintextContents) else: plaintextContents = ColTrans( splitLine[1]).decipher(plaintextContents) if (debug): print("Keycode line: " + str(i + 1) + ": Columnar transposition shifted " + originalPlaintext + " by " + splitLine[1] + " with a result of " + plaintextContents + ".") else: print( "Keycode line: " + str(i + 1) + ": Columnar transposition shift detected on keycode line " + str(i) + " attempting to use key that is not a string.") elif (splitLine[0] == "foursquare"): if ( len(splitLine[1]) != 25 ): # This makes sure that the keysquare's length is exactly 25. print( "Foursquare cipher detected on keycode line " + str(i) + " attempting to use keysquare that is not 25 characters long." ) sys.exit() elif (len(splitLine[2]) != 25): print( "Foursquare cipher detected on keycode line " + str(i) + " attempting to use keysquare that is not 25 characters long." ) sys.exit() else: originalPlaintext = plaintextContents if (debug): print("Foursquare cipher detected with a keysquare of " + splitLine[1] + " and a keyword of " + splitLine[2] + ".") if (encryptionDirection == "encrypt"): plaintextContents = Foursquare( key1=splitLine[1], key2=splitLine[2]).encipher(plaintextContents) else: plaintextContents = Foursquare( key1=splitLine[1], key2=splitLine[2]).decipher(plaintextContents) if (debug): print("Foursquare ciphered " + originalPlaintext + " by a keysquare of " + splitLine[1] + " and a keyword of " + splitLine[2] + " with a result of " + plaintextContents + ".") elif (splitLine[0] == "playfair"): if ( len(splitLine[1]) != 25 ): # This makes sure that the keysquare's length is exactly 25. print( "Keycode line: " + str(i + 1) + ": Playfair cipher detected on keycode line " + str(i) + " attempting to use keysquare that is not 25 characters long." ) sys.exit() else: originalPlaintext = plaintextContents if (encryptionDirection == "encrypt"): plaintextContents = Playfair( splitLine[1]).encipher(plaintextContents) else: plaintextContents = Playfair( splitLine[1]).decipher(plaintextContents) if (debug): print("Keycode line: " + str(i + 1) + ": Playfair ciphered " + originalPlaintext + " by a keysquare of " + splitLine[1] + " with a result of " + plaintextContents + ".") elif ( splitLine[0] == "railfence" ): #TODO: Fix this so that it throws an error if the key is a bad length relative to the plaintext. if (splitLine[1].isdigit() == False): print("Keycode line: " + str(i + 1) + ": Railfence cipher detected on keycode line " + str(i) + " with a non-numerical key.") sys.exit() elif ( int(splitLine[1]) < 1 ): # This makes sure that the keysquare's length is exactly 25. print("Keycode line: " + str(i + 1) + ": Railfence cipher detected on keycode line " + str(i) + " attempting to use a key less than 0.") sys.exit() else: originalPlaintext = plaintextContents if (encryptionDirection == "encrypt"): plaintextContents = Railfence(int( splitLine[1])).encipher(plaintextContents) else: plaintextContents = Railfence(int( splitLine[1])).decipher(plaintextContents) if (debug): print("Keycode line: " + str(i + 1) + ": Railfence ciphered " + originalPlaintext + " by a key of " + splitLine[1] + " with a result of " + plaintextContents + ".") elif (splitLine[0] == "rot13"): originalPlaintext = plaintextContents if (debug): print("Keycode line: " + str(i + 1) + ": Rot13 cipher detected.") if (encryptionDirection == "encrypt"): plaintextContents = Rot13().encipher(plaintextContents) else: plaintextContents = Rot13().decipher(plaintextContents) if (debug): print("Keycode line: " + str(i + 1) + ": Rot13 ciphered " + originalPlaintext + " with a result of " + plaintextContents + ".") elif (splitLine[0] == "simplesub"): if ( len(splitLine[1]) != 26 ): # This makes sure that the keysquare's length is exactly 25. print( "Keycode line: " + str(i + 1) + ": Simple substitution cipher detected on keycode line " + str(i) + " attempting to use key that is not 26 characters long.") sys.exit() else: originalPlaintext = plaintextContents if (debug): print( "Keycode line: " + str(i + 1) + ": Simple substitution cipher detected with a key of " + splitLine[1] + ".") if (encryptionDirection == "encrypt"): plaintextContents = SimpleSubstitution( splitLine[1]).encipher(plaintextContents) else: plaintextContents = SimpleSubstitution( splitLine[1]).decipher(plaintextContents) if (debug): print("Keycode line: " + str(i + 1) + ": Simple substitution ciphered " + originalPlaintext + " by a key of " + splitLine[1] + " with a result of " + plaintextContents + ".") if (i == (len(keycodeLines) - 1)): # print(plaintextContents) #A debug catch that you may find useful later. return plaintextContents
# 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 simsubencode(importx, infilepath, outfilepath, inputformat, export, raw, key): if importx == 'file': f = open(infilepath, 'r') raw = f.read() f.close() elif importx == 'print': raw = raw else: print('\033[1;31m[-]\033[0m Unknown error.') return False inp = raw if inputformat == 'base64': iput = base64.b64decode(inp) elif inputformat == 'raw': iput = inp elif inputformat == 'base32': iput = base64.b32decode(inp) elif inputformat == 'base16': iput = base64.b16decode(inp) elif inputformat == 'base58': iput = base58.b58decode(inp) elif inputformat == 'base85': print('\033[1;31m[-]\033[0m Option not available yet') elif inputformat == 'hex': iput = inp.decode('hex') elif inputformat == 'dec': print('\033[1;31m[-]\033[0m Option not available yet') elif inputformat == 'octal': print('\033[1;31m[-]\033[0m Option not available yet') elif inputformat == 'binary': iput = text_from_bits(inp) else: print('\033[1;31m[-]\033[0m Unknown error.') return False output = SimpleSubstitution(key).encipher(iput) if export == 'file': f = open(outfilepath, 'w') f.write(output) f.close() return True elif export == 'print': return output else: print('\033[1;31m[-]\033[0m Unknown error.') return False
def encipher(self, key, text): return SimpleSubstitution(key).encipher(text, True)
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)
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)
fitness = ngram_score('quadgrams.txt') #test cipher text ctext = 'pmpafxaikkitprdsikcplifhwceigixkirradfeirdgkipgigudkcekiigpwrpucikceiginasikwduearrxiiqepcceindgmieinpwdfprduppcedoikiqiasafmfddfipfgmdafmfdteiki' ctext = re.sub('[^A-Z]', '', ctext.upper()) maxkey = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ') maxscore = -99e9 parentscore, parentkey = maxscore, maxkey[:] i = 0 while 1: i = i + 1 random.shuffle(parentkey) deciphered = SimpleSubstitution(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 = SimpleSubstitution(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
def encrypt(self, key, plaintext): masker = Masker(plaintext) ciphertext = SimpleSubstitution(key).encipher(plaintext) return masker.extend(ciphertext)
def decrypt(self, key, ciphertext): masker = Masker(ciphertext) plaintext = SimpleSubstitution(key).decipher(ciphertext) return masker.extend(plaintext)
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)
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)
def decipher(self, text, key): return SimpleSubstitution(key).decipher(text)
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