def main():
    random.seed(42)

    for i in range(15):  #run 15 tests
        message = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" * random.randint(4, 40)

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

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

        for key in range(1,
                         math.ceil(len(message) / 2)):  #test all possible keys
            ciphertext = TranspositionCipher.encryptMessage(key, message)
            plaintext = TranspositionCipherDecrypt.decryptMessage(
                key, ciphertext)

            if plaintext != message:
                print("ERROR // Test #%s using key #%s failed!" % (i + 1, key))
                print("Message reads: %s" % (message))
                print("Decryption reads: %s" % (plaintext))
                sys.exit(0)

    print("Test passed.")
Example #2
0
def getPermutations(array, i, n):
    if (i == n):
        return array
    else:
        try:
            for j in range(
                    i, n,
                    1):  #still prduces some duplicates, but im not sure why
                array[j], array[i] = array[i], array[j]
                getPermutations(array, i + 1, n)
                array[j], array[i] = array[i], array[j]
        except IndexError:
            pass
    #print(array)
    outputStr = "".join(array)
    TranspositionCipher.transpositionCipher(
        "ne Ocpn uo idamihtngdea ry wr,ie hl onIpeeddr ea,w ndkawar e,veyO anrm  qyaantuiad  nuiocrsvou ue lmffoo gttronloe e Wr—ie hl odIne, dderlna apynig,pnsdd uny elhretecme aata  pngpi s ,Afsoo eonm  enegl rtypinap,rag pngpia m t haycbr meor.doTs  ioe smiitvsr Io,mtt urd,eetpp an aig y tmhmbcardoe r Oo—l tnyi ahsdnon hngtimre o   . ",
        outputStr, 0)
    return outputStr
def main():
    #inputFilename = 'frankenstein.txt'
    # to decrypt, next line must run
    inputFilename = 'frankenstein.encrypted.txt'
    outputFilename = 'frankenstein.decrypted.txt'
    
    myKey = 10
    myMode = 'decrypt'
    
    # if input file does not exist program leaves early.
    if not os.path.exists(inputFilename):
        print "the file %s does not exist. Qutting..." % (inputFilename)
        sys.exit()
    
    # if output file exists, give user a chance to continue
    
    if os.path.exists(outputFilename):
        print "this will overwrite the file %s. (C)ontinue or (Q)uit?" % (outputFilename)
        response = raw_input('> ')
        if not response.lower().startswith('c'):
            sys.exit()
    
    # read in message from input file
    
    fileObj = open(inputFilename)
    content = fileObj.read()
    fileObj.close()
    
    print '%sing...' % (myMode.title()) # converts lowercase to first letter capitalized 
    
    startTime = time.time()
    
    if myMode == 'encrypt':
        translated = TranspositionCipher.encryptMessage(myKey, content)
    elif myMode == 'decrypt':
        translated = decryptTransposition.decryptMessage(myKey, content)
    
    totalTime = round(time.time() - startTime, 2)
    print '%sion time: %s seconds' % (myMode.title(), totalTime)
    
    # write out translated message to a file
    
    outputFileObj = open(outputFilename, 'w')
    outputFileObj.write(translated)
    outputFileObj.close()
    
    
    print 'Done %sing %s (%s characters).' % (myMode, inputFilename, len(content))
    print '%sed file is %s.' % (myMode.title(), outputFilename)
Example #4
0
def encryptMessage(message, key, alphabet):
    key1 = len(message)
    new_alphabet = AffineCipher.encryptMessage(alphabet, key1, alphabet)
    out1 = TranspositionCipher.encryptMessage(message, key)
    num = len(new_alphabet)
    count = 0
    out2 = ''
    first_symbol = True
    for symbol in out1:
        symbol_index = new_alphabet.find(symbol)
        if symbol_index > -1:
            symbol_index += new_alphabet.find(new_alphabet[count])
            if first_symbol is True:
                symbol_index += len(message)
                first_symbol = False
            out2 += new_alphabet[(symbol_index) % num]
        else:
            out2 += symbol
        count = (count + 1) % num
    return out2
