예제 #1
0
def options(argument):
    if (argument == 1):
        print(bcolors.BOLD + bcolors.OKBLUE +
              "Ready to Encrypt/Decrypt Ceaser Cipher?" + bcolors.ENDC)
        Ceaser.main()
    elif (argument == 2):
        print(bcolors.BOLD + bcolors.OKBLUE +
              "Ready to Encrypt/Decrypt Columnar Cipher?" + bcolors.ENDC)
        Columnar.main()
    elif (argument == 3):
        print(bcolors.BOLD + bcolors.OKBLUE +
              "Ready to Encrypt/Decrypt Vigenere Cipher?" + bcolors.ENDC)
        Vigenere.main()
    elif (argument == 4):
        print(bcolors.BOLD + bcolors.OKBLUE +
              "Excited to Crack Ceaser Cipher?" + bcolors.ENDC)
        CeaserCracker.main()
    elif (argument == 5):
        print(bcolors.BOLD + bcolors.OKBLUE +
              "Excited to Crack Columnar Cipher?" + bcolors.ENDC)
        ColumnarCracker.main()
    elif (argument == 6):
        print(bcolors.BOLD + bcolors.OKBLUE +
              "Excited to Crack Vigenere Cipher?" + bcolors.ENDC)
        VigenereCracker.main()
    else:
        print(bcolors.FAIL +
              "Quitting!! The Option must be between 1 and 6\n" + bcolors.ENDC)
        exit(0)
def sendMessage():
   matriz = VT.vigenereTable()
   
   #Lectura de mensaje de entrada
   archivo = open("mensajedeentrada.txt","r")
   text = archivo.read().upper()

   #Cifrado de password para Vigenere
   pw = "dnavarreter".upper()
   pw = RN.rotN(pw,-5)

   #Proceso de cifrado de mensaje
   text = RN.rotN(text,-8)
   text = V.encode(matriz,pw,text)
   text = RN.rotN(text,20)

   #Obtencion de hash
   Hash = hashlib.sha1()
   Hash.update(text.encode('utf-8'))
   vHash = Hash.hexdigest()

   #Creacion de mensaje seguro
   archive = open("mensajeseguro.txt","w")
   archive.write(text)
   archive.close()

   archiveHash = open("hash.txt","w")
   archiveHash.write(vHash)
   archiveHash.close()

   return "Mensaje Enviado"
예제 #3
0
def receiveMessage():
    matriz = VT.vigenereTable()

    #Cifrado de password para Vigenere
    pw = "dnavarreter".upper()
    pw = RN.rotN(pw, -5)

    #Obtención de hash original
    archiveHash = open("hash.txt", "r")
    oHash = archiveHash.read()

    #Lectura de mensaje recivido
    archivo = open("mensajeseguro.txt", "r")
    text = archivo.read()

    #Validacion de hash
    Hash = hashlib.sha1()
    Hash.update(text.encode('utf-8'))
    vHash = Hash.hexdigest()

    if (oHash == vHash):
        text = RN.rotN(text, -20)
        text = V.decode(matriz, pw, text)
        text = RN.rotN(text, 8)
        return text

    else:
        return "MENSAJE ADULTERADO"
예제 #4
0
    def on_encrypt(self):
        text_widget = self.builder.get_object('plaintext', self.master)
        self.plaintext = text_widget.get("1.0", tk.END)
        print(self.plaintext + "\t" + self.key)
        self.cipher = ""

        if (self.vigenere == 1):
            self.cipher = v.encryptMess(key=self.key, message=self.plaintext)
            # self.cipher = str(Vigenere.encryptMess(key=self.key, message=self.plaintext))
            print(self.cipher)
            print(len(self.cipher))

        if (self.vernem == 1):
            vernO = Vernam.VernamCipher(self.plaintext, self.key)
            self.cipher = vernO.giveVernam(self.plaintext, self.key)

        elif (self.transposition == 1):
            for char in self.key:
                self.k += ord(char)
            self.cipher = transp.encMessage(self.k, self.plaintext)
            print("run")

        elif (self.own == 1):
            print("run")
            self.cipher = o.encrypt(self.plaintext, self.key)

        print(self.cipher)
        printwidget = self.builder.get_object('ciphertext', self.master)
        printwidget.delete("1.0", tk.END)
        printwidget.insert(tk.END, self.cipher)
