Beispiel #1
0
def main():

    for i in range(20):
        # set random message to test
        random.seed(42)

        message = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' * random.randint(4, 40)
        # convert message to a list and shuffle it

        message = list(message)
        random.shuffle(message)
        message = ''.join(message)

        print('Test #%s: "%s..."' % (i + 1, message[:50]))

        # Check all possible keys for each message
        for key in range(1, len(message)):
            encrypted = Caesar.caesar_cipher(message, key)
            decrypted = Caesar.caesar_cipher(encrypted, key, 'decrypt')

            # encrypted and decrypted should match
            if message != decrypted:
                print('Mismatch with key %s and message %s. \n' %
                      (key, message))
                print(decrypted)
                sys.exit()
    print('Transposition cipher is passed')
Beispiel #2
0
 def test_sanity(self):
     c = Caesar(3)
     e = CaesarExploits()
     self.assertTrue(c.encrypt("hello")=="khoor") 
     self.assertTrue(c.decrypt("khoor")=="hello")
     self.assertTrue(e.known_plaintext("hello", "khoor") == 3)
     self.assertTrue(e.chosen_plaintext(c)==3)
     self.assertTrue(e.chosen_ciphertext(c)==3)
Beispiel #3
0
def main():
    sentence = raw_input('Enter a sentence: ')
    sentence = sentence.upper()
    wordList = sentence.split()
    print sentence
    print wordList
    for word in wordList:
        print Caesar.encryptWord(word),
Beispiel #4
0
def task1():
    encrypted_data = read('./text_files/t3_caesar_c_all.txt')
    for key in range(256):
        decrypted = Caesar.decrypt_data(encrypted_data[:25], key)
        txt = ''.join(chr(ch) for ch in decrypted)
        if isEnglish(txt):
            break
    decrypted_data = Caesar.decrypt_data(encrypted_data, key)
    write('./text_files/task1_decrypted.txt', decrypted_data)
Beispiel #5
0
def task2():
    encrypted_img_data = read('./imgs/c4_caesar_c_all.bmp')
    for key in range(256):
        decrypted = Caesar.decrypt_data(encrypted_img_data[:2], key)
        if decrypted == [66, 77]:
            print(f'Key is {key}')
            break
    decrypted_bmp = Caesar.decrypt_data(encrypted_img_data, key)
    write('./imgs/task2_decrypted_bmp.BMP', decrypted_bmp)
Beispiel #6
0
    def decrypt(self, event):

        InvalidKey = ("Invalid key, re-enter key")
        NotInt = ("Not an integer")
        EncryptedText = self.Text.get()
        Key = self.Key.get()

        while True:
            try:
                Key = int(Key)
            except ValueError:
                self.useful_msg.set(NotInt)
                return False

            else:
                if Key >= 1 and Key <= 25:
                    break

                else:
                    self.useful_msg.set(InvalidKey)
                    return False

        DecryptedText = Caesar.Decrypt(EncryptedText, Key)
        self.Out.set(DecryptedText)
        self.useful_msg.set("Decryption complete")
Beispiel #7
0
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")
Beispiel #8
0
def processArgs(args):
    filename = args.file[0]
    if args.encrypt:
        file = open(filename, "r")
        resultFileName = createResultFile(filename, '_encrypted')
        resultFile = open(resultFileName, "w+")
        ln = file.readlines()
        for x in ln:
            if args.caesar:
                ret = Caesar.caesarCipherEncrypt(x)
                resultFile.write(ret)
            elif args.substitution:
                ret = SimpleSubstitution.simpleSubEncrypt(x)
                resultFile.write(ret)
            elif args.poly:
                ret = PolyAlpha.polyEncrypt(x)
                resultFile.write(ret)
            elif args.transposition:
                ret = Transposition.transEncrypt(x)
                resultFile.write(ret)
            else:
                ret = Caesar.caesarCipherEncrypt(x)
                resultFile.write(ret)
    elif args.decrypt:
        file = open(filename, "r")
        resultFileName = createResultFile(filename, '_decrypted')
        resultFile = open(resultFileName, "w+")
        ln = file.readlines()
        for x in ln:
            if args.caesar:
                ret = Caesar.caesarCipherDecrypt(x)
                resultFile.write(ret)
            elif args.substitution:
                ret = SimpleSubstitution.simpleSubDecrypt(x)
                resultFile.write(ret)
            elif args.poly:
                ret = PolyAlpha.polyDecrypt(x)
                resultFile.write(ret)
            elif args.transposition:
                ret = Transposition.transDecrypt(x)
                resultFile.write(ret)
            else:
                ret = Caesar.caesarCipherDecrypt(x)
                resultFile.write(ret)
