def attemptBreakWithKeyLength(ciphertext, mostLikelyKeyLength): # Determine the most likely letters for each letter in the key. # allFreqScores is a list of mostLikelyKeyLength number of lists. # These inner lists are the freqScores list. allFreqScores = [] for nth in range(1, mostLikelyKeyLength + 1): nthLetters = getNthLetter(nth, mostLikelyKeyLength, ciphertext) # freqScores is a list of tuples (<letter>, <eng. freq. match score>) # This list is sorted by match score (a lower score means a better # match. See the englishFreqMatch() comments in freqFinder). freqScores = [] for possibleKey in LETTERS: translated = vigenereCipher.decryptMessage(nthLetters, possibleKey) freqScores.append((possibleKey, freqFinder.englishFreqMatch(translated))) # Each value in freqScores is a tuple (<letter>, <match score>). Since # we want to sort by match score, we need to pass a "lambda" function # to sort()'s "key" parameter to look at the value at the [1] index. freqScores.sort(key=lambda x: x[1], reverse=True) allFreqScores.append(freqScores[:NUM_MOST_FREQ_LETTERS]) for i in range(len(allFreqScores)): # use i+1, because otherwise the "first" letter is called the "0th" letter print('Possible letters for letter %s of the key: ' % (i + 1), end='') for freqScore in allFreqScores[i]: print('%s ' % freqScore[0], end='') print() # Try every combination of the most likely letters for each position # in the key. for indexes in itertools.product(range(NUM_MOST_FREQ_LETTERS), repeat=mostLikelyKeyLength): # Create a possible key from the letters in allFreqScores possibleKey = '' for i in range(mostLikelyKeyLength): possibleKey += allFreqScores[i][indexes[i]][0] if not SILENT_MODE: print('Attempting with key: %s' % (possibleKey)) decryptedText = vigenereCipher.decryptMessage(ciphertext, possibleKey) if freqFinder.englishTrigramMatch(decryptedText): if detectEnglish.isEnglish(decryptedText): # Check with the user to see if the decrypted key has been found. print() print('Possible encryption break:') print('Key ' + str(possibleKey) + ': ' + decryptedText[:200]) print() print('Enter D for done, or just press Enter to continue breaking:') response = input('> ') if response.upper().startswith('D'): return decryptedText # No English-looking decryption found with any of the possible keys, # so return None. return None
def attemptHackWithKeyLength(ciphertext, mostLikelyKeyLength): # menentukan huruf yang mirip pada setiap kata dalam kunci ciphertextUp = ciphertext.upper() allFreqScores = [] for nth in range(1, mostLikelyKeyLength + 1): nthLetters = getNthSubkeysLetters(nth, mostLikelyKeyLength, ciphertextUp) freqScores = [] for possibleKey in LETTERS: decryptedText = vigenereCipher.decryptMessage( possibleKey, nthLetters) keyAndFreqMatchTuple = ( possibleKey, freqAnalysis.englishFreqMatchScore(decryptedText)) freqScores.append(keyAndFreqMatchTuple) # mengurutkan score freqScores.sort(key=getItemAtIndexOne, reverse=True) allFreqScores.append(freqScores[:NUM_MOST_FREQ_LETTERS]) if not SILENT_MODE: for i in range(len(allFreqScores)): # use i + 1 so the first letter is not called the "0th" letter print('Possible letters for letter %s of the key: ' % (i + 1), end='') for freqScore in allFreqScores[i]: print('%s ' % freqScore[0], end='') print() # print a newline #coba kombinasi yang mirip setiap formasi for indexes in itertools.product(range(NUM_MOST_FREQ_LETTERS), repeat=mostLikelyKeyLength): possibleKey = '' for i in range(mostLikelyKeyLength): possibleKey += allFreqScores[i][indexes[i]][0] if SILENT_MODE: print('Mencoba dengan Kata Kunci: %s' % (possibleKey)) decryptedText = vigenereCipher.decryptMessage(possibleKey, ciphertextUp) if detectEnglish.isEnglish(decryptedText): origCase = [] for i in range(len(ciphertext)): if ciphertext[i].isupper(): origCase.append(decryptedText[i].upper()) else: origCase.append(decryptedText[i].lower()) decryptedText = ''.join(origCase) return decryptedText # No English-looking decryption found, so return None. return None
def attemptHackWithKeyLength(ciphertext, mostLikelyKeyLength): # Determine the most likely letters for each letter in the key. ciphertextUp = ciphertext.upper() # allFreqScores is a list of mostLikelyKeyLength number of lists. # These inner lists are the freqScores lists. allFreqScores = [] for nth in range(1, mostLikelyKeyLength + 1): nthLetters = getNthSubkeysLetters(nth, mostLikelyKeyLength, ciphertextUp) # freqScores is a list of tuples like: # [(<letter>, <Eng. Freq. match score>), ... ] # List is sorted by match score. Higher score means better match. # See the englishFreqMatchScore() comments in freqAnalysis.py. freqScores = [] for possibleKey in LETTERS: decryptedText = vigenereCipher.decryptMessage(possibleKey, nthLetters) keyAndFreqMatchTuple = (possibleKey, freqAnalysis.englishFreqMatchScore(decryptedText)) freqScores.append(keyAndFreqMatchTuple) # Sort by match score freqScores.sort(key=getItemAtIndexOne, reverse=True) allFreqScores.append(freqScores[:NUM_MOST_FREQ_LETTERS]) if not SILENT_MODE: for i in range(len(allFreqScores)): # use i + 1 so the first letter is not called the "0th" letter print("Possible letters for letter %s of the key: ' % (i + 1), end='") for freqScore in allFreqScores[i]: print("%s ' % freqScore[0], end=") print() # print a newline # Try every combination of the most likely letters for each position # in the key. for indexes in itertools.product(range(NUM_MOST_FREQ_LETTERS), repeat=mostLikelyKeyLength): # Create a possible key from the letters in allFreqScores possibleKey = '' for i in range(mostLikelyKeyLength): possibleKey += allFreqScores[i][indexes[i]][0] if not SILENT_MODE: print('Attempting with key: %s' % (possibleKey)) decryptedText = vigenereCipher.decryptMessage(possibleKey, ciphertextUp) if detectEnglish.isEnglish(decryptedText): # Set the hacked ciphertext to the original casing. origCase = [] for i in range(len(ciphertext)): if ciphertext[i].isupper(): origCase.append(decryptedText[i].upper()) else: origCase.append(decryptedText[i].lower()) decryptedText = ''.join(origCase) # Check with user to see if the key has been found. print('Possible encryption hack with key %s:' % (possibleKey)) print(decryptedText[:200]) # only show first 200 characters print() print('Enter D for done, or just press Enter to continue hacking:') response = input('> ') if response.strip().upper().startswith('D'): return decryptedText # No English-looking decryption found, so return None. return None
def attemptHackWithKeyLength(ciphertext,mostLikelyKeyLength): ciphertextUp = ciphertext.upper() allFreqScores = [] for nth in range(1, mostLikelyKeyLength + 1): nthLetters = getNthSubkeysLetters(nth, mostLikelyKeyLength, ciphertextUp) freqScores = [] for possibleKey in vigenereCipher.LETTERS: decryptedText = vigenereCipher.decryptMessage(possibleKey, nthLetters) keyAndFreqMatchTuple = (possibleKey, freqAnalysis.englishFreqMatchScore(decryptedText)) freqScores.append(keyAndFreqMatchTuple) freqScores.sort(key=getItemAtIndexOne, reverse=True) allFreqScores.append(freqScores[:NUM_MOST_FREQ_LETTERS]) if not SILENT_MODE: for i in range(len(allFreqScores)): print('Possible letters for letter {0} of the key: '.format(i + 1)) for freqScores in allFreqScores[i]: print('%s ' % freqScores[0], end = '') print() for indexes in itertools.product(range(NUM_MOST_FREQ_LETTERS), repeat=mostLikelyKeyLength): possibleKey = '' for i in range(mostLikelyKeyLength): possibleKey += allFreqScores[i][indexes[i]][0] if not SILENT_MODE: print('Attempting with key: %s' % (possibleKey)) decryptedText = vigenereCipher.decryptMessage(possibleKey, ciphertextUp) if detectEnglish.isEnglish(decryptedText): origCase = [] for i in range(len(ciphertext)): if ciphertext[i].isupper(): origCase.append(decryptedText[i].upper()) else: origCase.append(decryptedText[i].lower()) decryptedText = ''.join(origCase) print('Possible encryption hack with key %s:' % (possibleKey)) print(decryptedText[:200]) print() print('Enter D fordone, or just press Enter tocontinue') response = input('> ') if response.strip().upper().startswith('D'): return decryptedText return None
def attemptHackWithKeyLength(ciphertext,mostLikelyKeyLength): ciphertextUp = ciphertext.upper() allFreqScores = [] for nth in range(1, mostLikelyKeyLength + 1): nthLetters = getNthSubkeyLetters(nth,mostLikelyKeyLength,ciphertextUp) freqScores = [] for possibleKey in LETTERS: decryptedText = vigenereCipher.decryptMessage(possibleKey,nthLetters) keyAndFreqMatchTuple = (possibleKey,freqAnalysis.englishFreqMatchScore(decryptedText)) freqScores.append(keyAndFreqMatchTuple) freqScores.sort(key=getItemAtIndexOne,reverse=True) allFreqScores.append(freqScores[:NUM_MOST_FREQ_LETTERS]) if not SILENT_MODE: for i in range(len(allFreqScores)): print 'Possible letters for letter' for freqScore in allFreqScores[i]: print freqScore[0] print '' for indexes in itertools.product(range(NUM_MOST_FREQ_LETTERS),repeat=mostLikelyKeyLength): possibleKey = '' for i in range(mostLikelyKeyLength): possibleKey += allFreqScores[i][indexes[i]][0] if not SILENT_MODE: print 'Attempting with key: '+ possibleKey decryptedText = vigenereCipher.decryptMessage(possibleKey,ciphertextUp) if detectEnglish.isEnglish(decryptedText): origCase = [] for i in range(len(ciphertext)): if ciphertext[i].isupper(): origCase.append(decryptedText[i].upper()) else: origCase.append(decryptedText[i].lower()) decryptedText = ''.join(origCase) print 'Possible encryption hack with key '+possibleKey print decryptedText[:200] print '' print 'enter d for done ,or just press enter to continue' response = raw_input('>') if response.upper().startswith('D'): return decryptedText return None
def crackPassword(): #open file script_dir = os.path.dirname(__file__) file_path = os.path.join(script_dir, './password_protected.txt') f = open(file_path) ciphertext = f.read() f.close() #get key key = hackVigenere(ciphertext) decipherText = vigenereCipher.decryptMessage(key, ciphertext) print(decipherText)
def vigenereKeySolver(ciphertext, keylen): ENG_LETT_FREQ = { 'E': 0.127, 'T': 0.09, 'A': 0.0817, 'O': 0.0751, 'I': 0.0697, 'N': 0.0675, 'S': 0.0633, 'H': 0.0609, 'R': 0.0599, 'D': 0.0425, 'L': 0.0403, 'C': 0.0278, 'U': 0.0276, 'M': 0.0241, 'W': 0.0236, 'F': 0.0223, 'G': 0.0202, 'Y': 0.0197, 'P': 0.0193, 'B': 0.0129, 'V': 0.0098, 'K': 0.0077, 'J': 0.0015, 'X': 0.0015, 'Q': 0.0010, 'Z': 0.0007 } key = [''] * keylen # loop that starts from key val 1 to end of key val for num in range(1, keylen + 1): letters = [] old_compare_val = -1 #this loop gets every num th letter from the ciper text. ie every 2nd letter for i in range(num - 1, len(ciphertext), num): letters.append(ciphertext[i]) #try every possible letter as a key val on that sub string called letters for let in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ': temp_decrypt = vigenereCipher.decryptMessage(let, letters) # make an imc functionthat will return the imc of temp_decrypt imc = imc_calc(temp_decrypt, len(temp_decrypt), ENG_LETT_FREQ) #now find the largest IMC new_compare_val = imc_total(imc) # if it is greater than the old saved one save it as the highes and # make the let that is being used as the key value at num in key[] if new_compare_val > old_compare_val: old_compare_val = new_compare_val key[num - 1] = let # save the highest one for that letter of the key return key
def hackvigenere(ciphertext): words = open('dict.txt').readlines() for word in words: word = word.strip() decrytedtext = vigenereCipher.decryptMessage(word,ciphertext) if detectEnglish.isEnglish(decrytedtext,40): print 'Possible encryption break:' print 'key ' + word + ':' + decrytedtext[:100] print 'enter d for done ,or just press enter to continue' response = raw_input('>') if response.upper().startswith('D'): return decrytedtext
def hackVigenere(ciphertext): # fungsi kasiskiExamination(ciphertext) akan me-return list dari semua kemungkinan # panjang keyword dalam integer di sebuah list (faktor pembagi dari jarak antar perulangan) allLikelyKeyLengths = kasiskiExamination(ciphertext) if not SILENT_MODE: keyLengthStr = '' for keyLength in allLikelyKeyLengths: keyLengthStr += '%s ' % (keyLength) print('Kemungkinan panjang kunci adalah: ' + keyLengthStr + '\n') for keyLength in allLikelyKeyLengths: if not SILENT_MODE: print('Mencari kata kunci dengan panjang %s ...' % keyLength) if keyLength == 2: fo = open('2letter.txt') elif keyLength == 3: fo = open('3letter.txt') elif keyLength == 4: fo = open('4letter.txt') elif keyLength == 5: fo = open('5letter.txt') elif keyLength == 6: fo = open('6letter.txt') elif keyLength == 7: fo = open('7letter.txt') elif keyLength == 8: fo = open('8letter.txt') words = fo.readlines() fo.close() for word in words: word = word.strip() # menghilangkan line baru pada akhir kata # meng-dekrip pesan dengan tiap kata kunci decryptedText = vigenereCipher.decryptMessage(word, ciphertext) # pengecekan tiap kata hasil dekrip dalam bahasa inggris, jika hasil return True maka akan di-print if detectEnglish.isEnglish(decryptedText, wordPercentage=40): print() print('Enkripsi yang mungkin:') print('Kunci ' + str(word) + ': ' + decryptedText[:100]) print() print( 'Tekan D jika enkripsi benar, atau Enter untuk melanjutkan mencoba:' ) response = raw_input('> ') if response.upper().startswith('D'): return decryptedText else: continue
def hackVigenere(ciphertext): fo=open('dictionary.txt') words=fo.readlines() fo.close() for word in words: word=word.strip() decryptedText=vigenereCipher.decryptMessage(word,ciphertext) if detectEnglish.isEnglish(decryptedText,wordPercentage=40): #print() #print 'Possible encryption break:' #print 'Key' , str(word) , ':' , decryptedText[:100] vigenereCipher.main(str(word))
def hackVigenere(string): #set a accurancy for apply in detectEnglish accurancy = 0 current_acc = 0 #get some possible key length for decipher key poss_KeyLength = keyLengthIC(string, 5) for length in poss_KeyLength: #get some possible keys by the input some possible key length poss_keys = vigenereKeySolver(string, length) for key in poss_keys: solution = vigenereCipher.decryptMessage(key, string) curr_accurancy = detectEnglish.getEnglishCount(solution) if curr_accurancy > accurancy: accurancy = curr_accurancy real_key = key return real_key
def hackVigenereDictionary(ciphertext): fo = open('dictionary.txt') words = fo.readlines() fo.close() for word in lines: word = word.strip() # Remove the newline at the end. decryptedText = vigenereCipher.decryptMessage(word, ciphertext) if detectEnglish.isEnglish(decryptedText, wordPercentage=40): # Check with user to see if the decrypted key has been found: print() print('Possible encryption break:') print('Key ' + str(word) + ': ' + decryptedText[:100]) print() print('Enter D for done, or just press Enter to continue breaking:') response = input('> ') if response.upper().startswith('D'): return decryptedText
def hackVigenere(ciphertext): fo = open('dictionary.txt') words = fo.readlines() fo.close() for word in words: word = word.strip() decryptedText = vigenereCipher.decryptMessage(word, ciphertext) if detectEnglish.isEnglish(decryptedText, wordPercentage=40): print() print('Possible encryption break:') print('Key ' + str(word) + ': ' + decryptedText[:100]) print() print('Enter D for done, or just press Enter to continue breaking:') response = input('> ') if response.upper().startswith('D'): return decryptedText return None
def hackVigenere(ciphertext): fo = open('dictionary.txt') words = fo.readlines() fo.close() for word in words: word = word.strip() # remove the newline at the end decryptedText = vigenereCipher.decryptMessage(word, ciphertext) if detectEnglish.isEnglish(decryptedText, wordPercentage=40): # Check with user to see if the decrypted key has been found. print() print('Possible encryption break:') print('Key ' + str(word) + ': ' + decryptedText[:100]) print() print('Enter D for done, or just press Enter to continue breaking:') response = input('> ') if response.strip().upper().startswith('D'): return decryptedText
def hackVigenere(ciphertext): # get 5 most possible keylength possible_key_length = keyLengthIC(ciphertext, 5) max_acc = 0 for key_length in possible_key_length: # get 10 most possible keys possible_keys = vigenereKeySolver(ciphertext, key_length) for key in possible_keys: decrpted_text = vigenereCipher.decryptMessage(key, ciphertext) current_acc = detectEnglish.getEnglishCount(decrpted_text) # check whether the current key is the best one if current_acc > max_acc: max_acc = current_acc best_key = key return best_key
def main(argv): password = '' try: opts, args = getopt.getopt(argv, "hp:", ["pword="]) except getopt.GetoptError: print('dec.py -p <password>') sys.exit(2) for opt, arg in opts: if opt == '-h': print('dec.py -p <password>') sys.exit() elif opt in ("-p", "--pword"): password = arg if password != '': myMessage = '' translated = '' myMessage = pyperclip.paste() translated = vigenereCipher.decryptMessage(password, myMessage) pyperclip.copy(translated) print('done.')
def main(): ciphertext = '' fp = open('dictionary.txt') for word in fp.readline(): word = word.upper().strip() # remove the newline at the end plaintext = vigenereCipher.decryptMessage(ciphertext, word) if detectEnglish.isEnglish(plaintext): # Check with the user to see if the decrypted key has been found. print() print('Possible encryption break:') print('Key ' + str(possibleKey) + ': ' + decryptedText[:100]) print() print('Enter D for done, or just press Enter to continue breaking:') response = input('> ') if response.upper().startswith('D'): return decryptedText fp.close()
def hackVigenere(cipherText): # don't use a 'word' key to avoid this attack fo = open('words.txt') words = fo.readlines() fo.close() for word in words: word = word.strip() # remove the newline at the end decryptedText = vigenereCipher.decryptMessage(word, cipherText) if detectEnglish.isEnglish(decryptedText, wordPercentage=40): # Check with user to see if the decrypted key has been found. print '' print 'Possible encryption break: ' print 'Key ' + str(word) + ': ' + decryptedText[:100] print '' print 'Enter D for done, or just press Enter to continue breaking: ' response = raw_input('> ') if response.upper().startswith('D'): return decryptedText
def hackVigenereDictionary(ciphertext): fo = open("dictionary.txt") words = fo.readlines() fo.close() for word in words: word = word.strip() #removes the newline at end decryptedText = vigenereCipher.decryptMessage(word, ciphertext) if detectEnglish.isEnglish(decryptedText, 40): #sends 40% as the 2nd argument #checks if it is right print() print("Possible answer:") print("Key " + str(word) + ": " + decryptedText[:100]) print() print("Press D for done or enter to continue") response = input(">") if response.upper().startswith("D"): return decryptedText
def hackVigenereDictionary(ciphertext): fo = open('dictionary.txt') words = fo.readlines() fo.close for word in word: # Remove newline word = word.strip() decryptedText = vigenereCipher.decryptMessage(word, ciphertext) if detectEnglish.isEnglish(decryptedText, wordPercentage=40): # Check with user to see if key has been found print() print("owo what's this? *notices possible encryption break*") print('Key ' + str(word) + ': ' + decryptedText[:100]) print() print('Enter D for done, or just press enter to continue...') response = input('>') if response.upper().startswith('D'): return decryptedText
def crackPassword(): # read text from the file script_dir = os.path.dirname(__file__) file_path = os.path.join(script_dir, './password_protected.txt') input_file = open(file_path) ciphered_message = input_file.read() input_file.close() # get the most possible key guess_key = hackVigenere(ciphered_message) deciphered_text = vigenereCipher.decryptMessage(guess_key, ciphered_message) # output the result in a file save_path = 'C:/Users/lzeeorno/Desktop/as7' filename = os.path.join(save_path, "a7.txt") output_file = open(filename, "w") output_file.write(deciphered_text) output_file.close() print(deciphered_text)
def vigenereKeySolver(ciphertext, key_len): keyIndex = 0 splitText = [""] * key_len for i in range(0, len(ciphertext)): if ciphertext[i].isalpha(): character = ciphertext[i].upper() if keyIndex < key_len: splitText[keyIndex] += character keyIndex = keyIndex + 1 else: keyIndex = 0 splitText[keyIndex] += character keyIndex = keyIndex + 1 imc_list = [] for i in range(0, len(splitText)): subString = splitText[i] imc_subString = [] for possible_key in LETTERS: deciphered_subString = vigenereCipher.decryptMessage( possible_key, subString) count_dict = { 'A': 0, 'B': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 0, 'I': 0, 'J': 0, 'K': 0, 'L': 0, 'M': 0, 'N': 0, 'O': 0, 'P': 0, 'Q': 0, 'R': 0, 'S': 0, 'T': 0, 'U': 0, 'V': 0, 'W': 0, 'X': 0, 'Y': 0, 'Z': 0 } for index in range(0, len(deciphered_subString)): current_letter = deciphered_subString[index] count_dict[current_letter] = count_dict[current_letter] + 1 imc = 0 for letter in count_dict: t_value = count_dict[letter] / len(deciphered_subString) e_value = ENG_LETT_FREQ[letter] / 100 imc += t_value * e_value key_imc_tuple = (possible_key, imc) imc_subString.append(key_imc_tuple) for n in range(0, len(imc_subString)): for m in range(len(imc_subString) - 1, n, -1): if imc_subString[m - 1][1] < imc_subString[m][1]: imc_subString[m], imc_subString[m - 1] = imc_subString[ m - 1], imc_subString[m] imc_list.append(imc_subString) keys_list = [] for i in range(0, 10): current_key = "" for m in range(0, key_len): current_key = current_key + imc_list[m][0][0] keys_list.append(current_key) min_difference = float(imc_list[0][0][1]) for i in range(0, key_len): current_difference = imc_list[i][0][1] - imc_list[i][1][1] if current_difference < min_difference: min_difference_index = i min_difference = current_difference del (imc_list[min_difference_index][0]) return keys_list
def attemptHackWithKeyLength(cipherText, mostLikelyKeyLength): # Determine the most likely letters for each letter in the key. cipherTextUp = cipherText.upper() # allFreqScores is a list of mostLikelyKeyLength number of lists. allFreqKey = [] for nth in range(mostLikelyKeyLength): nthLetters = getNthSubkeysLetters(nth, mostLikelyKeyLength, cipherTextUp) # freqScores is a list of tuples like: # [(<letter>, <Eng. Freq. match score>), ... ] freqScores = [] for possibleKey in LETTERS: decryptedText = vigenereCipher.decryptMessage( possibleKey, nthLetters) matchScore = freqAnalysis.englishFreqMatchScore(decryptedText) freqScores.append((possibleKey, matchScore)) # Sort by match score freqScores.sort(key=lambda x: x[1], reverse=True) # Get top letter numFreq = MIN_NUM_MOST_FREQ_LETTERS while numFreq < len( LETTERS) and freqScores[0][1] == freqScores[numFreq][1]: numFreq += 1 freqKey = [fs[0] for fs in freqScores[:numFreq]] allFreqKey.append(freqKey) if not SILENT_MODE: for i in range(mostLikelyKeyLength): print('Possible letters for letter %s of the key: ' % (i + 1) + getStringPrint(allFreqKey[i])) # Try every combination of the most likely letters for each position # in the key. indexes = [0 for _ in range(mostLikelyKeyLength)] while indexes is not None: # Create a possible key possibleKey = '' for i in range(mostLikelyKeyLength): possibleKey += allFreqKey[i][indexes[i]] if not SILENT_MODE: print('Attempting with key: %s' % possibleKey) decryptedText = vigenereCipher.decryptMessage(possibleKey, cipherTextUp) if detectEnglish.isEnglish(decryptedText): # Set the hacked ciphertext to the original casing. origCase = [] for i in range(len(cipherText)): if cipherText[i].isupper(): origCase.append(decryptedText[i].upper()) else: origCase.append(decryptedText[i].lower()) decryptedText = ''.join(origCase) # Check with user to see if the key has been found. print('Possible encryption hack with key %s:' % (possibleKey)) print(decryptedText[:200]) # only show first 200 characters print() if STOP: print( 'Enter D for done, or just press Enter to continue hacking:' ) response = input('> ') if response.strip().upper().startswith('D'): return decryptedText indexes = getNextCombine(indexes, allFreqKey) # No English-looking decryption found, so return None. return None
def attemptHackWithKeyLength(ciphertext, mostLikelyKeyLength): # Determine the most likely letters for each letter in the key: ciphertextUp = ciphertext.upper() # allFreqScores is a list of mostLikelyKeyLength number of lists. # These inner lists are the freqScores lists. allFreqScores = [] for nth in range(1, mostLikelyKeyLength + 1): nthLetters = getNthSubkeysLetters(nth, mostLikelyKeyLength, ciphertextUp) # freqScores is a list of tuples like: # [(<letter>, <Eng. Freq. match score>), ... ] # List is sorted by match score. Higher score means better match. # See the englishFreqMatchScore() comments in freqAnalysis.py. freqScores = [] for possibleKey in LETTERS: decryptedText = vigenereCipher.decryptMessage( possibleKey, nthLetters) keyAndFreqMatchTuple = ( possibleKey, freqAnalysis.englishFreqMatchScore(decryptedText)) freqScores.append(keyAndFreqMatchTuple) # Sort by match score: freqScores.sort(key=getItemAtIndexOne, reverse=True) allFreqScores.append(freqScores[:NUM_MOST_FREQ_LETTERS]) if not SILENT_MODE: for i in range(len(allFreqScores)): # Use i + 1 so the first letter is not called the "0th" letter: print('Possible letters for letter %s of the key: ' % (i + 1), end='') for freqScore in allFreqScores[i]: print('%s ' % freqScore[0], end='') print() # Print a newline. # Try every combination of the most likely letters for each position # in the key: for indexes in itertools.product(range(NUM_MOST_FREQ_LETTERS), repeat=mostLikelyKeyLength): # Create a possible key from the letters in allFreqScores: possibleKey = '' for i in range(mostLikelyKeyLength): possibleKey += allFreqScores[i][indexes[i]][0] if not SILENT_MODE: print('Attempting with key: %s' % (possibleKey)) decryptedText = vigenereCipher.decryptMessage(possibleKey, ciphertextUp) if detectEnglish.isEnglish(decryptedText): # Set the hacked ciphertext to the original casing: origCase = [] for i in range(len(ciphertext)): if ciphertext[i].isupper(): origCase.append(decryptedText[i].upper()) else: origCase.append(decryptedText[i].lower()) decryptedText = ''.join(origCase) # Check with user to see if the key has been found: print('Possible encryption hack with key %s:' % (possibleKey)) print(decryptedText[:200]) # Only show first 200 characters. print() print('Enter D if done, anything else to continue hacking:') response = input('> ') if response.strip().upper().startswith('D'): return decryptedText # No English-looking decryption found, so return None: return None
def attemptHackWithKeyLength(ciphertext, mostLikelyKeyLength): #Determine the most likely letters for each letter in the key: ciphertextUp = ciphertext.upper() allFreqScores = [] for nth in range(1, mostLikelyKeyLength + 1): nthLetters = getNthSubkeysLetters(nth, mostLikelyKeyLength, ciphertextUp) #FreqScore is a list of tuples like letter and English Freq match score #[<letter>, <Eng. Freq. match score>), ...] freqScores = [] for possibleKey in LETTERS: decryptedText = vigenereCipher.decryptMessage( possibleKey, nthLetters) keyAndFreqMatchTuple = ( possibleKey, freqAnalysis.englishFreqMatchScore(decryptedText)) freqScores.append(keyAndFreqMatchTuple) freqScores.sort(key=getItemAtIndexOne, reverse=True) #Example of some of the allFreqScores =[[('A',9), ('E', 5), ('O', 4), ('P', 4)], #[('S', 10), ('D', 4), ('G', 4), ('H',4)]] allFreqScores.append(freqScores[:NUM_MOST_FREQ_LETTER]) if not SILENT_MODE: for i in range(len(allFreqScores)): #Use i + 1 so the first letter is not called the "0th" letter: print('Possible letters for letter %s of the key: ' % (i + 1), end='') for freqScore in allFreqScores[i]: print('%s ' % freqScore[0], end='') print() # Print a newline #Try every combination of the most likely letters for each position in the key for indexes in itertools.product(range(NUM_MOST_FREQ_LETTER), repeat=mostLikelyKeyLength): #Create a possible key from the letters in allFreqScores: possibleKey = '' for i in range(mostLikelyKeyLength): possibleKey += allFreqScores[i][indexes[i]][0] if not SILENT_MODE: print('Attempting with key: %s' % (possibleKey)) decryptedText = vigenereCipher.decryptMessage(possibleKey, ciphertextUp) if detectEnglish.isEnglish(decryptedText): origCase = [] for i in range(len(ciphertext)): if ciphertext[i].isupper(): origCase.append(decryptedText[i].upper()) else: origCase.append(decryptedText[i].lower()) decryptedText = ''.join(origCase) #Check with user to see if the key has been found: print('Possible encryption hack with key %s:' % (possibleKey)) print(decryptedText[:200]) print() print('Enter D if done, anything else to continue hacking') response = input('> ') if response.strip().upper().startswith('D'): return decryptedText return None
def roundFunction(message, sKey, nKey, rnd): message = caesarCipher2.encryptMessage(nKey, message) message = transpositionCipher.encrypt(message, rnd) message = vigenereCipher.decryptMessage(sKey, message) return message
import vigenereCipher, itertools,math alphabets = ['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'] message="Qwtguhexcymwlhtzltjiwyuxethizyetcowqbpgzcwb" keyLength=2 #set the keylength keywords = [''.join(i) for i in itertools.product(alphabets, repeat = keyLength)] #all possible iterations myfile = open('randomphrases.txt', 'w') for key in keywords: #print key t=vigenereCipher.decryptMessage(key,message) myfile.write(t) myfile.write('\n') myfile.close() print 'decrypted'
def vigenereKeySolver(ciphertext, key_len): #split the ciphertext by the key length keyIndex = 0 splitText = [""] * key_len for i in range(0, len(ciphertext)): if ciphertext[i].isalpha(): #if the letter is english make all letter as capital letter character = ciphertext[i].upper() if keyIndex < key_len: splitText[keyIndex] += character keyIndex = keyIndex + 1 else: keyIndex = 0 splitText[keyIndex] += character keyIndex = keyIndex + 1 imc_list = [] for i in range(0, len(splitText)): subString = splitText[i] imc_subString = [] # 26 possible key in each sub string for possible_key in LETTERS: deciphered_subString = vigenereCipher.decryptMessage( possible_key, subString) count_dict = { 'A': 0, 'B': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 0, 'I': 0, 'J': 0, 'K': 0, 'L': 0, 'M': 0, 'N': 0, 'O': 0, 'P': 0, 'Q': 0, 'R': 0, 'S': 0, 'T': 0, 'U': 0, 'V': 0, 'W': 0, 'X': 0, 'Y': 0, 'Z': 0 } for index in range(0, len(deciphered_subString)): current_letter = deciphered_subString[index] count_dict[current_letter] = count_dict[current_letter] + 1 imc = 0 #calculate the imc value by the formula for letter in count_dict: t_value = count_dict[letter] / len(deciphered_subString) e_value = ENG_LETT_FREQ[letter] / 100 imc += t_value * e_value key_imc_tuple = (possible_key, imc) imc_subString.append(key_imc_tuple) #print(imc_subString) for n in range(0, len(imc_subString)): for m in range(len(imc_subString) - 1, n, -1): if imc_subString[m - 1][1] < imc_subString[m][1]: imc_subString[m], imc_subString[m - 1] = imc_subString[ m - 1], imc_subString[m] imc_list.append(imc_subString) #print(imc_list) keys_list = [] #find 10 possible keys for i in range(0, 10): current_key = "" for m in range(0, key_len): current_key = current_key + imc_list[m][0][0] keys_list.append(current_key) min_difference = float(imc_list[0][0][1]) #replace the by the difference for i in range(0, key_len): current_difference = imc_list[i][0][1] - imc_list[i][1][1] if current_difference < min_difference: min_difference_index = i min_difference = current_difference #delete one let next key become first key del (imc_list[min_difference_index][0]) return keys_list