예제 #5
0
    def on_decrypt(self):
        print("clicked")
        if (self.vigenere == 1):
            self.plaintext = v.decryptMess(key=self.key, message=self.cipher)
            # self.cipher = str(Vigenere.encryptMess(key=self.key, message=self.plaintext))
            print(self.cipher)
            print(len(self.cipher))
            print(self.plaintext)

        if (self.vernem == 1):
            vernO = Vernam.VernamCipher(self.cipher, self.key)
            self.plaintext = vernO.decryptVern(self.plaintext, self.key)
            print(self.plaintext)

        elif (self.transposition == 1):

            k = 0
            for char in self.key:
                self.k += ord(char)
            self.plaintext = transp.decMessage(self.k, self.cipher)
            print("run")
            print(self.plaintext)

        elif (self.own == 1):
            print("run")
            self.plaintext = o.decrypt(self.cipher, self.key)
            print(self.plaintext)

        instxt = self.builder.get_object('plaintext', self.master)
        instxt.delete("1.0", tk.END)
        instxt.insert(tk.END, self.plaintext)
예제 #6
0
def vigenere_menu():
    while True:
        print("-----Vigenere密码-----")
        print("请选择你要进行的操作:")
        print("1.Vigenere密码简介")
        print("2.Vigenere密码加密")
        print("3.Vigenere密码解密")
        print("4.返回上一级")
        crypto_operating = input("->")
        if crypto_operating == '1':
            Vigenere.vigenere_info()
        elif crypto_operating == '2':
            print("-----------------Vigenere密码加密---------------")
            print("[Input]请输入您的明文:")
            plain_text = input()
            print("[Input]请输入您的密钥:(密钥应为合法英文单词)")
            key = input()
            print("[Info]加密正在进行。。。")
            try:
                enc_text = Vigenere.vigenere_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("-----------------Vigenere密码解密---------------")
            print("[Input]请输入您的密文:")
            enc_text = input()
            print("[Input]请输入您的密钥:(密钥应为合法英文单词)")
            key = input()
            print("[Info]解密正在进行。。。")
            try:
                plain_text = Vigenere.vigenere_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':
            return
        else:
            print("[ERROR]选择出错!")
예제 #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")
예제 #8
0
def _():
    message = "This text is a sample to be encode and decode with various encryption methods."
    cesar = Cesar(3)  # Offset = 3
    vigenere = Vigenere("password")  # Key = password
    rot13 = ROT13()
    vernam = Vernam(len(message))  # RandomKey length = length of message
    rsa = RSA(33967, 917227)  # p et q prime number

    @it('should test the constructor of Cesar encryption module')
    def testConstructorOfCesarModule():
        assert cesar.offset == 3

    @it('should test the constructor of Vigenere encryption module')
    def testConstructorOfVigenereModule():
        assert vigenere.key == "password"

    @it('should test the constructor of ROT13 encryption module')
    def testConstructorOfROT13Module():
        assert rot13.rotation == 13

    @it('should test the constructor of Vernam encryption module')
    def testConstructorOfVernamModule():
        assert len(vernam.key) == len(message)

    @it('should test the constructor of RSA encryption module')
    def testConstructorOfRSAModule():
        assert rsa.p == 33967
        assert rsa.q == 917227

    @it('should test the Cesar encryption method')
    def testCesarEncryptionMethod():
        encoded = cesar.encrypt(message)
        decoded = cesar.decrypt(encoded)
        assert decoded == message

    @it('should test the Vigenere encryption method')
    def testVigenereEncryptionMethod():
        encoded = vigenere.encrypt(message)
        decoded = vigenere.decrypt(encoded)
        assert decoded == message

    @it('should test the ROT13 encryption method')
    def testROT13EncryptionMethod():
        encoded = rot13.encrypt(message)
        decoded = rot13.decrypt(encoded)
        assert decoded == message

    @it('should test the Vernam encryption method')
    def testVernamEncryptionMethod():
        encoded = vernam.encrypt(message)
        decoded = vernam.decrypt(encoded)
        assert decoded == message

    @it('should test the RSA encryption method')
    def testRSAEncryptionMethod():
        encoded = rsa.encrypt(message)
        decoded = rsa.decrypt(encoded)
        assert decoded == message