Beispiel #9
0
 def test_decrypt(self):
     """Tests decrypt function for Caesar cipher"""
     self.assertEqual(
             Caesar.decrypt(ALPHABET[10:] + ALPHABET[:10], 10), ALPHABET)
     self.assertEqual(
             Caesar.decrypt('KPUZEJOTYDINSXCHMRWBGLQVAF', 10, 5), ALPHABET)
     with self.assertRaises(Caesar.CaesarError):
         Caesar.decrypt(5, 5)
     with self.assertRaises(Caesar.CaesarError):
         Caesar.decrypt(ALPHABET, 1, 39)
     with self.assertRaises(Caesar.CaesarError):
         Caesar.decrypt(ALPHABET, 1, 20)
Beispiel #10
0
def main(argv):
	if(len(sys.argv) != 2):
		helps()
		sys.exit(1)
	options = str(sys.argv[1])
	#encryption
	if options == "-e":
		setWindowTitle("CCrypter")
		banner()
		plaintext = raw_input(color.proc(" Enter messages : "))
		key = raw_input(color.proc(" Enter key : "))
		try:
			Caesar.encrypt(str(plaintext), key)
		except:
			print(color.error(" Failed to encrypt ! "))
	#decryption
	if options == "-d":
		setWindowTitle("CCrypter")
		banner()
		ciphertext = raw_input(color.proc(" Enter ciphertext : "))
		key = raw_input(color.proc(" Enter key : "))
		try:
			Caesar.decrypt(str(ciphertext), key)
		except:
			print(color.error(" Failed to decrypt ! "))
	
	if options == "-fe":
		setWindowTitle("CCrypter")
		banner()
		file = raw_input(color.proc(" Enter file to encrypt : "))
		key = raw_input(color.proc(" Enter key : "))
		try:
			print(color.proc(" Encrypting ..."))
			Caesar.encryptFile(file, key)
		except:
			print(color.error(" Encrypting failed !"))
			print ""
			
	if options == "-fd":
		setWindowTitle("CCrypter")
		banner()
		file = raw_input(color.proc(" Enter file to decrypt : "))
		key = raw_input(color.proc(" Enter key : "))
		try:
		    print(color.proc(" Decrypting ..."))
		    Caesar.decryptFile(file, key)
		except:
			print(color.error(" Decrypting failed !"))
			print ""
	if not options in ["-e","-d","-fe","-fd"]:
		helps()
def list_all_cs(text):
    """
    lists chi-squared statistic for all caesar shifts of the text, returns the user's choice of key to proceed with
    :param text:
    :return key:
    """
    alphabet = 'abcdefghijklmnopqrstuvwxyz'

    for i in range(0, 26):
        decrypted = Caesar.decrypt(text, i)
        print ('key %2s  %s %10.4f' % (i, decrypted, chi_squared(decrypted)))
    return alphabet[int(raw_input('key choice: '))]
Beispiel #12
0
def list_all_cs(text):
    """
    lists chi-squared statistic for all caesar shifts of the text, returns the user's choice of key to proceed with
    :param text:
    :return key:
    """
    alphabet = 'abcdefghijklmnopqrstuvwxyz'

    for i in range(0, 26):
        decrypted = Caesar.decrypt(text, i)
        print('key %2s  %s %10.4f' % (i, decrypted, chi_squared(decrypted)))
    return alphabet[int(raw_input('key choice: '))]
Beispiel #13
0
def decrypt(text, seed):
    """Decrypts text using the One-Time Pad cipher

    D(x) = Caesar.decrypt(x, random)

    text : string
    seed : hashable
    """
    random.seed(seed)

    return ''.join(Caesar.decrypt(letter, random.randint(0, 25))
                   for letter in utils.fix_text(text))
Beispiel #14
0
def decrypt(text, password):
    """Decrypts text using the Vigenere cipher

    D(text[i]) = (text[i] - password[i]) % 26

    text, password : string
    """
    password = utils.fix_text(password)

    length = len(password)
    A = ord('A')

    return ''.join([Caesar.decrypt(letter, ord(password[index % length])
                    - A) for index, letter in enumerate(utils.fix_text(text))])
