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 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 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 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 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 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 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 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
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 decipher(self, text, key): return SimpleSubstitution(key).decipher(text)
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)
def encipher(self, key, text): return SimpleSubstitution(key).encipher(text, True)