예제 #9
0
        def Decode():
            txt = ent1.get()
            k = ent2.get()

            st = Vigenere.Dec(txt, k)

            global lbl
            lbl = Label(et, text="Original Message : "+st, font=("Helvetica", 25))
            lbl.place(x=700, y=500, anchor="center")
예제 #10
0
def validate_guess(keylens, fileids, alphabet, num_candidates):
    keys = list(keylens.keys())
    #for each fileid, we will want to check whether the correct guess is made
    #for all keys
    found = 0
    not_found = 0
    indecipherable = 0

    for fileid in fileids:
        #print("PLAINTEXT: ", fileid)
        #setting plaintext
        plaintext = corpus.gutenberg.raw(fileid)
        plaintext = plaintext[0:300]

        for key in keys:
            ciphertext, ciphertext_file = vg.encrypt(key, plaintext)

            #getting most likely key lengths
            cipher_match_indices, cipher_matches = vg.find_matches(ciphertext)
            most_likely_lengths, sorted_factor_counts = vg.likely_key_lengths(
                ciphertext)

            if type(sorted_factor_counts) == int:
                indecipherable += 1
                continue

            most_likely_lengths = sorted_factor_counts[:num_candidates]
            #print("Included: ", keylens.get(key) in most_likely_lengths, "|Key length: ", keylens.get(key), "|Choices: ", most_likely_lengths)
            if keylens.get(key) != 1:
                if keylens.get(key) in most_likely_lengths:
                    #print("Included: ", True, "|Key length: ", keylens.get(key), "|Choices: ", most_likely_lengths)
                    found += 1
                else:
                    print("Included: ", False, "|Key length: ", keylens.get(key), "|Choices: ",\
                           most_likely_lengths, "|Next: ", sorted_factor_counts[:num_candidates+1])
                    not_found += 1

    percent_top5 = (found) / (found + not_found)
    percent_indecipherable = (indecipherable) / (found + not_found +
                                                 indecipherable)
    return percent_top5, percent_indecipherable
예제 #11
0
 def test_encrypt(self):
     """Tests encrypt function for Vigenere cipher"""
     self.assertEqual(
             Vigenere.encrypt('A' * 26, ALPHABET), ALPHABET)
     self.assertEqual(
             Vigenere.encrypt('A' * 26, ALPHABET[:13]), ALPHABET[:13] * 2)
     self.assertEqual(
             Vigenere.encrypt(ALPHABET, ALPHABET), ALPHABET[::2] * 2)
     with self.assertRaises(Vigenere.VigenereError):
         Vigenere.encrypt(5, ALPHABET)
     with self.assertRaises(Vigenere.VigenereError):
         Vigenere.encrypt(ALPHABET, range(5))
예제 #12
0
 def test_decrypt(self):
     """Tests decrypt function for Caesar cipher"""
     self.assertEqual(
             Vigenere.decrypt(ALPHABET, ALPHABET), 'A' * 26)
     self.assertEqual(
             Vigenere.decrypt(ALPHABET[:13] * 2, ALPHABET[:13]), 'A' * 26)
     self.assertEqual(
             Vigenere.decrypt(ALPHABET[::2] * 2, ALPHABET), ALPHABET)
     with self.assertRaises(Vigenere.VigenereError):
         Vigenere.decrypt(5, ALPHABET)
     with self.assertRaises(Vigenere.VigenereError):
         Vigenere.decrypt(ALPHABET, range(5))
예제 #13
0
def main():
    print("Sheno cilin fajll do te ekzekutosh: ")
    sys.argv = input("vendos emrin e fajllit:").upper()
    if sys.argv == "VIGENERE":
        Vigenere.main()
        Provo()
    elif sys.argv == "FOUR_SQUARE_CIPHER":
        Four_square_cipher.main()
        Provo()
    elif sys.argv.upper() == "CREATE_USER":
        Create_user.main()
        Provo()

    elif sys.argv.upper() == "EXPORT_KEY":
        Export_Key.main()
        Provo()

    elif sys.argv == "CASE":
        Case.main()
        Provo()

    else:
        print("Vendos vlera valide ")
        main()
예제 #14
0
def decrypt(text, key):
    """Decrypts text using the One-Time Pad cipher

    D(x) = Vigenere.decrypt(text, key)

    text : string
    key : string
    """
    if type(text) is not str:
        raise OneTimePadError('Can only encrypt strings.')
    if type(key) is not str:
        raise OneTimePadError('key must be a string.')
    if len(key) < len(text):
        raise OneTimePadError('key must be at least the same length as text.')

    return Vigenere.decrypt(utils.fix_text(text), utils.fix_text(key))