Beispiel #15
0
def live_decrypt(pw):
    dec_msg = ''
    print 'Enter message to decrypt:'
    i = 0
    while True:
        msg = str(raw_input())
        if msg == 'exit()': break
        msg_out = ''
        for j in range(len(msg)):
            msg_out += Caesar.decrypt(
                ord(pw[i % len(pw)].lower()) - ord('a') + 1, msg[j])
            i += 1
        dec_msg += msg_out
        print msg_out
    return dec_msg
Beispiel #16
0
    def __decrypt(message, key):
        # Split message in half
        B = message[:len(message) / 2]
        C = message[len(message) / 2:]

        Rail_Fence_key = Jordan_Harman_Algorithm_1.get_rail_key(key)
        Caesar_key = Jordan_Harman_Algorithm_1.get_caesar_key(key)
        Vigenere_key = Jordan_Harman_Algorithm_1.get_vigenere_key(key)

        # Begin Rounds
        for x in range(0, 8):
            C = Caesar.decrypt(C, Caesar_key)
            C = Rail_Fence.decrypt(C, Rail_Fence_key)
            C = Vigenere.decrypt(C, Vigenere_key)
            B, C = C, B
        return B + C
Beispiel #17
0
    def __encrypt(message, key):
        # Split message in half
        Ln = message[:len(message) / 2]
        Rn = message[len(message) / 2:]

        # Get keys
        Rail_Fence_key = Jordan_Harman_Algorithm_1.get_rail_key(key)
        Caesar_key = Jordan_Harman_Algorithm_1.get_caesar_key(key)
        Vigenere_key = Jordan_Harman_Algorithm_1.get_vigenere_key(key)

        # Begin Rounds
        for x in range(0, 8):
            Rn = Vigenere.encrypt(Rn, Vigenere_key)
            Rn = Rail_Fence.encrypt(Rn, Rail_Fence_key)
            Rn = Caesar.encrypt(Rn, Caesar_key)
            Ln, Rn = Rn, Ln
        return Ln + Rn
Beispiel #18
0
def crackVigenere(message):
	messageNums = [] #Numerical characters, all lowercase
	messageModified = '' #String, all lowercase
	for c in message:
		n = ord(c)
		if 65<=n<=90:
			messageNums.append(n+32)
		elif 97<=n<=122:
			messageNums.append(n)
	for n in messageNums:
		messageModified+=str(chr(n))

	try:
		keyLength = Kasiski.kasiski(messageModified,3,15)[0] #Most likely key length based on Kasiski Analysis of ciphertext
	except IndexError:
		print('Kasiski Analysis failed. Message might be too short, or key might be too short or too long')
		return None

	print('Guessed key length as: '+str(keyLength))

	frequencyAnalyses = []
	splitTexts = []
	permutationSet = []
	for i in range(keyLength):
		l=[]
		n=i
		while n<len(messageNums):
			l.append(messageNums[n])
			n+=keyLength
		splitTexts.append(l)
		frequencyAnalyses.append(Caesar.frequencyAnalysis(l))
		permutationSet.extend([0,1,2,3]) #Highest number defines how deep in frequency tree program will search.

	p = permutations(permutationSet, keyLength)
	perms = sorted(set(p))
	for perm in perms:
		key = ''
		for j in range(keyLength):
			key+=str(chr((frequencyAnalyses[j])[perm[j]]+97))
		decodedString = str(EncodeDecode.decodeVigenere(messageModified, key))
		validWords = DictionaryCheck.dictCheck(decodedString)
		print('Guessed key as: ' + key+ '. There are ' + str(validWords) +' valid words as a part of the decoded message')
		if(DictionaryCheck.dictCheck(decodedString)>0.28*len(decodedString)): #0.28, approximately
			print('Number of valid words is greater than 0.28*message length. This key is likely correct!')
			return decodedString
Beispiel #19
0
def decrypt(text, password):
    """Decrypts text using the Vigenere cipher

    D(text[i]) = (text[i] - password[i]) % 26

    text, password : string
    """
    if type(text) is not str:
        raise VigenereError('Can only decrypt strings.')
    if type(password) is not str:
        raise VigenereError('Password must be a string.')

    password = utils.fix_text(password)

    length = len(password)
    A = ord('A')

    return ''.join([Caesar.decrypt(letter, ord(password[index % length])
                    - A) for index, letter in enumerate(utils.fix_text(text))])
