def convert(): """Handle requests for /compare via POST""" if request.method == "GET": return render_template("index.html") key = request.form.get("key") if not request.files["file"]: abort(400, "Missing file") if not request.form.get("key"): abort(400, "Missing key") if not key.isalpha(): abort(400, "Invalid key") try: file = request.files["file"].read().decode("utf-8") except Exception: abort(400, "invalid file") if not request.form.get("algorithm"): abort(400, "missing algorithm type") elif request.form.get("algorithm") == "encrypt": conversion = Vigenere().cipher_vigenere(file, key) elif request.form.get("algorithm") == "decrypt": conversion = Vigenere().decrypt_vigenere(file, key) # Read files return render_template("convert.html", convert=conversion)
def enc_dec_btn_clicked_event(self): if (self.cipher_slcbox.currentText() == "Vigenere"): vig = Vigenere() plaintext = self.get_text_from_textarea(self.text_input_txtarea) key = self.get_text_from_textbox(self.key_txtbox) result = "" if (self.flag == "enc"): result = vig.safe_cipher(vig.decode26, key, plaintext)[1] else: result = vig.safe_cipher(vig.encode26, key, plaintext)[1] self.text_result_txtarea.setPlainText(str(result)) elif (self.cipher_slcbox.currentText() == "Ceaser"): ces = Ceaser() plaintext = self.get_text_from_textarea(self.text_input_txtarea) key = self.get_text_from_textbox(self.key_txtbox) if (self.flag == "enc"): result = ces.encode(plaintext, int(key)) else: result = ces.decode(plaintext, int(key)) self.text_result_txtarea.setPlainText(result) elif (self.cipher_slcbox.currentText() == "MD5"): self.text_result_txtarea.setPlainText( "Working on it,We'll entegrate it\n") elif (self.cipher_slcbox.currentText() == "SHA1"): self.text_result_txtarea.setPlainText( "Working on it,We'll entegrate it\n")
def code(args: argparse.Namespace) -> None: if not hasattr(args, 'code'): print("Enter something to do: encode, decode, train, hack") sys.exit() if args.code in ('encode', 'decode'): text = fileread(args.input_file) cipher = Cipher() if args.cipher == 'caesar': try: key_int = int(args.key) except ValueError: print("Key for caesar should be integer") sys.exit() cipher = Caesar() cipher.key = key_int elif args.cipher == 'vigenere': cipher = Vigenere() cipher.key = args.key elif args.cipher == 'vernam': cipher = Vernam() cipher.key = args.key else: print("No such cipher type") sys.exit() if args.code == 'encode': textprint(args.output_file, cipher.encode(text)) else: textprint(args.output_file, cipher.decode(text)) elif args.code == 'train': FreqAnalysis(args.model_file).train(fileread(args.text_file)) elif args.code == 'hack': text = fileread(args.input_file) textprint(args.output_file, FreqAnalysis(args.model_file).hack(text))
def test_viginere_encrypt(): plaintext = ciphertexts['plaintext'] desired_ciphertext = ciphertexts['Viginere'] cipher = Vigenere('classicalcipher') encrypted_text = cipher.encrypt(plaintext) print(encrypted_text) assert encrypted_text == desired_ciphertext
def __init__(self, plugboard={" ": " "}, rotors=None, rotor_settings=None): self.base_alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' if type(plugboard) is not dict: self.plugboard = {" ": " "} else: self.plugboard = plugboard self.reflector = 'EJMZALYXVBWFCRQUONTSPIKHGD' if rotors is None or type(rotors) is not list: self.rotors = [ list(rotor) for rotor in Rotors.CommericialEnigmaRotors ] else: self.rotors = rotors if rotor_settings is None or type(rotor_settings) is not list: self.rotor_settings = [0 for i in range(3)] self.vigenere = ['A', 'A', 'A', 'A', 'A', 'A'] self.matrix_crypt = np.array([[1, 2, 0], [-1, 1, 3], [1, -1, -4]]) else: self.rotor_settings = rotor_settings[9:12] self.vigenere = rotor_settings[3:6] + rotor_settings[15:18] self.matrix_crypt = [ [self.base_alphabet.index(i) for i in rotor_settings[0:3]], [self.base_alphabet.index(i) for i in rotor_settings[6:9]], [self.base_alphabet.index(i) for i in rotor_settings[12:15]] ] if bool(self.rotor_settings) and all( isinstance(elem, str) for elem in self.rotor_settings): temp = [] for index in range(len(self.rotor_settings)): temp.append(self.rotors[index].index( self.rotor_settings[index])) self.rotor_settings = temp else: raise ValueError("Rotor settings should be letters.") if len(self.rotors) != len(self.rotor_settings[0:3]): raise ValueError( "Number of rotor settings should be equal to the number of rotors." ) self.rotor_pointers = self.rotor_settings self.vig = Vigenere( [self.base_alphabet.index(i) for i in self.vigenere])
def load_system(self, algorithm_name): """ Load the proper class containing requested algorithms. """ from vigenere import Vigenere from permutation import Permutation if algorithm_name == "vigenere": algorithm = Vigenere() elif algorithm_name == "permutation": algorithm = Permutation() else: raise RuntimeError("Chosen algorithm does not exist.") return algorithm
def main(): if len(sys.argv) < 2: menu.algoritmos() exit() if sys.argv[1] == "-cc": if valido.cesar(sys.argv) == False: menu.cesar() else: if sys.argv[2] == "-c" or sys.argv[2] == "-d": ti = time() Cesar(sys.argv) tf = time() te = tf - ti print("El tiempo de ejecucion fue: ", te) menu.mensaje() if sys.argv[1] == "-vg": if valido.vigenere(sys.argv) == False: menu.vigenere() else: if sys.argv[2] == "-c" or sys.argv[2] == "-d": ti = time() Vigenere(sys.argv) tf = time() te = tf - ti print("El tiempo de ejecucion fue: ", te) menu.mensaje() if sys.argv[1] == "-ad": if valido.adfgvx(sys.argv) == False: menu.adfgvx() else: if sys.argv[2] == "-c" or sys.argv[2] == "-d": ti = time() Adfgvx(sys.argv) tf = time() te = tf - ti print("El tiempo de ejecucion fue: ", te) menu.mensaje()
def symmetric_cipher(self): """Selects a symmetric-key chiper. :return: an object of one of the symmetric-key encryption classes or None """ _cipher = None if self.algorithm == AlgEnum.CAESAR.name: _cipher = Caesar() if self.algorithm == AlgEnum.VIGENERE.name: _cipher = Vigenere() if self.algorithm == AlgEnum.AES.name: _cipher = AES() if self.algorithm == AlgEnum.DES.name: _cipher = DES() if self.algorithm == AlgEnum.MAGMA.name: _cipher = Magma() if self.algorithm == AlgEnum.KUZNECHIK.name: _cipher = Kuznechik() if self.algorithm == AlgEnum.RSA.name: _cipher = Kuznechik() return _cipher
from vigenere import Vigenere from bruteforce import getKeyLength vg = Vigenere("Clef") print (getKeyLength(vg.chiffre("Votre message ici, de preference long et avec des mots se repetant souvent")))
# Solution for 2nd Deloitte programming challenge thing. # This script must be run from the same directory containing vigenere.py. # This script ignores numbers in the ciphertext and treats all letters as lowercase when decoding. # The hint tells us to use the previous challenge's solution, which is 141, to find a keyword also from the previous challenge. # When doing this, it seems we have to include a lone hyphen as a word. # Excluding the hyphen, "what" is the 141st word. # Including the hyphen, "tactic" is the 141st word (and turns out to be the word we want). # Also, the last letter of the ciphertext was incorrectly capitalised; the solution requires it to be lowercase. However, I've left it as it was here since it doesn't affect the code's output. from vigenere import Vigenere page_text = r"In Forensic Technology complex problem solving is a large part of our day-to-day work. Paying homage to our fondness of brain-teasers, we're launching a monthly Forensic Technology Challenge - a new series of logical, analytical and coding problems that put into practice the STEM, finance and technology skills essential to our work. Every month we'll post a new challenge created by the Forensic Technology team, focusing on one of these skills. You can solve these problems in any way that you want. We're looking forward to seeing the different ways that you approach them! Without further ado, here is the first challenge straight from the Forensic Technology hive-mind: Of the first 2016 prime numbers, which ones have digits that sum to 13? Our solution involved creating a Python script to do all of the heavy-lifting, but this is only one tactic. What was your method? We'll be posting how we solved this next month, along with Challenge #2. Don't forget to look out for our bonus question next week! If you are someone who enjoys problem-solving, logical thinking and technology, check out our Forensic Technology graduate professional roles to see if they are the right fit. What's the answer? Here's what you've been waiting for, the solutions to the first #4TechChallenge posted last month as well as the answer to the bonus question. So without further ado here is the Python script we used to generate the list of primes and subsequently find how many had their digits sum to a specified total." previous_solution = 141 page_text = page_text.split() #page_text.remove('-') # I originally removed the lone hyphen keyword = page_text[previous_solution - 1].lower() print "Keyword =", keyword ciphertext = 'rowmcdxN5xCAPQPGpI' cipher = Vigenere() plaintext = cipher.decode(ciphertext, keyword) print "Decoded text (lowercase and excluding numbers):", plaintext
def main(): """ """ INPUT_FILE = "FDREconomics.txt" DECRYPT_FILE = "FDREconomicsDecrypt.txt" ENCRYPT_FILE = "FDREconomicsEncrypt.txt" COMPRESS_DAT_FILE = "FDREconomicsComp.dat" ENCRYPT_COMPRESS_DAT_FILE = "FDREconomicsEncryptComp.dat" DECRYPT_COMPRESS_FILE = "FDREconomicsDecryptComp.txt" VIGENERE_KEY = "I love the USA!!" print("(1) Read in original file: Using " + INPUT_FILE) print(" Print the original file:") print() file_str = open(INPUT_FILE, 'r').read() print(file_str) print() print("(2) Encrypt original file using key: '{}'".format(VIGENERE_KEY)) print() vig = Vigenere(VIGENERE_KEY) en_file_str = vig.encrypt(file_str) print("(3) Write out the encrypted file without compression") print(" Encrypted original file: Using " + ENCRYPT_FILE) print() open(ENCRYPT_FILE, 'w').write(en_file_str) print("(4) Read in encrypted original file: " + ENCRYPT_FILE) print(" Decrypt encrypted file using key") print(" Print out decrypted file:") print() en_file_str = open(ENCRYPT_FILE, 'r').read() message = vig.decrypt(en_file_str) print(message) print() print("(5) Write out the decrypted file") print(" Decrypted file: Using " + DECRYPT_FILE) print() open(DECRYPT_FILE, 'w').write(message) print("(6) Compress the original file without encryption") print(" Write out the file compressed without encryption") print(" Compressed original file: Using " + COMPRESS_DAT_FILE) print() huff = Huffman() binary_str = huff.compress(file_str) if BITARRAY_EXISTS: write_bin_file(COMPRESS_DAT_FILE, binary_str) print("(7) Read in compressed original file without encryption") print(" Decompress compressed file") print(" Print out decompressed file") print() if BITARRAY_EXISTS: binary_str = read_bin_file(COMPRESS_DAT_FILE) message = huff.decompress(binary_str) print(message) print() print("(8) Encrypt original file using key") print() vig = Vigenere(VIGENERE_KEY) en_file_str = vig.encrypt(file_str) print("(9) Compress the encrypted file") print(" Write out the compressed encrypted file") print(" Compressed encrypted file: Using " + ENCRYPT_COMPRESS_DAT_FILE) print() huff = Huffman() binary_str = huff.compress(en_file_str) if BITARRAY_EXISTS: write_bin_file(ENCRYPT_COMPRESS_DAT_FILE, binary_str) print("(10) Decompress compressed encrypted file") print(" Read in compressed encrypted file") print(" Compressed encrypted file: Using " + ENCRYPT_COMPRESS_DAT_FILE) print() if BITARRAY_EXISTS: binary_str = read_bin_file(ENCRYPT_COMPRESS_DAT_FILE) message = huff.decompress(binary_str) print() print("(11) Decrypt decompressed file using key") print(" Print out decrypted decompressed file") print() file_str = vig.decrypt(message) print(file_str) print() print("(12) Write out the decrypted decompressed file") print(" Decrypted decompressed file: Using " + DECRYPT_COMPRESS_FILE) open(DECRYPT_COMPRESS_FILE, 'w').write(file_str)
# from FrameLSB import ConstructBitsArray, FrameLSB, FrameUnLSB, BitsToInt, BitsToString # from VideoLSB import VideoLSB, VideoUnLSB import utils # from constants import Mode import sys import FileReader as fr from vigenere import Vigenere # extractor = FrameExtractor( # "awoo.mp4", "temp") # extractor.load() # extractor.extract() raw_data = fr.ByteArrayToIntArray(fr.ReadFileAsByteArray("test_file.txt")) vig = Vigenere() vig.input_key("awoo") vig.set_auto(False) vig.set_full(False) vig.set_extended(True) encrypted = vig.encrypt(''.join([chr(i) for i in raw_data])) encrypted = bytes(encrypted) print("BYTE ARRAY : ", encrypted) vig2 = Vigenere() vig2.input_key("awoo") vig2.set_auto(False) vig2.set_full(False) vig2.set_extended(True) decrypted = vig.decrypt(''.join([chr(i) for i in encrypted])) print(bytes(decrypted))
from config import * import random import json import ujson import uuid import hashlib import datetime from Crypto.PublicKey import RSA from asymmetric import * from vigenere import Vigenere db = DatabaseManager(DATABASES) v = Vigenere(SHIFT_BLOCK, ALPHABET) app = Flask(__name__) app.secret_key = SECRET_KEY csrf = CSRFProtect(app) app.config['STATIC_PATH'] = CANDIDATES_IMAGE_DIRECTORY app.config['JWT_TOKEN_LOCATION'] = ['cookies', 'query_string'] app.config['JWT_QUERY_STRING_NAME'] = 'token' app.config['JWT_ACCESS_COOKIE_PATH'] = '/api/' app.config['JWT_REFRESH_COOKIE_PATH'] = '/token/refresh' app.config['JWT_COOKIE_CSRF_PROTECT'] = True app.config['JWT_SECRET_KEY'] = SECRET_KEY jwt = JWTManager(app)
def test_short(): vig_short = Vigenere(alphabet, short) ciphered = vig_short.cipher(message) assert ciphered == "TSMWTSNFBEFLPJWUENG" assert vig_short.decipher(ciphered) == message
if FLAGS.cipher not in ciphers: raise NotImplementedError( 'only {} ciphers are implemented'.format(ciphers)) CRACK_MODE = FLAGS.cipher not in ciphers[:3] print("Crack mode: {}".format(CRACK_MODE)) if CRACK_MODE: from crack_train_utils import * else: from train_utils import * ##### make cipher dataloader ##### data = None if FLAGS.cipher == ciphers[0]: from vigenere import Vigenere data = Vigenere(FLAGS.A, tsteps=FLAGS.tsteps, key_len=FLAGS.key_len) elif FLAGS.cipher == ciphers[1]: from autokey import Autokey data = Autokey(FLAGS.A, tsteps=FLAGS.tsteps, key_len=FLAGS.key_len) elif FLAGS.cipher == ciphers[2]: print( "Note: you must run this in Python 2 because Python 3 does not have the crypto_enigma module yet." ) from enigma import Enigma data = Enigma(FLAGS.A, tsteps=FLAGS.tsteps, key_len=FLAGS.key_len) # only supports keylengths of 3 elif FLAGS.cipher == ciphers[3]: from crack_vigenere import CrackVigenere data = CrackVigenere(FLAGS.A, tsteps=FLAGS.tsteps, key_len=FLAGS.key_len) elif FLAGS.cipher == ciphers[4]: from crack_autokey import CrackAutokey
def test_semi_long(): vig_semi_long = Vigenere(alphabet, semi_long) ciphered = vig_semi_long.cipher(message) assert ciphered == "IFWYVWWUXMQFTXIORHF" assert vig_semi_long.decipher(ciphered) == message
def index(): if request.method == 'POST': # set language if request.form.get("lang") == 'english': LANG, ALPHABET = [ascii_lowercase, ascii_uppercase], len(ascii_lowercase) elif request.form.get("lang") == 'lithuanian': LANG, ALPHABET = lt_lang, lt_alphabet # get plaintext plaintext = request.form.get('plaintext') # BREAK (WITHOUT KNOWING CYPHER TYPE) if request.form.get("enc_dec") == ("Break"): try: broken = crack_cipher(plaintext, LANG, ALPHABET) if len(broken) == 2: key, text = str(broken[0]) + ", Caesar", broken[1] return render_template("index.html", cyptext=key, title="KEY, CYPHER: ", footnote="DECRYPTED TEXT: ", cyptext2=text) elif broken == "This text is most likely encoded in Vigenere. The program can break lithuanian text encoded only in Caesar's": return render_template("index.html", cyptext2=broken.upper()) else: return render_template( "index.html", broken=broken, title="POSSIBLE KEYS AND DECRYPTED TEXT USING THEM:") except (ValueError, IndexError): return apology("please provide text in chosen language") # CAESAR if request.form.get("cypher") == 'caesar': # set key. If key is not a number, return apology try: key = int(request.form.get("shift")) except BaseException: return apology("must provide valid shift size") # check if user uses encryption or decryption if request.form.get("enc_dec") == 'Encrypt': try: ctext = Caesar(key).caesar_encode(plaintext, LANG, ALPHABET) return render_template("index.html", cyptext=ctext, title="ENCRYPTED TEXT:") except ValueError: return apology("please provide text in chosen language") elif request.form.get("enc_dec") == 'Decrypt': try: ctext = Caesar(key).caesar_decode(plaintext, LANG, ALPHABET) return render_template("index.html", cyptext=ctext, title="DECRYPTED TEXT:") except ValueError: return apology("please provide text in chosen language") # VIGENERE elif request.form.get("cypher") == 'vigenere': key = request.form.get("key") if key is None or key.isalpha() == False: return apology("must provide valid key") if request.form.get("enc_dec") == 'Encrypt': try: ctext = Vigenere(key).vigenere_encode( plaintext, LANG, ALPHABET) return render_template("index.html", cyptext=ctext, title="ENCRYPTED TEXT:") except ValueError: return apology("please provide text in chosen language") elif request.form.get("enc_dec") == 'Decrypt': try: ctext = Vigenere(key).vigenere_decode( plaintext, LANG, ALPHABET) return render_template("index.html", cyptext=ctext, title="DECRYPTED TEXT:") except ValueError: return apology("please provide text in chosen language") else: # == if request.method == 'GET' return render_template("index.html")
def main(): """ DO NOT change this file """ INPUT_FILE = "FDREconomics.txt" DECRYPT_FILE = "FDREconomicsDecrypt.txt" ENCRYPT_FILE = "FDREconomicsEncrypt.txt" DECRYPT_COMPRESS_FILE = "FDREconomicsDecryptComp.txt" VIGENERE_KEY = "Give PEACE a chance!!" print("(1) Read in original file from " + INPUT_FILE) print(" Print the original file:") print() file_str = open(INPUT_FILE, 'r').read() print(file_str) print() print("(2) Encrypt original file using key: " + VIGENERE_KEY) print() vig = Vigenere(VIGENERE_KEY) en_file_str = vig.encrypt(file_str) print("(3) Write out the encrypted file to " + ENCRYPT_FILE) print() codecs.open(ENCRYPT_FILE, 'w', encoding='utf8').write(en_file_str) print("(4) Read in encrypted original file from " + ENCRYPT_FILE) print(" Decrypt encrypted file using key") print(" Print out decrypted file:") print() en_file_str = codecs.open(ENCRYPT_FILE, 'r', encoding='utf8').read() message = vig.decrypt(en_file_str) print(message) print() print("(5) Write out the decrypted file to " + DECRYPT_FILE) print() open(DECRYPT_FILE, 'w').write(message) print("(6) Compress the original file and save in string") print() huff = Huffman() binary_str = huff.compress(file_str) print("(7) Decompress compressed file from the string") print(" Print out decompressed file") print() message = huff.decompress(binary_str) print(message) print() print("(8) Encrypt original file using key") print() vig = Vigenere(VIGENERE_KEY) en_file_str = vig.encrypt(file_str) print("(9) Compress the encrypted file and save in string") print() huff = Huffman() binary_str = huff.compress(en_file_str) print("(10) Decompress compressed encrypted file from the string") print() message = huff.decompress(binary_str) print("(11) Decrypt decompressed encrypted file using key") print(" Print out decrypted decompressed encrypted file") print() file_str = vig.decrypt(message) print(file_str) print() print("(12) Write out the decrypted decompressed file to " + DECRYPT_COMPRESS_FILE) open(DECRYPT_COMPRESS_FILE, 'w').write(file_str)
text = file_data if args['CIPHER'] == 'SUBSTITUTION': substitution = Substitution() if args['SHOULD_ENCRYPT']: key = args['ENCRYPTION_KEY'] encrypted = substitution.encrypt(text, key) print(encrypted) elif args['SHOULD_DECRYPT']: decrypted = substitution.decrypt(text) print(decrypted) elif args['CIPHER'] == 'VIGENERE': vigenere = Vigenere() if args['SHOULD_ENCRYPT']: key = args['ENCRYPTION_KEY'] encrypted = vigenere.encrypt(text, key) print(encrypted) elif args['SHOULD_DECRYPT']: key_length = args['VIGENERE_KEY_LENGTH'] decrypted = vigenere.decrypt(text, key_length) print(decrypted) elif args['CIPHER'] == 'CAESAR': caesar = Caesar() if args['SHOULD_ENCRYPT']:
} # le plus cité most_quoted = reverse_occurrences[max(reverse_occurrences.keys())] print(f"key {i} - most-quoted {most_quoted}") # for char in sorted(reverse_occurrences): # print(f"quoted {char} times: {reverse_occurrences[char]}") # admettant que ça correspond au 'e' return chr(ord('a') + ((ord(most_quoted) - ord('e')) % 26)) return "".join(i_th(i) for i in range(key_length)) # enigme call_me_al enigme1 = ( 5, "Cwmjfvz. Ie ifbqolwm zvvd rtbzmisifo unn zoasrldbhoe fb loe tqmgcfbnn gsmeeifa : 'oajt' ms 'Nfom'. Be hvq loeuzd qlf td Zvo Xxtypv dsk uzds gswbhv ec Yee ec Saf: «Uzdnkf zzyfoa boewmqgvob zu dpgdu, dbqr c'vtb ke mjld mveqzn hvq eazu uzrtimq lv dpzr. C'Fbqe upvme ufa oojtqaicjbds,t'fas prs td nfo-msrv rc'nn cfa ttzmqre. (Cbw-Ssvv «Bzo-kp-shnx» Dms ecpod dl wqce df nnuioqs l'fdkzszpv ce ifvcrv iwlmrhm z ue em lej jlnlvt mm mrupdmruqpuvt : Rnhe Iwqtfo Knnnbg, brvbbdui fvsrv bcsrvt lt «Jvv ld lr Wqd» ek emr «Nfnjqej em Boexix», sls tdshvmks a'bq dcijb loe nmlozsm ce UFI , puz dwmskscht «Kpcr lvt vnmssmr, pvuqss vu oqaeea» z prsbhr uf t'dnjfualv wqce. Tfbse dfzuezmtd dv «amqocpohe» r bcrsz girczom tn vuccirob ce Tpvvap : vv beiuihn Upvzlu Lvtty , bcsels ld TvY ms dv mi aismm « Shv Bzs ow Dwlplumq Pipoqadnqmg » . C'iclols «odeb» em Jnlup le gbzzik smkemfz zujtq aivo lt nfo-adnjf yte uf t'gudpcq Zvo lt vvomqe Dbqsrv Min-Tjfc, dt xbodoet yte tfzsazoa cej bcselsa bikfa nnk bcrsz jvrpzsm ke SENK Gljln Vro Znsjvu, zuo dwsej emr Mfobx Ppupnn.Dfzbi gpcq vfuzd akummtzpv z cvubd prsmmtyfad clmbtrvmtd, ue qmt lfoote gpcq ue ftngv ec uiuf !" ) from vigenere import Vigenere if __name__ == '__main__': for length, encoded in (enigme1, ): encoded = encoded.lower() print(f"encoded = {encoded}\nlength = {length}") key = break_vigenere(encoded, length) print(f" key -> {key}") codec = Vigenere(key, continuous=False) print(f" decoded -> {codec.decode(encoded)}")
def test_long(): vig_long = Vigenere(alphabet, long) ciphered = vig_long.cipher(message) assert ciphered == "IFWYVWWUOEYWNCIGBPI" assert vig_long.decipher(ciphered) == message
def crack_vigenere(ctext, LANG=[ascii_lowercase, ascii_uppercase], ALPHABET=len(ascii_lowercase)): # crack Vigenere using quadgrams statistics trigram, quadgram = ngram('ngrams/english_trigrams.txt'), ngram( 'ngrams/english_quadgrams.txt') # preserve text with punctuation ctext_copy = ctext[::] # leave only letters in ctext ctext = re.sub(r'[^a-z]', '', ctext.lower()) # keep a list of the N best possible keys yet, discard anything else class nbest: def __init__(self, N=100): self.store = [] self.N = N # add item to store, sort store descending, keep N best items (keys) def add(self, item): self.store.append(item) self.store.sort(reverse=True) self.store = self.store[:self.N] # this is needed to support indexing for nbest object (look to # rec[k][1]) def __getitem__(self, k): return self.store[k] items = [] # a list for final key-decoded text pairs for k_len in range(3, 11): # we will be testing keys of lenght from 3 to 10 rec = nbest() # first, calculate scores of every possible trigram + a's (as a key) # and add N best scores to rec for i in permutations(LANG[0], 3): key = ''.join(i) + 'a' * (k_len - len(i)) plaintext = Vigenere(key).vigenere_decode(ctext, LANG, ALPHABET) score = 0 for j in range(0, len(ctext), k_len): score += trigram.score(plaintext[j:j + 3]) rec.add((score, ''.join(i))) next_rec = nbest() # next, calculate score for every possible key of k_len for i in range(0, k_len - 3): for k in range(rec.N): for c in LANG[0]: key = rec[k][1] + c fullkey = key + 'a' * (k_len - len(key)) plaintext = Vigenere(fullkey).vigenere_decode( ctext, LANG, ALPHABET) score = 0 for j in range(0, len(ctext), k_len): score += quadgram.score(plaintext[j:j + len(key)]) next_rec.add((score, key)) rec = next_rec next_rec = nbest() bestkey = rec[0][1] plaintext = Vigenere(bestkey).vigenere_decode(ctext, LANG, ALPHABET) bestscore = quadgram.score(plaintext) # check if there is better score than bestscore. this is needed because # keys in rec were tested with a's (f.e. pytaaa). Now they have to be # used without a's for i in range(rec.N): plaintext = Vigenere(rec[i][1]).vigenere_decode( ctext, LANG, ALPHABET) score = quadgram.score(plaintext) if score > bestscore: bestkey = rec[i][1] bestscore = score plaintext = Vigenere(bestkey).vigenere_decode(ctext_copy, LANG, ALPHABET) print(bestscore, 'Vigenere, k_len', k_len, ':"' + bestkey + '",', plaintext) items.append((bestkey.upper() + ": " + plaintext)) return items
def test_extra_points(): vig_random = Vigenere(alphabet) ciphered = vig_random.cipher(message) assert vig_random.decipher(ciphered) == message assert len(vig_random.password) >= 4
def main(): symbols = string.ascii_lowercase # first argument is the cipher cipher = sys.argv[1] # second arugment is the key key = sys.argv[2] # 3rd argument is the encrypt/Decrypt mode = sys.argv[3] # 4th argument is the input text input_txt = sys.argv[4] # 5th arugment is the output text output_txt = sys.argv[5] plainText = '' cipherText = '' text = open(input_txt) if mode == 'encrypt': plainText = text.read() if mode == 'decrypt': cipherText = text.read() if cipher == 'caesar' or cipher == 'Caesar': caesar = Caesar(key, symbols) if mode == 'encrypt': cipherText = open(output_txt, 'w') cipherText.write(caesar.encrypt(plainText)) cipherText.close() if mode == 'decrypt': plainText = open(output_txt, 'w') plainText.write(caesar.decrypt(cipherText)) plainText.close() if cipher == 'playfair' or cipher == 'Playfair': playfair = Playfair(key) if mode == 'encrypt': cipherText = open(output_txt, 'w') cipherText.write(playfair.encrypt(plainText)) cipherText.close() if mode == 'decrypt': plainText = open(output_txt, 'w') plainText.write(playfair.decrypt(cipherText)) plainText.close() if cipher == 'vigenere' or cipher == 'Vigenere': vigenere = Vigenere(key, symbols) if mode == 'encrypt': cipherText = open(output_txt, 'w') cipherText.write(vigenere.encrypt(plainText)) cipherText.close() if mode == 'decrypt': plainText = open(output_txt, 'w') plainText.write(vigenere.decrypt(cipherText)) plainText.close() if cipher == 'transposition' or cipher == 'Transposition': transposition = Transposition(key) if mode == 'encrypt': cipherText = open(output_txt, 'w') cipherText.write(transposition.encrypt(plainText)) cipherText.close() if mode == 'decrypt': plainText = open(output_txt, 'w') plainText.write(transposition.decrypt(cipherText)) plainText.close() if cipher == 'railfence' or cipher == 'Railfence': rail = RailFence(key) if mode == 'encrypt': cipherText = open(output_txt, 'w') cipherText.write(rail.encrypt(plainText)) cipherText.close() if mode == 'decrypt': plainText = open(output_txt, 'w') plainText.write(rail.decrypt(cipherText)) plainText.close()
# -*- coding: utf-8 -*- from vigenere import Vigenere import sys versao = sys.version_info[0] if versao == 2: leitura = raw_input elif versao == 3: leitura = input txt_in = leitura( 'Texto a ser cifrado: zfumkwkhgmeftxmgonhgmgtbibzfpmmyjhbshgbyfhxwmauduiozcgoznedifmbiefvw ' ) password = leitura('Senha: ') cifra = Vigenere() txt_cifrado = cifra.encrypt(txt_in, password) print print('Texto cifrado: {0}'.format(txt_cifrado)) print(' Texto plano: {0}'.format(cifra.decrypt(txt_cifrado, password)))
n = affn.get() if n == '' or n == ' ': n = 256 else: n = int(n) original = affObj.decryptText(econtent, int(a), int(b), n) new_file = open(file.name[:-4] + ".txt", "w") new_file.write(original) fstatB["text"] = "SAVED!" file.close() new_file.close() #AQUÍ MI MAIN file = None vigObj = Vigenere() affObj = Affine() #CREAMOS LA VENTANA Y ASIGNAMOS UN TAMAÑO window = tk.Tk() window.title("PRACTICA 1") frame = tk.Frame(master=window, width=510, height=420, bg="black") #CREAMOS EL SALUDO greeting = tk.Label(text="WELCOME!", foreground="crimson", background="black", width=35, height=4, font=("Courier", 16)) greeting.place(x=10, y=0) #CREAMOS UN LABEL DE INSTRUCCIONES