예제 #15
0
def VigenereCrack(message):
    with open('Wordlist.txt','r') as fo:
        words = fo.readlines()
  
    for word in words:
        word = word.strip() # Remove the newline at the end.
        cracked = Vigenere.decryption(word, message)
        #Will ask the user to decide with their human congitive ability to decide the result
        if detectEnglish.isEnglish(cracked, wordPercentage=40):
            print('\nPossible encryption hack:')
            print('Key ' + str(word) + ': ' + bcolors.OKBLUE+bcolors.UNDERLINE+cracked[:100]+"\n"+bcolors.ENDC)
            response = input('Press'+bcolors.FAIL+' G '+bcolors.ENDC+'if desired message is found! Else, continue: ')

            if response.strip().upper().startswith('G'):
                return cracked
    return None
예제 #16
0
파일: Encryption.py 프로젝트: ilae4e/Tools
    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
예제 #17
0
파일: Encryption.py 프로젝트: ilae4e/Tools
    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
예제 #18
0
def tryVigenere(nomeEntrada, nomeSaida):
    inputFile = Util.scanFile(nomeEntrada)
    outputFile = Util.scanFile(nomeSaida)
    lenInputFile = len(inputFile)
    key = ""
    idx = 0

    while idx < lenInputFile:
        key += chr((ord(outputFile[idx]) - ord(inputFile[idx])) % 256)
        retornoVigenere = Vigenere.cript(inputFile, key)
        # if(filecmp.cmp(nomeSaida, "./saidaCriptVigenere.txt")):
        if retornoVigenere == outputFile:
            print("Algoritmo: Cifra de Vigenere\nChave: " + key)
            return True
        idx += 1

    return False
예제 #19
0
def tryVigenere2(nomeEntrada, nomeSaida):
    inputFile = Util.scanFile(nomeEntrada)
    outputFile = Util.scanFile(nomeSaida)
    lenInputFile = len(inputFile)
    key = ""
    idx = 0

    while idx < lenInputFile:
        key += chr((ord(outputFile[idx]) - ord(inputFile[idx])) % 256)
        vigenereReturn = Vigenere.criptStatusReturn(inputFile, outputFile, key)
        if vigenereReturn == 1:
            print("Algoritmo: Cifra de Vigenere2\nChave: " + key)
            return True
        elif vigenereReturn == -1:
            return False
        idx += 1

    return False
예제 #20
0
    def on_import_image(self):
        self.file_path = filedialog.askopenfilename(
            title="select an image to open")

        self.plaintext = conv.convertFileToString(self.file_path)

        text_widget = self.builder.get_object('plaintext', self.master)
        text_widget.delete("1.0", tk.END)
        text_widget.insert(tk.END, self.plaintext)

        if (self.vigenere == 1):
            self.cipher = v.encryptMess(key=self.key, message=self.plaintext)
            # self.cipher = str(Vigenere.encryptMess(key=self.key, message=self.plaintext))
            print(self.cipher)
            print(len(self.cipher))

        if (self.vernem == 1):
            vernO = Vernam.VernamCipher(self.plaintext, self.key)
            self.cipher = vernO.giveVernam(self.plaintext, self.key)

        elif (self.transposition == 1):

            k = 0
            for char in self.key:
                self.k += ord(char)
            self.cipher = transp.encMessage(self.k, self.plaintext)
            print("run")

        elif (self.own == 1):
            print("run")
            self.cipher = o.encrypt(self.plaintext, self.key)
            with open('enc.enc', 'w') as file:
                file.write(str(self.cipher))
            self.plaintext = self.on_decrypt()

        printwidget = self.builder.get_object('ciphertext', self.master)
        printwidget.delete("1.0", tk.END)
        printwidget.insert(tk.END, self.cipher)

        conv.convertStringToFile(self.plaintext, "jpg", self.file_path)