Beispiel #20
0
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"]:
	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:
#import all ciphers and converters
#they were all made as classes to not confuse the encrypt methods with each other
#import * for classes
from A1Z26 import *
from Caesar import *
from Combined import *
from MorseCode import *
from OneTimePad import *
from Vigenere import *
from Binary import *
from Hex import *
from Octal import *

#create instances of each class
a1 = A1()
caesar = Caesar()
comb = Combined()
morse = Morse()
otp = OneTimePad()
vig = Vigenere()
binary = Binary()
hexa = Hexa()
octal = Octal()

#in order to avoid long if statements, functions/methods added to lists
encFunc = [
    vig.encrypt, otp.encrypt, caesar.encrypt, a1.encrypt, morse.encrypt,
    comb.encrypt
]
decFunc = [
    vig.decrypt, otp.decrypt, caesar.decrypt, a1.decrypt, morse.decrypt,
Beispiel #22
0
#!/usr/bin/env python

import Caesar
import Binary

userinput = raw_input()

print "user input: " + userinput

encr = Caesar.rotate(userinput, 13)
decr = Caesar.rotate(encr, 13)

print Binary.shortdecode(userinput)

print encr
print decr
Beispiel #23
0
def main():
    print("Would you like to encode or decode a message?")
    first_choice = input("Encode/Decode: ").lower()
    if first_choice == "encode":
        print("You have chosen to Encode a message.")
        print("Would you like to continue?")
        encode_confirm_choice = input("Yes/No: ").lower()
        if encode_confirm_choice == "yes":
            print("You may choose between the following ciphers:")
            print("1. Caesar Cipher (Easiest to decode)")
            print(
                "2. Stream Cipher (For Messages in Binary, almost impossible to decode without the key)"
            )
            print(
                "3. Block Cipher (Almost impossible to decode without the key."
            )
            print("Which one would you like to use?")
            encode_cipher_choice = int(input("1/2/3: "))
            if encode_cipher_choice == 1:
                print(
                    "You have selected to encode a message using the Caesar Cipher."
                )
                print("Is this correct?")
                caesar_cipher_confirm_choice = input("Yes/No: ").lower()
                if caesar_cipher_confirm_choice == "yes":
                    print("Great.")
                    Caesar.encode_caesar_cipher()
                    newmessage_ask()
                elif caesar_cipher_confirm_choice == "no":
                    no_confirm()
                else:
                    print("Invalid Input. Starting Over.")
                    main()
            elif encode_confirm_choice == 3:
                print(
                    "You have selected to encode a message with the Block Cipher."
                )
                print("Is this Correct?")
                block_cipher_confirm_choice = input("Yes/No: ").lower()
                if block_cipher_confirm_choice == "yes":
                    print("Great.")
                    Block.encode_block_cipher()
                    newmessage_ask()
                elif block_cipher_confirm_choice == "no":
                    no_confirm()
                else:
                    print("Invalid Input. Starting Over.")
                    main()
            elif encode_cipher_choice == 2:
                print(
                    "You have selected to encode a string of binary numbers using the Stream Cipher."
                )
                print("Would you like to continue?")
                stream_cipher_confirm_choice = input("Yes/No: ").lower()
                if stream_cipher_confirm_choice == "yes":
                    print("Great.")
                    Stream.encode_stream_cipher()
                    newmessage_ask()
                elif stream_cipher_confirm_choice == "no":
                    no_confirm()
                else:
                    print("Invalid Input. Starting Over.")
                    main()
        elif encode_confirm_choice == "no":
            no_confirm()
        else:
            print("Invalid Input. Starting Over.")
            main()
    elif first_choice == "decode":
        print(
            "Right now the only cipher we have support for decoding is the Caesar Cipher."
        )
        print("Would you like to continue?")
        decode_confirm_choice = input("Yes/No: ")
        if decode_confirm_choice == "yes":
            print("Great.")
            print("Enter the message you want to decode below.")
            caesar_decode_message = input("Message: ")
            DecodeCaesar.decode_caesar_cipher(caesar_decode_message)
            newmessage_ask()
        elif decode_confirm_choice == "no":
            no_confirm()
        else:
            print("Invalid Input. Starting over.")
    else:
        print("Invalid Input. Starting Over.")
        main()
Beispiel #24
0
def encrypt(pwd, msg):
    enc_msg = ''
    for letter in range(len(msg)):
        enc_msg += Caesar.encrypt(
            ord(pwd[letter % len(pwd)].lower()) - ord('a') + 1, msg[letter])
    return enc_msg
Beispiel #25
0
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...")
Beispiel #26
0
import Caesar, Winder, My

print(Caesar.encode("dima", 3))
print(Caesar.decode("glpd", 3))
print('\n--------------\n')
print(Winder.encode('attackatdawn', 'lemon'))
print(Winder.decode('lxfopvefrnhr', 'lemon'))
print('\n--------------\n')
print(My.encode('myencode', 13))
print(My.decode('qdkbxzfk', 13))
print('\n--------------\n')
def caesar_menu():
    while True:
        print("-------Caesar密码-------")
        print("请选择你要进行的操作:")
        print("1.Caesar密码简介")
        print("2.Caesar密码加密")
        print("3.Caesar密码解密")
        print("4.Caesar密码列举破解")
        print("5.返回上一级")
        crypto_operating = input("->")
        if crypto_operating == '1':
            Caesar.caesar_info()
        elif crypto_operating == '2':
            print("----------------------Caesar加密----------------------")
            print("[Input]请输入您的明文:")
            plain_text = input()
            print("[Input]请输入您的密钥:(密钥应为数字)")
            key = input()
            if type(key) != int:
                print("[ERROR]非法输入!")
                continue
            print("[Info]加密正在进行。。。")
            try:
                enc_text = Caesar.caesar_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("----------------------Caesar解密----------------------")
            print("[Input]请输入您的密文:")
            enc_text = input()
            print("[Input]请输入您的密钥:(密钥应为数字)")
            key = input()
            if type(key) != int:
                print("[ERROR]非法输入!")
                continue
            print("[Info]解密正在进行。。。")
            try:
                plain_text = Caesar.caesar_decrypt(enc_text, key)
                print("[Success]解密成功!")
                print("[Info]明文为:" + plain_text)
            except BaseException as e:
                print("[ERROR]解密失败!")
                if EXE_MODE == 'DEBUG':
                    print(e)
                pass
        elif crypto_operating == '4':
            print("----------------------Caesar列举破解----------------------")
            print("[Input]请输入您的密文:")
            enc_text = input()
            print("[Info]列举破解正在进行。。。")
            try:
                plain_text_possible = Caesar.caesar_attack(enc_text)
                print("[Success]列举破解完成!")
                for j in plain_text_possible:
                    print("[Info]可能的明文为:" + j)
            except BaseException as e:
                print("[ERROR]列举破解失败!")
                if EXE_MODE == 'DEBUG':
                    print(e)
                pass
        elif crypto_operating == '5':
            return
        else:
            print("[ERROR]选择出错!")
Beispiel #28
0
for key in range(len(LETTERS)):
    translated = ''
    for symbol in message:
        if symbol in LETTERS:
            num = LETTERS.find(symbol)
            num = num - key
            if num < 0:
                num = num + len(LETTERS)
            translated = translated + LETTERS[num]
        else:
            translated = translated + symbol
print('Hacking key #%s: %s' % (key, translated))

# Method 2 - Try decrypting 26 ways and see what looks like english text
print("\nMethod 2:")
lst_language = [
    'am', 'era', 'my', 'liquor', 'jugs'
]  # For a real routine you should provide a list of hundreds of words, frequent in your language.
lst_scores = list()  # list of tuples of (score, key)
m2 = ""  # message-2, a local clean copy of the message, only including letters and wide-spaces
for char in message:
    if char.upper() in LETTERS or char == ' ':
        m2 += char
for key in range(len(LETTERS)):
    cleartext = Caesar.decrypt(m2, key)
    score = sum([w in lst_language for w in cleartext.split(' ')])
    if score > 0:
        lst_scores.append((score, key))
best_key = sorted(lst_scores, reverse=True)[0][1]
print(f"most likely key: {best_key} -> {Caesar.decrypt(message, best_key)}")
Beispiel #29
0
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.")
        exit()
    #Setting key from inputfile
    if cipher_type.setKey(sys.argv[2]):
        inFile = open(str(sys.argv[4]), "r")
        inputText = inFile.read()
        if str(sys.argv[3]) == 'ENC':
            outputText = cipher_type.encrypt(inputText)
        elif str(sys.argv[3] == 'DEC'):
            outputText = cipher_type.decrypt(inputText)
        #Invalid user input
        else:
            print("Unrecognized coding type, did you want Encode or Decode?")
Beispiel #30
0
                  enable_events=True,
              )
          ],
          [
              sg.Text("", size=(8, 1)),
              sg.Button("encrypt", size=(10, 1), border_width=2, pad=(15, 15)),
              sg.Button("decrypt", size=(10, 1), border_width=2, pad=(15, 15)),
              sg.Button("attack", size=(10, 1), border_width=2, pad=(15, 15))
          ],
          [
              sg.Text("Ciphertext: ", size=(8, 1)),
              sg.Multiline(key="-CIPHERTEXT-")
          ]]