Example #5
0
def decryptMessage(message, key, alphabet):
    key1 = len(message)
    new_alphabet = AffineCipher.encryptMessage(alphabet, key1, alphabet)
    out1 = ''
    count = 0
    num = len(new_alphabet)
    first_symbol = True
    for symbol in message:
        symbol_index = new_alphabet.find(symbol)
        if symbol_index > -1:
            symbol_index -= new_alphabet.find(new_alphabet[count])
            if first_symbol is True:
                symbol_index -= len(message)
                first_symbol = False
            out1 += new_alphabet[(symbol_index) % num]
        else:
            out1 += symbol
        count = (count + 1) % num
    out2 = TranspositionCipher.decryptMessage(out1, key)
    return out2
Example #6
0
    def run_algorithm(self):
        # Cleaning the warning messages
        self.warning.grid_forget()
        self.result.configure(state='normal')
        self.result.delete(0.0, END)
        self.result.configure(state='disabled')

        # Getting the cipher
        cipher = self.cipher.get()

        # Getting the alphabet
        self.setDefaultAlphabet()
        if self.alphabetButton.get() == 2 and cipher != 5:
            self.alphabet = self.alphabetEntry.get()
            if len(self.alphabet) == 0:
                # Warning message
                self.warning[
                    "text"] = "Your custom alphabet cannot be empty.\nTip: you should consider enter a large alphabet."
                self.warning.grid(row=self.affine_row + 6,
                                  column=11,
                                  sticky=W + W,
                                  padx=10,
                                  columnspan=2,
                                  rowspan=2)
                return

        # Getting the key
        if len(self.keyEntry.get()) == 0:
            # Warning message
            self.warning["text"] = "Please enter a valid key (numbers only)."
            self.warning.grid(row=self.affine_row + 6,
                              column=11,
                              sticky=W + W,
                              padx=10,
                              columnspan=2,
                              rowspan=2)
            return
        self.key = int(self.keyEntry.get())

        # Getting the message
        # Put end-1c for avoid getting '\n' at the end of the input.
        message = self.plainText.get("1.0", 'end-1c')
        if len(message) == 0:
            # Warning message
            self.warning[
                "text"] = "I think you forgot to enter your message..."
            self.warning.grid(row=self.affine_row + 6,
                              column=11,
                              sticky=W + W,
                              padx=10,
                              columnspan=2,
                              rowspan=2)
            return

        # Configuring the result
        self.result.configure(state='normal')

        # Encrypt according to the selected cipher
        if cipher == 1:  # Affine Cipher
            valid = AffineCipher.validateKey(self.key, len(self.alphabet))
            if valid is True:
                # Continue the algorithm
                self.result.insert(
                    0.0,
                    AffineCipher.decryptMessage(message, self.key,
                                                self.alphabet))
            else:
                # Show a warning message
                self.warning[
                    "text"] = "This key can't be used with this alphabet.\nPlease enter another key."
                self.warning.grid(row=self.affine_row + 6,
                                  column=11,
                                  sticky=W + W,
                                  padx=10,
                                  columnspan=2,
                                  rowspan=2)

        elif cipher == 2:  # Caesar Cipher
            self.result.insert(
                0.0,
                CaesarCipher.decryptMessage(message, self.key, self.alphabet))

        elif cipher == 3:  # Multiplicative Cipher
            valid = MultiplicativeCipher.validateKey(self.key,
                                                     len(self.alphabet))
            if valid is True:
                # Continue the algorithm
                self.result.insert(
                    0.0,
                    MultiplicativeCipher.decryptMessage(
                        message, self.key, self.alphabet))
            else:
                # Show a warning message
                self.warning[
                    "text"] = "This key can't be used with this alphabet.\nPlease enter another key."
                self.warning.grid(row=self.affine_row + 6,
                                  column=11,
                                  sticky=W + W,
                                  padx=10,
                                  columnspan=2,
                                  rowspan=2)

        elif cipher == 4:  # My Cipher
            valid = MyCipher.validateKey(self.key, len(self.alphabet))
            if valid is True:
                # Continue the algorithm
                self.result.insert(
                    0.0,
                    MyCipher.decryptMessage(message, self.key, self.alphabet))
            else:
                # Show a warning message
                self.warning[
                    "text"] = "This key can't be used with this alphabet.\nPlease enter another key."
                self.warning.grid(row=self.affine_row + 6,
                                  column=11,
                                  sticky=W + W,
                                  padx=10,
                                  columnspan=2,
                                  rowspan=2)

        elif cipher == 5:  # Transposition Cipher
            self.result.insert(
                0.0, TranspositionCipher.decryptMessage(message, self.key))

        # Setting result for read-only again
        self.result.configure(state='disabled')