예제 #21
0
 def updateConfig():
     global username
     global password
     global time
     global url
     global loginAtStartup
     LogManager.log("Updating config file...")
     file = open('config.ini', 'w')
     config = configparser.ConfigParser()
     config.add_section('SerraAutoLogin')
     config.set('SerraAutoLogin', 'Username', username)
     config.set('SerraAutoLogin', 'cryptedpassword',
                Vigenere.encryptMessage("NoobTest", password))
     config.set('SerraAutoLogin', 'Url', url)
     config.set('SerraAutoLogin', 'loginAtStartup', loginAtStartup)
     config.set('SerraAutoLogin', 'Time', str(time))
     config.set('SerraAutoLogin', 'FirstRun', '0')
     config.write(file)
     file.close()
     LogManager.log("Config file updated")
     stopTimer()
     startTimer()
예제 #22
0
    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"
    key = "SPARTAN"
    plain_file = open(plain_path, "r")
    cipher_text = Vr.vernam_cipher(plain_file.readlines(), key)
    print(cipher_text)
########################## write the ouput cipher Text ########################################333

if (cipher_path != './'):  #one of algorithms has been selected
    cipher_file = open(cipher_path, "w")
    #for ciph_msg in cipher_text :
    cipher_file.writelines(cipher_text)
    cipher_file.close()
    plain_file.close()
예제 #23
0
        QMessageBox.critical(
            None, "Systray",
            "I couldn't detect any system tray on this system.")
        sys.exit(1)
    QApplication.setQuitOnLastWindowClosed(False)

    icon = 'icon/SerraAutoLogin.ico'
    hover_text = "SerraAutoLogin"

    LogManager.createLog()

    LogManager.log("Reading Config file...")
    config = configparser.ConfigParser()
    config.read('config.ini')
    username = config.get('SerraAutoLogin', 'Username')
    password = Vigenere.decryptMessage(
        "NoobTest", config.get('SerraAutoLogin', 'cryptedpassword'))
    url = config.get('SerraAutoLogin', 'Url')
    loginAtStartup = config.get('SerraAutoLogin', 'loginAtStartup')
    time = int(config.get('SerraAutoLogin', 'Time'))
    firstRun = config.get('SerraAutoLogin', 'FirstRun') == '1'
    LogManager.log("Config file loaded successfully")

    leftTime = time

    def timerFunc():
        global leftTime
        global time
        if leftTime <= 0:
            login(True)
            leftTime = time
        startTimer()
예제 #24
0
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,
    comb.decrypt
]

#need encode and decode list and convert to and convert from lists
예제 #25
0
#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.")
        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)
# -*- coding: utf-8 -*-
"""
Created on Tue Mar  3 15:46:45 2020

@author: omeil
"""
import Vigenere as VV
from Vigenere import Vigenere as Vin
import numpy as np

pr = True

fake = Vin("FAKE")
cipher = "OCNYBIFHBRUPBNYAZGBBNBYESSYXYYNSQVMFDCHDNCSWHTEGNPMNLRSWXRYPPAFNGBUCFNGBISLRTRPILFXYXOMUXBTIHFXRHONRLQIOFYLRBBXNFGHVNLPMNOHJBRIONBKAIKBBLCGZUZXGTHBRBKQFCFHLFRFVZFUBCAZYORBRKLBAYZHRISLBYCYWFRLDSCGUXPCSUPHLIOHQZJPKMJHPMRQVWCXSFPHKFVYEFGMRYLXQDCGZTLEHBRTGSPLVWEFRBNKZPFNUTRUKCAVGUWYFYPBAYXXCQOHPBCOHFNGBTMIHKQUCLVXBQCGCVPJSMFACXWNULGMSHGEGQGAVOCNSSBNPUWLRWWPILCHMSMIHKFVRXYXBNOMFXQZSUEGGOUNBUPFONUXDSSYGACXFYGVFFRLRYSTSISRMVFNRXKJBAFAMSSMRGBUVYFXRISBBFCMSMFMCNDYFMRPGNGHKFWFVYRNMFNFNCSMVWCUVYTHJESHQHMS"
ln = VV.findL(cipher)

#keyholder = np.zeros(l)

for i in range(26):
    for j in range(26):
        for k in range(26):
            for l in range(26):
                for m in range(26):
                    for n in range(26):
                        keyholder = np.array((i, j, k, l, m, n))
                        key = ""
                        for i in range(len(keyholder)):
                            ch = chr((keyholder[i] % 26) + 65)
                            key += ch
                        vin = Vin(key)
                        decode = vin.decode(cipher)
예제 #27
0
import Util
import Cesar
import Vigenere
import Transposicao
import Substituicao
import QuebrarCifras
import AtaqueDicionario