window = sg.Window(title="Caesar Cipher Tool", layout=layout, margins=(30, 50))
crypto = Caesar.Caesar()

while True:
    event, values = window.read()

    if event == None or event == 'Exit':
        logger.warning("EXIT...")
        break

    elif event == "encrypt":
        plain = values["-PLAINTEXT-"]
        cipher = crypto.encrypt(plain)
        window["-CIPHERTEXT-"].update(cipher)
        logger.info(f"ENCRYPT: {plain.strip()} -> {cipher.strip()}")

    elif event == "decrypt":
Beispiel #31
0
 def caesar(ciphertext, key):
     result = Caesar.Caesar_Decrypt(ciphertext, key) if key else ciphertext
     return result
Beispiel #32
0
import Caesar

print("Ingrese texto a cifrar: ")
text=input()

code=Caesar.encrypt(3, text)
print(code)
print(Caesar.encrypt(-3, code))
Beispiel #33
0
 def CaesarShow(self):
     plaintext = self.Input.get() or ''
     Casercipher = Caesar.doCaesar(plaintext)
     self.CaesarText.set(Casercipher)
Beispiel #34
0
def choose_cipher(cipher_name, key, option, input_file, output_file):
    #Playfair
    if cipher_name == "PLF":
        if option == "ENC":
            pass

        elif option == "DEC":
            pass

        else:
            print("Invalid option! Options are ENC/DEC")

    #Row Transposition
    elif cipher_name == "RTS":
        rowtransposition = RowTransposition()
        rowtransposition.setKey(key)

        if option == "ENC":
            plain_text = read_file(input_file)
            cipher_text = rowtransposition.encrypt(plain_text)
            write_file(output_file, cipher_text)

        elif option == "DEC":
            cipher_text = read_file(input_file)
            plain_text = rowtransposition.decrypt(cipher_text)
            write_file(output_file, plain_text)

        else:
            print("Invalid option! Options are ENC/DEC")

    #Railfence
    elif cipher_name == "RFC":
        railfence = Railfence()
        railfence.setKey(key)

        if option == "ENC":
            plain_text = read_file(input_file)
            cipher_text = railfence.encrypt(plain_text)
            write_file(output_file, cipher_text)

        elif option == "DEC":
            cipher_text = read_file(input_file)
            plain_text = railfence.decrypt(cipher_text)
            write_file(output_file, plain_text)

        else:
            print("Invalid option! Options are ENC/DEC")

    #Vigenere
    elif cipher_name == "VIG":
        vigenere = Vigenere()
        vigenere.setKey(key)

        if option == "ENC":
            plain_text = read_file(input_file)
            cipher_text = vigenere.encrypt(plain_text)
            write_file(output_file, cipher_text)

        elif option == "DEC":
            cipher_text = read_file(input_file)
            plain_text = vigenere.decrypt(cipher_text)
            write_file(output_file, plain_text)

        else:
            print("Invalid option! Options are ENC/DEC")

    #Caesar
    elif cipher_name == "CES":
        caesar = Caesar()
        caesar.setKey(int(key))

        if option == "ENC":
            plain_text = read_file(input_file)
            cipher_text = caesar.encrypt(plain_text)
            write_file(output_file, cipher_text)

        elif option == "DEC":
            cipher_text = read_file(input_file)
            plain_text = caesar.decrypt(cipher_text)
            write_file(output_file, plain_text)

        else:
            print("Invalid option! Options are ENC/DEC")

    else:
        print("Invalid cipher name chosen!")
Beispiel #35
0
 def __init__(self):
     self.book = Book()
     self.caesar = Caesar()
     self.rsa = RSA()