def test_decrypt(self): key = "mykey" #pdb.set_trace() self.assertEqual("abcde", vigenere.decrypt("mzmhC", key)) self.assertEqual("nicolas", vigenere.decrypt("zGmsJmQ", key)) self.assertEqual("nico", vigenere.decrypt("zGms", key)) key = "aNotherkEY" self.assertEqual("IssoMesmoAquii", vigenere.decrypt("IfGHTiJwSyqhwB", key))
def icm_shift_guess(keys, cipher_text, typ_file): icms = [] freqs_typ = get_freqs(typ_file) for k in keys: freqs_plain = get_freqs(decrypt(cipher_text, k)) icms.append(icm(freqs_plain, freqs_typ)) return keys[icms.index(max(icms))] # return the key maximising the icm
def process_vigenere(mode, input_text, key, output_type, output_file): if mode == "encrypt": print("Plaintext:\n----------------------------") print (input_text.decode('utf-8')) ciphertext = vigenere.encrypt(input_text.decode('utf-8'), key.upper()) if output_type == "a": processed_ciphertext = ciphertext elif output_type == "b": processed_ciphertext = re.sub('\W', '', ciphertext) elif output_type == "c": ciphertext = re.sub('\W', '', ciphertext).upper() processed_ciphertext = ' '.join(ciphertext[i:i+5] for i in range(0,len(ciphertext),5)) else: print ("Invalid output option") sys.exit(2) print ("Ciphertext:\n----------------------------") print (processed_ciphertext) open(output_file, 'w').write(processed_ciphertext) elif mode == "decrypt": print ("Ciphertext:\n----------------------------") print (input_data.decode('utf-8')) ciphertext = re.sub('\W', '', input_text).upper() plaintext = vigenere.decrypt(ciphertext, key.upper()) print ("Plaintext:\n----------------------------") print (plaintext) open(output_file, 'w').write(plaintext)
def get_message(self): # extract message form self.stego_object and save as file # extract additional message first used_pixel = self.__extract_additional_message() # extract message content result_as_bits = self.__msg_operation_stego_object( "get", False, used_pixel=used_pixel) # convert bits to chars result = '' bytes_char = [ result_as_bits[i:i + 8] for i in range(0, len(result_as_bits), 8) ] for byte in bytes_char: result += chr(int(byte, 2)) # decrypt message if self.is_message_encrypted: result = vigenere.decrypt(result, self.key) # save as file filepath = self.message_output_path + self.message_output_filename + "." + self.message_file_format f = open(filepath, 'wb') f.write(result) f.close() return self.message_output_filename + "." + self.message_file_format, self.message_file_format
def test_encrypt_decrypt(self): for _ in range(1000): random_key = vigenere.random_key(key_size=100) plain_text = self.random_text(size=1000) cipher = vigenere.encrypt(plain_text, random_key) self.assertEqual(vigenere.decrypt(cipher, random_key), plain_text, "Decrypted cipher not equal to the plain-text")
def main(filename): encrypted_phrase = '' # key gen helper is an array that will keep track the character ascii values for us key_gen_helper = [] # read the requested file with open(filename, 'r') as f: encrypted_phrase = f.read() decrypted_phrase = encrypted_phrase # start the timer # TODO: instrument the brute force attack using the time module to measure # how long it takes to determine the key # https://stackoverflow.com/questions/7370801/measure-time-elapsed-in-python key = 'a' # keep iterating until a successful decrypt has occurred while not successful_decrypt(decrypted_phrase): key = '' # generate the string from the key_gen_helper for i in reversed(range(len(key_gen_helper))): key += chr(key_gen_helper[i]) # attempt to decrypt using the key generated if key != '': decrypted_phrase = vigenere.decrypt(encrypted_phrase, key) # increment the key_gen_helper ascii values index = 0 # this while loops carries any repeated 'z's over to 'a's while (index < len(key_gen_helper)) and (key_gen_helper[index] == ord('z')): key_gen_helper[index] = ord('a') index += 1 # add an 'a' to the key_gen_helper if we've reached all 'z's if index == len(key_gen_helper): key_gen_helper.append(ord('a')) print('Testing keys of length {} starting with letter:'.format( len(key_gen_helper))) print('{}'.format(chr(key_gen_helper[index - 1]))) # otherwise increment ascii value at the current index else: key_gen_helper[index] += 1 # If we're incrementing the first letter, print that letter if index == len(key_gen_helper) - 1: print('{}'.format(chr(key_gen_helper[index]))) # end the timer duration = 0 print('Success! Key is: {}\nDecrypted phrase is:\n{}'.format( key, decrypted_phrase)) print('Time elapsed: {}s'.format(duration)) return 0
def on_quest_invite(token): from vigenere import decrypt data = request.json if data['webhookType'] == 'questActivity' and data['type'] == 'questInvited': with open('settings/key.txt', encoding='utf8') as file: key = file.read() token = decrypt(token[::-1], key) client.connect(data['user']['_id'], token).quest_accept_pending(data['group']['id']) return {'status': 'success', 'message': 'thank you'}
def decrypt(cypher, crypt, key): msg = '' if cypher == "caesar": msg = caesar.decrypt(crypt, int(key)) elif cypher == "vigenere": msg = vigenere.decrypt(crypt, key) else: print 'cypher not found' return 0 return msg
def brute_force_key(cipher_text, key_length, secret_message): # initialize key to all As brute_force_key = [0 for i in range(key_length)] # go through all 26*26*26... possibilities till the key is found for i in range(26**key_length): # if the key decrypts the message correctly return the key if decrypt(cipher_text, brute_force_key) == secret_message: return brute_force_key # otherwise increment and continue _increment_brute_force_key(brute_force_key, key_length, key_length - 1)
def prompt_cycle(response): if response == "e": message = input("Please enter an alphanumeric message to encrypt: ") key = input("Please enter a key: ") print("Your encrypted messages is: " + vigenere.encrypt(message, key)) print("") else: message = input("Please enter an alphanumeric message to decrypt: ") key = input("Please enter a key: ") print("Your decrypted message is: " + vigenere.decrypt(message, key)) print("")
def test(number, cipher, key): i = 0 print("Decrypting the code process is getting started...") solve = vigenere.decrypt(key, sezar.decrypt(cipher)) while i <= len(number): if i == len(number): print("Mission complated") break elif i < len(number) and number[i] == solve[i]: i += 1 else: print("Mission failed") break
def process_key(key='', max_key_length=20): decrypted = vigenere.decrypt(key, s) phrase = decrypted.split() if dictionary.are_all_words(phrase) and princeton_dictionary.words_make_sense_as_whole(phrase): print('key: "{}" message: "{}"'.format(key, decrypted)) if check_online(key): print("legan! {} {}".format(key, decrypted)) sys.exit(0) if len(key) < max_key_length and need_to_go_deeper(decrypted, len(key)): for k in string.ascii_lowercase: process_key(''.join([key, k]), max_key_length)
def kasiski_manual_crack(text): choice = "" formated_text = "".join( [i for i in text.upper() if ord(i) <= ord('Z') and ord('A') <= ord(i)]) key = "aaa" invalid_idxs = [] autokey = False while (True): print(vigenere.decrypt(text, key, autokey, invalid_idxs)) print("autokey: {}\tinvalid_idxs={}".format(autokey, invalid_idxs)) print("commands: | substrings | key | autokey | help |") choice = input("command: ") if (choice == "substrings"): n = int(input("substring length: ")) kasiski_pretty(formated_text, n) input() elif (choice == "key"): key = input("input key(zeros will be seen as nothing): ").upper() invalid_idxs = [i for i in range(len(key)) if key[i] == 0] elif (choice == "autokey"): autokey = not autokey elif (choice == "help"): print( "susbtrings->get factors of the number of characters between substrings repetitions" ) print("key->set key to use(use zero for undefined spaces)") print("autokey->toogle autokey mode on/off") print("help->print this panel") else: continue
def vigenere_decrypt(msg, key, label): if msg == "" or key == "": print("one of the following [message/key] is empty") messagebox.showinfo('Error', 'one of the following [message/key] is empty') return else: for char in key: if char.isdigit(): print("invalid key - containing digits") messagebox.showinfo('Error', 'invalid key - containing digits') return label.delete(0, END) label.insert(0, vigenere.decrypt(msg, key))
def test_vigenere(): file = open(path["reference"]["lorem"], "r") lorem_text = file.read() file.close() file = open(path["reference"]["random"], "r") random_text = file.read() file.close() file = open(path["reference"]["constant"], "r") constant_text = file.read() file.close() print("Rauheitsgrad Lorem: %s" % vigenere.calc_rauheitsgrad(lorem_text)) print("Rauheitsgrad Random: %s" % vigenere.calc_rauheitsgrad(random_text)) print("Rauheitsgrad Constant: %s" % vigenere.calc_rauheitsgrad(constant_text)) for crypto_path in path["vigenere-crypto"]: file = open(path["vigenere-crypto"][crypto_path], "r") text = file.read() file.close() print("____________________") vigenere.decrypt(lorem_text, text)
def _calculate_fitness(self): letter_counter = {} bigram_counter = {} # store the message decrypted with key text = decrypt(self.cipher_text, self.letters) # set the counter for the first letter to 1 # so that bigrams and monograms can be calculated at the same time letter_counter[text[0]] = 1 # go through the cipher and count the monograms and bigrams for i in range(1, self.cipher_size): # increment the counter for the letter # create counter for letter if there is none letter_count = letter_counter.get(text[i]) if letter_count == None: letter_counter[text[i]] = 1 else: letter_counter[text[i]] = letter_count + 1 # increment the counter for the bigram # create counter for bigram if there is none bigram_count = bigram_counter.get((text[i - 1], text[i])) if bigram_count == None: bigram_counter[(text[i - 1], text[i])] = 1 else: bigram_counter[(text[i - 1], text[i])] = bigram_count + 1 # set the fitness to 0 for calculation self.fitness = 0 # add to the fitness all deviation from english statistics for bigram, number in bigram_counter.items(): self.fitness += 0.73 * \ (abs(bigram_frequencies_as_num(bigram) - (number/(self.cipher_size - 1)))) for letter, number in letter_counter.items(): self.fitness += 0.27 * \ (abs(letter_frequencies_as_num(letter) - (number/self.cipher_size))) # if the fitness is better than the personal best, update personal best if self.fitness < self.pb_fitness: self.pb_fitness = self.fitness self.pb_letters = self.letters
def main(): # Gathering user input key = input("Input cypher key: ").strip() while True: text = input("Input text to decode: ").strip() # Printing deciphered text and returning print("Deciphered text:") print(vigenere.decrypt(text, vigenere.lengthen_key(text, key))) # Seeing if we should continue resume = input("Would you like to decipher more with this key? " "(y/n) ").strip().lower() if (resume == "n") or (resume == "no"): break print("Decoding complete") return
def solve_vig(cryptogram, key_length): min_score = score_markov(cryptogram) soln = cryptogram soln_key = 'A' if key_length == 'words': test_keys = (word.upper() for word in words) else: test_keys = product(*([alphabet] * key_length)) for test_key in test_keys: test_key = ''.join(test_key) guess = vigenere.decrypt(test_key, cryptogram) score = score_markov(guess) if score < min_score: min_score = score soln = guess soln_key = test_key return soln_key, soln
def extract_message(stego_file, message_file, key=None): audio_bytes = read_audio_bytes(stego_file) current_index = 0 flag = get_message(audio_bytes, range(current_index, current_index + 8))[0] current_index = current_index + 8 extension_length = get_message(audio_bytes, range(current_index, current_index + 8))[0] current_index = current_index + 8 extension = get_message( audio_bytes, range(current_index, current_index + 8 * extension_length)) current_index = current_index + 8 * extension_length message_length_flag = get_message(audio_bytes, range(current_index, current_index + 8))[0] current_index = current_index + 8 message_length = int( get_message_in_bits_string( audio_bytes, range(current_index, current_index + 8 * message_length_flag)), 2) current_index = current_index + 8 * message_length_flag if (flag & 2) == 2: # randomized random.seed(create_seed(key)) indexes = random.sample(range(current_index, len(audio_bytes)), 8 * message_length) else: #sequential indexes = range(current_index, current_index + 8 * message_length) message = get_message(audio_bytes, indexes) if (flag & 1) == 1: message = bytearray(decrypt(str(message), key)) write_message_bytes(str(message_file + extension), message) return extension
def Vigenere(): msg = '' output = '' set1 = 'opt1' set2 = 'opt4' key = 'key' if request.method == 'POST': task = request.form.get('task') msg = request.form.get('original-text') set1 = request.form.get('set1') set2 = request.form.get('set2') key = request.form.get('key') key = ''.join([i for i in key if i.isupper() or i.islower()]) if task == 'encrypt': output = vigenere.encrypt(msg,key) if set1 == 'opt1': pass elif set1 == 'opt2': output = removeAllSpecialCharactersExcludingSpaces(output) elif set1 == 'opt3': output = removeAllSpecialCharactersIncludingSpaces(output) elif task == 'decrypt': output = vigenere.decrypt(msg,key) if set1 == 'opt1': pass elif set1 == 'opt2' : output = removeAllSpecialCharactersExcludingSpaces(output) elif set1 == 'opt3': output = removeAllSpecialCharactersIncludingSpaces(output) if set2 == 'opt4': pass elif set2 == 'opt5': output = output.upper() elif set2 == 'opt6': output = output.lower() return render_template('vigenere.html', title='Vigenère Cipher', msg=msg, output=output, set1=set1, set2=set2, key=key)
ic = 0 for i in range(len(alphabet)): ic += ci_perletter[alphabet[i]] * v.count( alphabet[(i + k) % len(alphabet)]) / len(v) diff = abs(ci_target - ic) if diff < best['DIFF']: best = { 'KEY@' + str(x): alphabet[k], 'INDEX': ic, 'DIFF': diff } results[x] = { 'KEY@' + str(x): alphabet[k], 'INDEX': ic, 'DIFF': diff } return results if __name__ == '__main__': print("ANALYZING: " + tocrack) ics = get_ics(keylength=6, ciphertext=tocrack, language="de") sol = "" for i in range(len(ics)): print(ics[i]) sol += ics[i]["KEY@" + str(i)] print("DECRYPT WITH: " + sol) print(vigenere.decrypt(tocrack, sol))
def test_decryption_1(): key = 'snake' encrypted = 'FSFERXOUPQXDILSMZBVJ' expected = 'MEETMEATELEPHANTLAKE' assert decrypt(encrypted, key) == expected
def main(): answer = input( 'Would you like to perform a cipher operation? Enter y/n.\n') while answer.lower() == 'y': print('1.) Caesar Cipher') print('2.) Transposition Cipher') print('3.) Classic Vigenere Cipher') print('4.) Modified Vigenere Cipher') print('5.) View Modified Vigenere Keys') print('0.) Exit') cipherChoice = input('Enter an option 0-5.\n') while not ((cipherChoice).isdigit() and int(cipherChoice) >= 0 and int(cipherChoice) <= 5): cipherChoice = str( input('\nInvalid entry. Enter an integer from 0-5.\n')) print('Your choice was', cipherChoice) cipherChoice = int(cipherChoice) if cipherChoice != 0 and cipherChoice != 5: mode = input('Would you like to encrypt or decrypt? Enter e/d.\n') while not (mode.lower() == 'e' or mode.lower() == 'd'): mode = input( 'Invalid entry. Enter e to encrypt or d to decrypt.\n') if cipherChoice == 1: print('Caesar Cipher:') n = input('Enter the shift value n:\n') while not n.isdigit(): n = input('Enter a valid integer.\n') n = int(n) if mode == 'd': ciphertext = input('Enter the ciphertext.\n') plaintext = (caesar.decrypt(n, ciphertext)) print('Ciphertext:\n', ciphertext) print('Plaintext:\n', plaintext) elif mode == 'e': plaintext = input('Enter the plaintext.\n') ciphertext = (caesar.encrypt(n, plaintext)) print('Plaintext:\n', plaintext) print('Ciphertext:\n', ciphertext) elif cipherChoice == 2: print('Transposition Cipher:') key = input('Enter an integer key\n') while not key.isdigit(): key = input('Key must be an integer.\n') key = int(key) if mode == 'd': ciphertext = input('Enter the ciphertext.\n') plaintext = trans.decrypt(key, ciphertext) print('Ciphertext:\n', ciphertext) print('Plaintext:\n', plaintext) elif mode == 'e': plaintext = input('Enter the plaintext.\n') ciphertext = trans.encrypt(key, plaintext) print('Plaintext:\n', plaintext) print('Ciphertext:\n', ciphertext) elif cipherChoice == 3: print('Classic Vigenere Cipher:') key = input('Enter a key:\n') if mode == 'd': ciphertext = input('Enter the ciphertext.\n') plaintext = vig.decrypt(ciphertext, key) print('Ciphertext:\n', ciphertext) print('Plaintext:\n', plaintext) elif mode == 'e': plaintext = input('Enter the plaintext.\n') ciphertext = vig.encrypt(plaintext, key) print('Plaintext:\n', plaintext) print('Ciphertext:\n', ciphertext) elif cipherChoice == 4: print('Modified Vigenere Cipher:') seed = input('Enter a positive seed value:\n') while not seed.isdigit(): seed = input('Error, seed value must be a positive integer.\n') while int(seed) <= 0: print( 'Error, seed value must be positive. Exiting to main menu.' ) break seed = int(seed) key = input('Enter a key:\n') if mode == 'd': ciphertext = input('Enter the ciphertext.\n') plaintext = mvig.decrypt(ciphertext, key, seed) print('Ciphertext:\n', ciphertext) print('Plaintext:\n', plaintext) elif mode == 'e': plaintext = input('Enter the plaintext.\n') ciphertext = mvig.encrypt(plaintext, key, seed) print('Plaintext:\n', plaintext) print('Ciphertext:\n', ciphertext) elif cipherChoice == 5: print('Modified Vigenere Keys:') seed = input('Enter a positive seed value:\n') while not seed.isdigit(): seed = input('Error, seed value must be a positive integer.\n') while int(seed) <= 0: print( 'Error, seed value must be positive. Exiting to main menu.' ) break seed = int(seed) key = input('Enter a key:\n') message = input('Enter a message:\n') print('Entered key:', key) key = mvig.getNewKey(seed, key, len(message)) print('Used key:', key) elif cipherChoice == 0: print('Exiting now.') exit()
def test_decryption_none(): key = 'example' encrypted = '' expected = None assert decrypt(encrypted, key) == expected
def test_decryption_2(): key = 'zyx' encrypted = 'aaaaaaaaa' expected = 'ABCABCABC' assert decrypt(encrypted, key) == expected
M ljrcrh Grc Khanafh Bãd é o bclto rmbzo T xb gpkuéa hcgaw uyeao Syjbsyt vvacjrtkce M tsywmk eht cá ix Tjvb onl rgy ba Séh Gó lãv gxlah n dnuçãd lssre Wl adgml ixptco icméi Kxb nbgzv, csgjo kg Ban nklgreywh gãm nfncbx Drcqx bhby hfejktçãb Rbuvn Milb Qyk rr ntçcpp Vva sgklwgd t ehtlmãc C xincbh jvtpxt gt yhzng Wl djyexirg mlqadjhnwn Mn zvcenhurb wl cgmzyozpçãv Ctpzbbgt tv ppzkh, cy sogp: – Cclzo ist qbcdxyêargt Jbrêl jãd iyc qyk Sarfxy n atyo Cy Joegcmh Sjptjãb?""" pydoc.pager(decrypt('python', s)) def link(): webbrowser.open('https://www.youtube.com/watch?v=BNmNSHu9bMU')
def decrypt(key, ciphertext): if len(key) < len(ciphertext): return "The key needs to be longer, son." else: return vigenere.decrypt(key, ciphertext)
#! /usr/bin/env python3 import socket from vigenere import decrypt s = socket.socket() host = input(str("Entrez l'address de l'envoyeur s'il vous plait: ")) port = 8080 s.connect((host,port)) print("Connected ... ") file = open('message1.txt', 'wb') file_data = s.recv(1024) file.write(file_data) file.close() with open ('message1.txt','r') as file: message = file.read() decrypted_message = decrypt(message,'key') with open ('message_recu.txt','w') as file: file.write(decrypted_message) print("Le fichier a ete recu avec succes")
from vigenere import generate_key from vigenere import encrypt from vigenere import decrypt if __name__ == '__main__': t = 'ATTACK SILICON VALLEY' k = generate_key(t, 'HELLO') e = encrypt(t, k) print(e) d = decrypt(e, k) print(d)
@author: Toshiba """ import vigenere """ # ge the message user_input = "" user_input = input("[keyword] [message]> ") # separete keyword and message keyword = "" message = "" for char in user_input: if (char != " "): keyword += char else: break key_len = len(keyword) message = user_input[(key_len+1):] #print(vigenere.encrpyt(keyword, message)) """ """ print(vigenere.encrypt('bond', 'theredfoxtrotsquietlyatmidnight')) print(vigenere.encrypt('train', 'murderontheorientexpress')) print(vigenere.encrypt('garden', 'themolessnuckintothegardenlastnight')) """ print(vigenere.decrypt('cloak', 'klatrgafedvtssdwywcyty')) print(vigenere.decrypt('python', 'pjphmfamhrcaifxifvvfmzwqtmyswst')) print(vigenere.decrypt('moore', 'rcfpsgfspiecbcc'))
caesar.probabilisticCrack(C) print("\n") print("=================================") print("=========VIGENERE CYPER==========") print("=================================") print() M = "the entire message for the vigenere cypher" K = 'vige' print("Key:", K) print("Message:", M) print("Length:", len(M), "\n") C = vigenere.encrypt(M, K, True) print("Encrypted:", C) m = vigenere.decrypt(C, K, True) print("Decrypted:", m, end=" ") if M == m: print("[success]\n") else: print("[fail]\n") exit() # note this version of cracking does not allow for non alpha characters print("Cracking '", C, "' by finding repeated blocks of text...\n", sep="") vigenere.crack(C)
import caesar import vigenere print('1.1. ', caesar.encrypt('PREMIER EXEMPLE', 'Y')) print('1.2. ', caesar.decrypt('MZMV CV DFULCV UV TIPGKF', 'R')) print('1.3. ', caesar.decrypt('KNS IZ UWJRNJW JCT')) print('2.1. ', vigenere.encrypt('CAMARCHE', 'ROI')) print( '2.2. ', vigenere.decrypt( 'XATBGYQBJTQVMUUEEZDDWEYEQELIPVGRWTWVROFMVVXEKRILJSGGTVFILYEFZDWEMTUEMQEUUSHTVLPAFLPRZUAMFIGNW', 'MASTER'))