fileName = "./entrada.txt"

option = Util.menuAlgoritmo()

while option != 0:
    if option == 1:
        Cesar.start(fileName)
    elif option == 2:
        Transposicao.start(fileName)
    elif option == 3:
        Vigenere.start(fileName)
    elif option == 4:
        Substituicao.start(fileName)
    elif option == 5:
        nomeArquivo = Util.scan("Arquivo: ")
        QuebrarCifras.quebrarCifra(nomeArquivo)
    elif option == 6:
        nomeArquivo = Util.scan("Arquivo: ")
        AtaqueDicionario.startAttack(nomeArquivo)

    option = Util.menuAlgoritmo()
예제 #28
0
import Vigenere

if __name__ == '__main__':
    Vigenere.initializeDictionaries()

    # Test
    key = 'EncryptionKey'
    print('Key:', key)
    message = 'Some random text with UPPER and lower alphabets...!'
    print('Plain Text:', message)
    cipher = Vigenere.encryption(key, message)
    print('Ciphertext:', cipher)

    plain = Vigenere.decryption(key, cipher)
    print('Plain Text:', plain)
예제 #29
0
密文: 442315 4145241325 1242345233 213453 2445323543 442315 31115554 143422
#普莱菲尔密码
加密解密实例(ps:这里加解密也是横向编制密码表):
#!python
>>>from pycipher import Playfair
>>>Playfair('CULTREABDFGHIKMNOPQSVWXYZ').encipher('THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG')
#输出'UKDNLHTGFLWUSEPWHLISNPCGCRGAUBVZAQIV'
>>>Playfair('CULTREABDFGHIKMNOPQSVWXYZ').decipher('UKDNLHTGFLWUSEPWHLISNPCGCRGAUBVZAQIV')
#输出'THEQUICKBROWNFOXIUMPSOVERTHELAZYDOGX'
#维吉尼亚密码
明文: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
密钥(循环使用,密钥越长相对破解难度越大): CULTURE
(2)已知密钥加解密
#!python
>>>from pycipher import Vigenere
>>>Vigenere('CULTURE').encipher('THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG')
'VBPJOZGMVCHQEJQRUNGGWQPPKNYINUKRXFK'
>>>Vigenere('CULTURE').decipher('VBPJOZGMVCHQEJQRUNGGWQPPKNYINUKRXFK')
'THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG'
#格罗斯费尔德密码(Gronsfeld cipher)
#!python
>>>from pycipher import Gronsfeld
>>>Gronsfeld([2,20,11,45,20,43,4]).encipher('THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG')
'VBPJOZGMVCHQEJQRUNGGWQPPKNYINUKRXFK'
>>>Gronsfeld([2,20,11,45,20,43,4]).decipher('VBPJOZGMVCHQEJQRUNGGWQPPKNYINUKRXFK')
'THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG'
#自动密钥密码
#Porta密码--Porta密码(Porta Cipher)是一个由意大利那不勒斯的医生Giovanni Battista della Porta发明的多表代换密码,Porta密码具有加密解密过程的是相同的特点
密表
#!shell
KEYS| A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
예제 #30
0
파일: cipher.py 프로젝트: lekevin42/ciphers
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!")
예제 #31
0
            print("entrez la clef")
            clef = input()
            print("entrez le message chiffer")
            mess = input()
            print("\n")
            print("voici le carre ainsi que le message dechiffer: \n")
            Transposition.dechiffre(clef, mess)
    if sys.argv[1] == "-Vigenere":
        if sys.argv[2] == "-c":
            print("entrez la clef : ")
            a = input()
            print("entrez le message : ")
            b = input()
            print("\n")
            print("voici le message chiffrer:")
            print(Vigenere.VIGCode(b, a, decode=False))
            print("\n")
        if sys.argv[2] == "-d":
            print("entrez la clef")
            clef = input()
            print("entrez le message chiffer")
            mess = input()
            print("\n")
            print("voici le message dechiffer:")
            print(Vigenere.VIGCode(mess, clef, decode=True))

    if sys.argv[1] == "-DES":
        if sys.argv[2] == "-c":
            print("entrez la clef (64bits): ")
            a = input()
            print("entrez le message : ")
예제 #32
0
import Vigenere
import Util

inputFile = Util.scanFile("./outputs/pg174.txt.enc")
print Vigenere.decript3(inputFile, 'abcd')