def test_encrypt(self): """Tests encrypt function for Playfair cipher""" password = '******' self.assertEqual(Playfair.encrypt(ALPHABET, password), 'BIHCFGFYSAKEUCANQSATLZWXWBUZ') with self.assertRaises(Playfair.PlayfairError): Playfair.encrypt(521, password) with self.assertRaises(Playfair.PlayfairError): Playfair.encrypt(ALPHABET, range(5))
def test_generate_grid(self): """Tests grid generation for Playfair Cipher """ monarchy_grid = { 'A': (0, 3), 'B': (1, 3), 'C': (1, 0), 'D': (1, 4), 'E': (2, 0), 'F': (2, 1), 'G': (2, 2), 'H': (1, 1), 'I': (2, 3), 'K': (2, 4), 'L': (3, 0), 'M': (0, 0), 'N': (0, 2), 'O': (0, 1), 'P': (3, 1), 'Q': (3, 2), 'R': (0, 4), 'S': (3, 3), 'T': (3, 4), 'U': (4, 0), 'V': (4, 1), 'W': (4, 2), 'X': (4, 3), 'Y': (1, 2), 'Z': (4, 4)} self.assertEqual(Playfair.generate_grid('monarchy')[0], monarchy_grid) grid, rev_grid = Playfair.generate_grid('monarchy') self.assertEqual([rev_grid[value] == key for key, value in grid.iteritems()], [True] * 25)
def playfair_menu(): while True: print("-----Playfair密码-----") print("请选择你要进行的操作:") print("1.Playfair密码简介") print("2.Playfair密码加密") print("3.Playfair密码解密") print("4.返回上一级") crypto_operating = input("->") if crypto_operating == '1': Playfair.playfair_info() elif crypto_operating == '2': print("-----------------Playfair密码加密---------------") print("[Input]请输入您的明文:(加密结束后会丢失大小写与空格)") plain_text = input() print("[Input]请输入您的密钥:") key = input() print("[Info]加密正在进行。。。") try: enc_text = Playfair.playfair_encrypt(plain_text, key) print("[Success]加密成功!") print("[Info]密文为:" + enc_text) except BaseException as e: print("[ERROR]加密失败!") if EXE_MODE == 'DEBUG': print(e) pass elif crypto_operating == '3': print("-----------------Playfair密码解密---------------") print("[Input]请输入您的密文:") enc_text = input() print("[Input]请输入您的密钥:") key = input() print("[Info]解密正在进行。。。") try: info = Playfair.playfair_decrypt(enc_text, key) if info == 40001: print("[ERROR]解密失败!") print("[ERR_info]请检查密文长度!密文必须为偶长度!") else: print("[Success]解密成功!(大小写与空格需要自行根据语义恢复)") print("[Info]明文为:" + info) except BaseException as e: print("[ERROR]解密失败!") if EXE_MODE == 'DEBUG': print(e) pass elif crypto_operating == '4': return else: print("[ERROR]选择出错!")
def main(): print() cipher = None # Determine which type of cipher if cipher_name == 'PLF': cipher = Playfair() elif cipher_name == 'RTS': cipher = RowTransposition() elif cipher_name == 'RFC' or cipher_name == 'CES': try: shift_amt = int(key) except ValueError: print("ERR: Please enter a number as the key for a Caesar/Railfence cipher!\n") return cipher = Railfence() if cipher_name == 'RFC' else Caesar() elif cipher_name == 'VIG': cipher = Vigenere() else: print("ERR: Not a valid cipher type! Please use:") print("\tPLF, RTS, RFC, VIG, or CES\n") return # Set the key if not cipher.setKey(key): print("ERR: Invalid key, try again.\n") return inFile = None outFile = None # Attempt to read in the text the user wants to encrypt/decrypt try: inFile = open(input_file, "r") except FileNotFoundError: print("ERR: '", input_file, "' cannot be opened! Try a valid file\n") return outFile = open(output_file, 'w') # Perfrom the encryption/decryption if method == "ENC": plaintext = inFile.read() ciphertext = cipher.encrypt(plaintext) outFile.write(ciphertext) print("Encryption was successfull!") elif method == "DEC": ciphertext = inFile.read() plaintext = cipher.decrypt(ciphertext) outFile.write(plaintext) print("Decryption was successfull!") else: print("ERR: Incorrect method. Please enter 'ENC' or 'DEC'\n") return print("Thank you for using this program.\n")
def main(): parser = argparse.ArgumentParser( description='Encrypt or decrpyt a message using Playfair Cipher') parser.add_argument('-k', default="None", help="The keyword to be used in the cipher") args = parser.parse_args() if args.k == 'None': keyword = input("What is your keyword?: ") else: keyword = args.k cipher = Playfair.Playfair(keyword) 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': splitMessage = cipher.splitMessage(message) newMessage = cipher.encrypt(splitMessage) if option == 'decrypt' or option == 'Decrypt' or option[0] == 'd': newMessage = cipher.decrypt(message) print("Here is your " + option + "ed message:") print(newMessage)
def test_check_padding(self): """Tests check_padding function for Playfair cipher """ self.assertEqual(Playfair.check_padding('i', 'double'), 'I') self.assertEqual(Playfair.check_padding('j', 'double'), 'I') with self.assertRaises(Playfair.PlayfairError): Playfair.check_padding(5, 'end') with self.assertRaises(Playfair.PlayfairError): Playfair.check_padding('ab', 'end') with self.assertRaises(Playfair.PlayfairError): Playfair.check_padding('5', 'end')
def testWikipediaExample(self): wikiCipher = Playfair.Playfair("playfair example") message = "Hide the gold in the tree stump" expectedSplit = "hi de th eg ol di nt he tr ex es tu mp" actualSplit = wikiCipher.splitMessage(message) self.assertEqual(actualSplit, expectedSplit) expectedEncryption = "BM OD ZB XD NA BE KU DM UI XM MO UV IF" actualEncryption = wikiCipher.encrypt(actualSplit) self.assertEqual(actualEncryption, expectedEncryption)
def test_decrypt(self): """Tests decrypt function for Playfair cipher """ password = '******' self.assertEqual(Playfair.decrypt(Playfair.encrypt(ALPHABET, password), password), ALPHABET[:9] + 'XI' + ALPHABET[10:] + 'X') with self.assertRaises(Playfair.PlayfairError): Playfair.decrypt(521, password) with self.assertRaises(Playfair.PlayfairError): Playfair.decrypt(ALPHABET, range(5))
def handle_input(cipher, key, in_file, out_file, mode): # Standardize the cipher the_cipher = cipher.lower() # Try to open files specified try: input_file = open(in_file, "r") output_file = open(out_file, "w") text = input_file.read() input_file.close() except IOError: # If there was an error opening the file, abort print("Error opening file") return # Execute Caesar cipher if the_cipher == "caesar": CIPHER = Caesar.Caesar() if CIPHER.set_key(key): if mode == "e": print("Using Caesar cipher to encrypt: {}".format(in_file)) encrypt = CIPHER.encrypt(text) output_file.write(encrypt) elif mode == "d": print("Using Caesar cipher to decrypt: {}".format(out_file)) decrypt = CIPHER.decrpyt(text) output_file.write(decrypt) output_file.close() else: print("Key: \"{}\" is not a valid key.\n " "No encryption will occur.".format(key)) # Execute Playfair cipher elif the_cipher == "playfair": CIPHER = Playfair.Playfair() if CIPHER.set_key(key): CIPHER.construct_key_matrix(key) if mode == "e": print("Using Playfair cipher to encrypt: {}".format(in_file)) encrypt = CIPHER.encrypt(text) output_file.write(encrypt) elif mode == "d": print("Using Playfair cipher to decrypt: {}".format(out_file)) decrypt = CIPHER.decrpyt(text) output_file.write(decrypt) output_file.close() else: print("Key: \"{}\" is not a valid key.\n " "No encryption will occur.".format(key)) # Execute Railfence cipher elif the_cipher == "railfence": CIPHER = Railfence.Railfence() if CIPHER.set_key(key): if mode == "e": print("Using Railfence cipher to encrypt: {}".format(in_file)) encrypt = CIPHER.encrypt(text) output_file.write(encrypt) elif mode == "d": print("Using Railfence cipher to decrypt: {}".format(out_file)) decrypt = CIPHER.decrpyt(text) output_file.write(decrypt) output_file.close() else: print("Key: \"{}\" is not a valid key.\n " "No encryption will occur.".format(key)) # Execute Row Transposition cipher elif the_cipher == "rowtransposition": CIPHER = RowTransposition.RowTransposition() if CIPHER.set_key(key): if mode == "e": print("Using Row Transposition cipher to encrypt: {}".format( in_file)) encrypt = CIPHER.encrypt(text) output_file.write(encrypt) elif mode == "d": print("Using Row Transposition cipher to decrypt: {}".format( out_file)) decrypt = CIPHER.decrpyt(text) output_file.write(decrypt) output_file.close() else: print("Key: \"{}\" is not a valid key.\n " "No encryption will occur.".format(key)) # Execute Vigenre cipher elif the_cipher == "vigenre": CIPHER = Vigenre.Vigenre() if CIPHER.set_key(key): CIPHER.build_rows() if mode == "e": print("Using Vigenre cipher to encrypt: {}".format(in_file)) encrypt = CIPHER.encrypt(text) output_file.write(encrypt) elif mode == "d": print("Using Vigenre cipher to decrypt: {}".format(out_file)) decrypt = CIPHER.decrpyt(text) output_file.write(decrypt) output_file.close() else: print("Key: \"{}\" is not a valid key.\n " "No encryption will occur.".format(key)) # User didn't enter a correct cipher else: print("Unknown cipher entered...")
def setUp(self): self.cipher = Playfair.Playfair(self.keyword)
# Make sure we have enough arguments, if not print the help message if len(sys.argv) < 5: parser.print_help() sys.exit(1) # Actually parse the arguments arguments = parser.parse_args() cipher = CipherInterface() 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"]:
#Main program import sys import Caesar import RailFence import Row_Transposition import Playfair import Vigenere #Checking user input if len(sys.argv) < 6: print("You are missing arguments, check your input.") else: #Playfair Cipher if str(sys.argv[1]) == 'PLF': cipher_type = Playfair.Playfair() #Row_Transposition Cipher elif str(sys.argv[1]) == 'RTS': cipher_type = Row_Transposition.Row_Transposition() #RailFence Cipher elif str(sys.argv[1]) == 'RFC': cipher_type = RailFence.Railfence() #Vigenere Cipher elif str(sys.argv[1]) == 'VIG': cipher_type = Vigenere.Vigenere() #Caesar Cipher elif str(sys.argv[1]) == 'CES': cipher_type = Caesar.Caesar() #Invalid Input else: print("Unrecognized cipher type, check your spelling and try again.")