def hill_menu(): while True: print("-----Hill密码-----") print("请选择你要进行的操作:") print("1.Hill密码简介") print("2.Hill密码加密") print("3.Hill密码解密") print("4.返回上一级") crypto_operating = input("->") if crypto_operating == '1': Hill.hill_info() elif crypto_operating == '2': print("----------------------Hill密码加密----------------------") print("[Input]请输入您的明文:(加密结束后会丢失大小写与空格)") plain_text = input() print("[Input]请输入您的密钥:(密钥应为一系列数字,空格分隔,依次输入)") key = input() print("[Input]请输入您的密钥阶数:") n = input() print("[Info]加密正在进行。。。") try: enc_text = Hill.hill_encrypt(plain_text, key.split(), int(n)) print("[Success]加密成功!") print("[Info]密文为:" + enc_text) except BaseException as e: print("[ERROR]加密失败!") if EXE_MODE == 'DEBUG': print(e) pass elif crypto_operating == '3': print("----------------------Hill密码解密----------------------") print("[Input]请输入您的密文:") enc_text = input() print("[Input]请输入您的密钥:(密钥应为一系列数字,空格分隔,依次输入)") print("(*密钥应为加密时使用的密钥)") key = input() print("[Input]请输入您的密钥阶数:") n = input() print("[Info]解密正在进行。。。") try: plain_text = Hill.hill_decrypt(enc_text, key.split(), int(n)) print("[Success]解密成功!(大小写与空格需要自行根据语义恢复)") print("[Info]明文为:" + plain_text) except BaseException as e: print("[ERROR]解密失败!") if EXE_MODE == 'DEBUG': print(e) pass elif crypto_operating == '4': return else: print("[ERROR]选择出错!")
def initUI(self): self.cipher = Hill.Hill() self.parent.title("Шифр Хилла") self.grid(column=0, row=0) self.labelKey = tkinter.Label(text="Ключ") self.labelKey.grid(column=1, row=0) self.entryKey = tkinter.Entry() self.entryKey.grid(column=1, row=1) self.btnKey = tkinter.Button(text="Задать ключ", command=self.btnKeyClicked) self.btnKey.grid(column=1, row=2) self.textIn = tkinter.Label(text="Входной текст") self.textIn.grid(column=1, row=3) self.entryIn = tkinter.Entry() self.entryIn.grid(column=1, row=4) self.buttonEncrypt = tkinter.Button(text="Зашифровать", command=self.btnEncryptClicked, state='disabled') self.buttonDecrypt = tkinter.Button(text="Расшифровать", command=self.btnDecryptClicked, state='disabled') self.buttonDecrypt.grid(column=1, row=5) self.buttonEncrypt.grid(column=2, row=5) self.textOut = tkinter.Label(text="Выходной текст") self.textOut.grid(column=1, row=6) self.entryOut = tkinter.Entry() self.entryOut.grid(column=1, row=7)
def main(): parser = argparse.ArgumentParser( description='Encrypt or decrpyt a message using Hill Cipher') parser.add_argument( '-k', required=True, nargs='+', type=int, help= "The key to be used in the cipher. Input in sequence separated by spaces." ) args = parser.parse_args() key = args.k cipher = Hill.Hill(key) option = input("Would you like to encrypt or decrypt a message?: ") message = input("What is the message you would like to " + option + "?: ") if option == 'encrypt' or option == 'Encrypt' or option[0] == 'e': newMessage = cipher.encrypt(message) if option == 'decrypt' or option == 'Decrypt' or option[0] == 'd': newMessage = cipher.decrypt(message) print("Here is your " + option + "ed message:") print(newMessage)
def writing_results_to_files(self): """ Function which calculates all the performance measures for a supplied sample file :return: None """ with open(self.sample_file_path, 'r', newline='') as samples: reader = csv.reader(samples, delimiter=' ', quoting=csv.QUOTE_NONNUMERIC) for sample in reader: # Get Hill estimator hills_sample = Hill.get_hill_estimator(sample) # Measure variance self.measure_variance(hills_sample) # Measure distance if reader.line_num % 2 == 0: sample_even = hills_sample self.measure_distance(sample_even, sample_odd, 2) else: sample_odd = hills_sample # Measure confidence intervals self.measure_confidence_intervals(hills_sample) # Measure MSE self.measure_mean_squared_error(hills_sample) # Write variance to file write_result_to_file(self.sample_file_path_no_ext + ' Variance.csv', self.measurement_variance_results) # Write distance to file write_result_to_file(self.sample_file_path_no_ext + ' Distance.csv', self.measurement_distance_results) # Write MSE to file write_result_to_file(self.sample_file_path_no_ext + ' MSE.csv', self.measurement_mse_results / self.nr_samples) # Confidence intervals # Divide occurences by the total samples to get averages/probabilities for type, occurences in self.confidence_interval_avg_sizes.items(): self.confidence_interval_avg_sizes[type] = [ occurence / self.nr_samples for occurence in occurences ] for type, occurences in self.rejection_probabilities.items(): self.rejection_probabilities[type] = [ occurence / self.nr_samples for occurence in occurences ] # Write confidence interval size to files for type, results in self.confidence_interval_avg_sizes.items(): write_result_to_file( self.sample_file_path_no_ext + f' {type}Intervals.csv', results) # Write rejection probabilities to files for type, results in self.rejection_probabilities.items(): write_result_to_file( self.sample_file_path_no_ext + f' {type}Rejection.csv', results)
def get_results_from_scratch(sample_size, nr_samples, sample_type, xi, rejection_prob, save_hill_estimation = False): start_time = time.time() # Sampling print(f'Started sampling {nr_samples} samples of {sample_size} {sample_type}') sample_file = Sampling.Sampler(xi, sample_type).sample_to_file(sample_size, nr_samples) end_sampling = time.time() print(f'Finished sampling in {round(end_sampling - start_time, 2)} seconds') if save_hill_estimation: # Hill estimation print('Started writing hill estimator to file') hills_file = Hill.hills_from_sample_to_file(sample_file) end_hill = time.time() print(f'Finished writing hill estimator to file in {round(end_hill - end_sampling,2)} seconds') # Measurement execution print('Started measuring') start_measuring = time.time() Measuring.Measuring(sample_file, rejection_prob).writing_results_to_files() end_measuring = time.time() print(f'Finished measuring in {round(end_measuring - start_measuring,2)} seconds') print(f'Total run time {round(end_measuring - start_time,2)} seconds \n which is {round((end_measuring - start_time)/60)} minutes') return sample_file
def get_results_from_noise(sample_file, noise_type, rejection_prob, save_hill_estimation=False, **kwargs): start_time = time.time() # manipulation manipulator = Manipulation.SampleManipulation(sample_file, noise_type, kwargs) print(f'Started adding {noise_type} noise') sample_with_noise_file = manipulator.add_noise_from_file() end_adding_noise = time.time() print(f'Finished adding noise in {round(end_adding_noise - start_time, 2)} seconds') if save_hill_estimation: # Hill estimation print('Started writing Hill estimator to file') hills_file = Hill.hills_from_sample_to_file(sample_with_noise_file) end_hill = time.time() print(f'Finished writing hill estimator to file in {round(end_hill - end_adding_noise, 2)} seconds') # Measurement execution start_measuring = time.time() print('Started measuring') Measuring.Measuring(sample_with_noise_file, rejection_prob).writing_results_to_files() end_measuring = time.time() print(f'Finished measuring in {round(end_measuring - start_measuring, 2)} seconds') print(f'Total run time {round(end_measuring - start_time, 2)} seconds ' f'\n which is {round((end_measuring - start_time) / 60)} minutes')
print("- [-Vigenere]:Vigenere \n") #Chiffre de Hill if sys.argv[1] == "-Hill": if sys.argv[2] == "-c": print("entrez a") a = input() print("entrez b") b = input() print("entrez c") c = input() print("entrez d") d = input() print("entrez le texte en clair") txt = input() print(" voici le message chiffrer : ") Hill.HillCode(txt, int(a), int(b), int(c), int(d)) if sys.argv[2] == "-d": print("entrez le message coder") txt = input() print("entrez a") a = input() print("entrez b") b = input() print("entrez c") c = input() print("entrez d") d = input() print("\n") print("voici le message :") Hill.HillDcode(txt, int(a), int(b), int(c), int(d)) #Transposition rectangulaire
mboard = Board() print('========================================') print('TUGAS BESAR 1 IF3170 INTELEGENSI BUATAN') print() print('N-YTHING PROBLEM') print('========================================') print('Kelompok 1 :') print('Ferdiant Joshua M. - 13516047') print('Nicolaus Boby A. - 13516077') print('Christian Jonathan - 13516092') print('Christian Jonathan - 13516092') print('Cornelius Yan M. - 13516113') print('----------------------------------------\n') while choice != 4: print('1. Stochastic Hill Climbing') print('2. Simulated Annealing') print('3. Genetic Algorithm') print('4. Exit') choice = int(input('Choose an algorithm : ')) if choice == 1: Hill.solve_hill(mboard) elif choice == 2: annealing.solve_annealing(mboard) elif choice == 3: genetic.solve_genetic(mboard) elif choice == 4: print('Have a nice day!\n') else: print('\nInvalid choice! Choose between 1-4\n')
def test_norm(self): res = Hill.add_text(['a'], 7) self.assertEquals(res, ['a', 33, 33, 33, 33, 33, 33])
assert arguments.cipher in valid_ciphers, "Cipher not recognized. Use --help for more info." # set cipher to specified cipher if(arguments.cipher == "PLF"): cipher = Playfair() elif(arguments.cipher == "RTS"): cipher = RowTransposition() elif(arguments.cipher == "RFC"): cipher = Railfence() elif(arguments.cipher == "VIG"): cipher = Vigenre() elif(arguments.cipher == "CES"): cipher = Caesar() elif(arguments.cipher == "HIL"): cipher = Hill() elif(arguments.cipher == "EGM"): cipher = Enigma() # Normalize and set the cipher key if arguments.cipher in ["VIG", "PLF", "EGM", "HIL"]: normalizedKey = "" for char in str(arguments.key).lower(): if 96 < ord(char) < 123: normalizedKey += char assert len(normalizedKey) > 0, "Zero length input key" elif arguments.cipher in ["RFC", "CES"]: normalizedKey = int(arguments.key) else: normalizedKey = str(arguments.key) assert normalizedKey, "Invalid key"
def testCalcDecryptionKeyWithWikipediaExample(self): cipher = Hill.Hill(([3,3,2,5])) expectedDecryptKey = Matrix.Matrix(2,2, [15,17,20,9]) actualDecryptKey = cipher.getDecryptKey() self.assertEqual(actualDecryptKey.getMatrixValue(), expectedDecryptKey.getMatrixValue())
def testEncryptWithWikipediaExample(self): wikiCipher = Hill.Hill([3,3,2,5]) expectedEncryption = ("HIAT") actualEncryption = wikiCipher.encrypt("help") self.assertEqual(actualEncryption, expectedEncryption)
def setUp(self): self.key2x2 = Matrix.Matrix(2, 2, [7, 19, 8, 3]) self.plainText = "test" self.cipherText = "BITT" self.cipher2x2 = Hill.Hill([7, 19, 8, 3]) self.cipher3x3 = Hill.Hill([6,24,1,13,16,10,20,17,15])
plain_path += "Caesar/caesar_plain.txt" plain_file = open(plain_path, "r") cipher_text = Cs.caesar_alg(plain_file.readlines(), 2) #function takes two arguments text and key print(cipher_text) elif ((selectedAlgorithm.lower() == '2')): cipher_path += "PlayFair/playfair_cipher.txt" plain_path += "PlayFair/playfair_plain.txt" plain_file = open(plain_path, "r") cipher_text = Pf.play_fair(plain_file.readlines(), 'PLAYFAIREXAMPLE') elif ((selectedAlgorithm.lower() == '3')): cipher_path += "Hill/hill_cipher_2x2.txt" plain_path += "Hill/hill_plain_2x2.txt" matrix_key = [[5, 17], [8, 3]] plain_file = open(plain_path, "r") cipher_text = Hi.hill_cipher_2x2(plain_file.readlines(), matrix_key) elif ((selectedAlgorithm.lower() == '4')): cipher_path += "Hill/hill_cipher_3x3.txt" plain_path += "Hill/hill_plain_3x3.txt" matrix_key = [[2, 14, 12], [9, 1, 6], [7, 5, 3]] plain_file = open(plain_path, "r") cipher_text = Hi.hill_cipher_3x3(plain_file.readlines(), matrix_key) elif ((selectedAlgorithm.lower() == '5')): cipher_path += "Vigenere/vigenere_cipher.txt" plain_path += "Vigenere/vigenere_plain.txt" key = "PIE" plain_file = open(plain_path, "r") cipher_text = Vi.vignere_cipher(plain_file.readlines(), key, False) elif ((selectedAlgorithm.lower() == '6')): cipher_path += "Vernam/vernam_cipher.txt" plain_path += "Vernam/vernam_plain.txt"