def main(): #-----------------------------------------------------/V-------- plaintext = 'THOSEPOLICEOFFICERSOFFEREDHERARIDEHOMETHEYTELLTHEMAJOKETHOSEBARBERSLENTHERALOTOFMONEY' antiPlainText = antiKasiski('WICK', plaintext, 'X') if antiPlainText == 'THOSEPOLICEOFFICERSXOFFEREDHERARIDEHOMETHEYTELLXTHEMAJOKETHOSEBARBERSLENXTHERALOTOFMONEY': print('Texts Match:') print(antiPlainText) else: print("Texts Do Not Match:") print("Created: " + antiPlainText) print( "Actual : " + 'THOSEPOLICEOFFICERSXOFFEREDHERARIDEHOMETHEYTELLXTHEMAJOKETHOSEBARBERSLENXTHERALOTOFMONEY' ) print("CipherText :" + vigenere.vigenere('WICK', antiPlainText, 'encrypt')) print("Actual Cipher Text:" + vigenere.vigenere( 'WICK', 'THOSEPOLICEOFFICERSXOFFEREDHERARIDEHOMETHEYTELLXTHEMAJOKETHOSEBARBERSLENXTHERALOTOFMONEY', 'encrypt')) text2 = 'TIMMYTIMMYTIMMYAAAAATIMMY' apt = antiKasiski('WICK', text2, 'XYZ') print(apt) print(vigenere.vigenere('wick', apt, 'encrypt'))
def main(): # inputstr = 'ABA' # print(stringIC(inputstr)) # print() # inputstr2 = 'A' # print(stringIC(inputstr2)) # print() # for i in range(3): # print('subseqIC("PPQCAXQVEKGYBNKMAZUHKNHONMFRAZCBELGRKUGDDMA",', str(3+i), ')') # print(subseqIC("PPQCAXQVEKGYBNKMAZUHKNHONMFRAZCBELGRKUGDDMA", 3+i)) # print() # Testing Key Length IC # ct = "PPQCAXQVEKGYBNKMAZUHKNHONMFRAZCBELGRKUGDDMA" # klIC = keyLengthIC(ct, 10) # print(klIC) ciphertext1 = vigenere.vigenere( 'WAVING', 'ASHFORDISATOWNINFONDDULACCOUNTYWISCONSINUNITEDSTATESTHEPOPULATIONWASATTHECENSUSTHEUNINCORPORATEDCOMMUNITIESOFASHFORDANDELMOREARELOCATEDINTHETOWN', 'encrypt') ciphertext2 = vigenere.vigenere( 'QWERTYUI', 'CONSIDEREDBYSOMETOBEAFATHEROFTHECOMPUTERBABBAGEISCREDITEDWITHINVENTINGTHEFIRSTMECHANICALCOMPUTERTHATEVENTUALLYLEDTOMORECOMPLEXELECTRONICDESIGNSTHOUGHALLTHEESSENTIALIDEASOFMODERNCOMPUTERSARETOBEFOUNDINBABBAGESANALYTICALENGINEHISVARIEDWORKINOTHERFIELDSHASLEDHIMTOBEDESCRIBEDASPREEMINENTAMONGTHEMANYPOLYMATHSOFHISCENTURY', 'encrypt') print("First Test:") print(keyLengthIC(ciphertext1, 5)) print('\nSecond Test:') print(keyLengthIC(ciphertext2, 5))
def caesar_or_vigenere(): if request.form['encryptionType'] == "caesar": rot = int(request.form['rot']) text = request.form['text'] return form.format(caesar(text, rot)) else: text = request.form['text'] key = request.form['key'] return form.format(vigenere(text, key))
def brute(keys): """ Para cada password del fichero 'passwords' trata de descifrar el texto cipherText usando el dictionary y comprueba si el proceso es correcto. Si coincide el hash calculado con el esperado (hash) el programa finaliza. :param keys: todas las claves del fichero passwords :return: no devuelve ningún valor """ for clave in keys: if vigenere.vigenere(cipherText, dictionary, hash, clave.decode('utf-8')): break
def crackPassword(): # This function prints out the decrypted text for the password_protected.txt file # Make this true if you wish to see what key was used for the decryption showKey = False file = 'password_protected.txt' fileContents = '' with open(file, 'r') as f: for line in f: fileContents += line key = hackVigenere(fileContents) if showKey == True: print('Key Used:', key) print(vigenere.vigenere(key, fileContents, 'decrypt'))
def antiKasiski(key, plaintext, chars): key = key.upper() # Turn chars into a list to use random.choice chars = list(chars) repetitions = True while repetitions: # we must get the new cipher text after each insertion cipherText = vigenere.vigenere(key, plaintext, 'encrypt') # find the first instance of a repeating subsequence substring, index = locateRepetitions(cipherText) # stop the loop once no more repetitions are found if substring == None: repetitions = False else: plaintext = insertChar(index, chars, plaintext) repetitions = True return plaintext
def crack(text, scorer=ts.NgramDict('english_quadgrams.txt')): ''' crack the vigenere cypher ''' # possible keylengths text = map(ord, text) keyLens = crackKeyLen(text) # each element is text divided by key length and transponed blocksList = [] for kl in keyLens: blocks = [] for i in xrange(int(len(text) / kl)): blocks.append(text[i*kl : (i+1)*kl]) blocksList.append(matrix(blocks).T) # crack key character with FreqDict crackKeyFreq = lambda t: ts.crackKey(t, ts.NormDict()) # for ech blocks in blocks list crack each charackter and then put it together # to have list of possible keys keys = [''.join(map(chr,k)) for k in map((lambda m : [crackKeyFreq(e) for e in m.tolist()]), blocksList)] # for k in keys: print map(ord,k) plaintexts = [ hexdecode(vigenere(text, k)) for k in keys] ptscores = [scorer.score(pt) for pt in plaintexts] # for score in ptscores: print score bestindex = ptscores.index(max(ptscores)) return plaintexts[bestindex], keys[bestindex]
def vigenereKeySolver(ciphertext, keyLength): possibleKeys = [] # for case insensitivity, make everything uppercase ciphertext = ciphertext.upper() # for storing each letters IMC value for each subsequence IMCT = {} for i in range(1, keyLength+1): #getting the subsequence of nth letters for a given keylength nthLetters = getNthSubkeysLetters(i, keyLength, ciphertext) nthLettersLen = len(nthLetters) #contains the IMC values for a subsequence of the nth letters when decrypted with each letter IMC = [] for letter in ALPHABET: currentIMC = 0 #decrypt the subsequence with a single letter of the alphabet decryptedSubSeq = vigenere.vigenere(letter, nthLetters, 'decrypt') subSeqFreq = getFrequency(decryptedSubSeq, nthLettersLen) # find the sum for t(i) * e(i) for all letters for char in ALPHABET: currentIMC += subSeqFreq[char] * (ENG_LETT_FREQ[char]/100) IMC.append([currentIMC, letter]) IMC.sort(key=lambda x: x[0], reverse=True) IMCT[str(i)] = IMC topTenKeys = getTopTenKeys(IMCT, keyLength) return topTenKeys
if input_cipher == 'C': message = caessar.caessar(input_text, encoding_key, input_alphabet) if input_encode_decode == 'E': result = message.encode() elif input_encode_decode == 'D': result = message.decode() if input_cipher == 'Af': message = affine.affine(input_text, encoding_key1, encoding_key2, input_alphabet) if input_encode_decode == 'E': result = message.encode() elif input_encode_decode == 'D': result = message.decode() if input_cipher == 'At': message = atbash.atbash(input_text, input_alphabet) if input_encode_decode == 'E': result = message.encode() elif input_encode_decode == 'D': result = message.decode() if input_cipher == 'V': message = vigenere.vigenere(input_text, encoding_keyword, input_alphabet) if input_encode_decode == 'E': result = message.encode() elif input_encode_decode == 'D': result = message.decode() results.results(input_text, input_encode_decode, input_cipher, result)
def test_vigenere_2(self): result = vigenere('VALENTIN', 'FARAZ') self.assertEqual(result, 'AACEMYIE')
def test_vigenere_1(self): result = vigenere('WIKIHOWISTHEBEST', 'LIMELIMELIMELIME') self.assertEqual(result, 'HPVMRWIMDBSIMMEX')
def hackVigenere(cipherText): # This function takes in a cipher text and returns the most likely key used for that cipher text # Find the top 4 most likely key lengths possibleKeyLens = keyLengthIC(cipherText, 4) allPossibleKeys = [] foundKeys = [] keyDecipherments = {} # Find the possible keys for each of the 4 most likely key lengths for keyLength in possibleKeyLens: possibleKeys = vigenereKeySolver(cipherText, keyLength) allPossibleKeys += possibleKeys for key in allPossibleKeys: possibleDecipherment = vigenere.vigenere(key, cipherText, 'decrypt') keyDecipherments[key] = possibleDecipherment #This while loop is a little unnecessary, however it gets the key that has the highest word percentage decryption of the cipher text singleKey = False # start with a high but possible word percentage wordPercent = 95 totalRounds = 0 preventReturningNoKeys = [] while singleKey == False: foundKeys = [] # look up the decipherment for each key and check if it is english, hitting the word percentage threshold # add the key to foundKeys if so for key in keyDecipherments.keys(): possibleDecipherment = keyDecipherments[key] isItEnglish = detectEnglish.isEnglish(possibleDecipherment, wordPercentage=wordPercent) if isItEnglish: foundKeys.append(key) # If the word percentage is too high and no keys were found, decrease it by 5% foundKeysLen = len(foundKeys) if foundKeysLen == 0: wordPercent -= 5 # If a single key is found or the total rounds of this while loop hits 25, set single key to true and break from the loop # This prevents an infinite while loop elif foundKeysLen == 1 or totalRounds > 25: singleKey = True # If we get more than one key, the word percentage is most likely set too high, so increment it by 1 elif foundKeysLen > 1: wordPercent += 1 # Store the most recent set of found keys that has at least 1 key, this prevents returning no keys if foundKeysLen != 0: preventReturningNoKeys = foundKeys totalRounds += 1 # If we exited the while loop with no keys found, get the most valid key from a past loop if len(foundKeys) == 0: foundKeys = preventReturningNoKeys return foundKeys[0]
from caesar import caesar from vigenere import vigenere from onetimepad import one_time_pad plaintext = input("Enter Plaintext: ") # Caesar caesar(plaintext) # Vigenere vigenere(plaintext) # One Time Pad one_time_pad(plaintext)
elif cipher == 'vig': vig_total += 1 if key == 'X' or key == 'Y': print('Procurando chave do arquivo', ofile, '...', end="") sys.stdout.flush() sub = np.array(outputfile - inputfile) for k in range(1, 30): sys.stdout.flush() candidate = sub[0:k] full = np.array([int(x) for x in ((",".join(str(x) + ',' for x in candidate)) * (int(len(sub)/k)+1)).split(',') if len(x) > 0])[0:len(sub)] compare = np.array(full == sub) if 1-compare.mean() < 10**-2: print('Chave descoberta = ', "".join([chr(x) for x in candidate])) vig_ok += 1 enc = vigenere(inputfile, candidate) break else: enc = vigenere(inputfile, key.encode('ascii')) vig_ok += (np.array(enc == outputfile).mean() == 1) elif cipher == 'transp': transp_total += 1 if key == 'X' or key == 'Y': print('Procurando chave do arquivo', ofile, '...', end="") sys.stdout.flush() for key in range(1, 256): enc = transposicao(inputfile, int(key)) if np.array(enc == outputfile).mean() == 1: print('Chave descoberta =', key) transp_ok += 1
def interfaz(mensaje, clave): resultado = vigenere(mensaje, clave) return resultado
text = input("Input cipher text: ") print(fromHex(text)) elif choice in ("letternumber", "letter number", "l"): if encode_or_decode(): text = input("Input plain text: ").lower() print(ltnc(text)) else: text = input("Input cipher text: ").lower() print(ntlc(text)) elif choice in ("morse code", "morse", "m"): if encode_or_decode(): text = input("Input plain text: ") print(toMorse(text)) else: text = input("Input cipher text: ") print(fromMorse(text)) elif choice in ("vigenere", "v"): if encode_or_decode(): text = input("Input plain text: ").lower() key = input("Input a key: ").lower().strip() print(vigenere(text, key, True)) else: text = input("Input cipher text: ").lower() key = input("Input a key: ").lower().strip() print(vigenere(text, key, False)) else: print("Please input a valid command.")
def test_vigenere(self): inp = "attackatdawn" password = '******' expected = 'lxfopvefrnhr' self.assertEqual(vigenere(inp, password), expected)