Beispiel #1
0
def decode(cipher: str, key: Union[int, str], input_file, output_file):
    """Use this command to decode the text (read from stdio or a file)
       using the available ciphers and display the decrypted text or write
       it to a file.
    """

    input_file_name = input_file.name if input_file is not None else None
    output_file_name = output_file.name if output_file is not None else None

    io_handler = IOHandler(input_file_name, output_file_name)

    input_text = io_handler.read()

    if cipher == "caesar":
        key = Caesar.check_key_type(key, int)
        c = Caesar(key=key)
        decrypted_str = c.decrypt(input_text)

    if cipher == "vigenere":
        v = Vigenere(key=key)
        decrypted_str = v.decrypt(input_text)

    if cipher == "vernam":
        if input_file is None:
            print(("An input file is required for the Vernam cipher"
                   " to work correctly. Exitting..."))
            sys.exit()
        vernam = Vernam(key=key)
        decrypted_str = vernam.decrypt(input_text)

    io_handler.write(decrypted_str)
Beispiel #2
0
def test_banburismus():
    """Test the Banburismus test with two different vigenere
    ciphertext first and then with two equals.
    """
    text1 = ("Once upon a midnight dreary, while I pondered, weak and weary "
             "Over many a quaint and curious volume of forgotten lores.")
    text2 = ("While I nodded, nearly napping, suddenly there came a tapping "
             "As of some one gently rapping, rapping at my chamber door")
    vigenere1 = Vigenere(key_length=8)
    vigenere2 = Vigenere(key_length=8)

    # H1 case
    print("\nGenerated by the same cipher:")
    ciphertext1 = vigenere1.encrypt(text1)
    ciphertext2 = vigenere1.encrypt(text2)
    banburismus(ciphertext1, ciphertext2)

    # H0 case
    print("\nGenerated by the different ciphers:")
    ciphertext1 = vigenere1.encrypt(text1)
    ciphertext2 = vigenere2.encrypt(text2)
    banburismus(ciphertext1, ciphertext2)
Beispiel #3
0
 def __init__(self):
     super().__init__()
     self.vg = Vigenere()
     self.initUI()
Beispiel #4
0
class vigenereFrame(frameTemplate):
    def __init__(self):
        super().__init__()
        self.vg = Vigenere()
        self.initUI()

    def initUI(self):
        super().initUI()

        self.definition.insertPlainText(vigenere_txt)

        self.cb_method.addItem("Encrypt")
        self.cb_method.addItem("Decrypt")
        self.cb_method.currentIndexChanged.connect(self.selectionChange)
        self.btn_encrypt.clicked.connect(self.encrypt)

        self.label_key = QLabel()
        self.label_key.setText('Ključ:')

        self.key_input = QLineEdit(self)

        regex = QtCore.QRegExp("^[a-zA-Z]+$")
        validator = QtGui.QRegExpValidator(regex, self.key_input)
        self.key_input.setValidator(validator)

        text_validator = QtGui.QRegExpValidator(regex, self.plaintext)
        self.plaintext.setValidator(validator)

        self.checkbox_autokey = QCheckBox("Autokey")
        self.checkbox_autokey.setChecked(False)
        self.checkbox_autokey.stateChanged.connect(self.stateChange)

        self.encryption_v_box.addWidget(self.label_key)
        self.encryption_v_box.addWidget(self.key_input)
        self.encryption_v_box.addWidget(self.checkbox_autokey)

    def selectionChange(self, index):
        if (self.cb_method.itemText(index) == "Encrypt"):
            self.label_plaintext.setText("Plaintext:")
            self.label_ciphertext.setText("Ciphertext:")

            if(self.checkbox_autokey.isChecked()):
                self.btn_encrypt.clicked.disconnect()
                self.btn_encrypt.clicked.connect(self.autokeyEncrypt)
            else:
                self.btn_encrypt.clicked.disconnect()
                self.btn_encrypt.clicked.connect(self.encrypt)

            self.btn_encrypt.setText("Encrypt")
            self.plaintext.clear()
            self.ciphertext.clear()

        elif (self.cb_method.itemText(index) == "Decrypt"):
            self.label_plaintext.setText("Ciphertext:")
            self.label_ciphertext.setText("Plaintext:")

            if(self.checkbox_autokey.isChecked()):
                self.btn_encrypt.clicked.disconnect()
                self.btn_encrypt.clicked.connect(self.autokeyDecrypt)
            else:
                self.btn_encrypt.clicked.disconnect()
                self.btn_encrypt.clicked.connect(self.decrypt)

            self.btn_encrypt.setText("Decrypt")
            self.plaintext.clear()
            self.ciphertext.clear()

    def stateChange(self):
        self.btn_encrypt.clicked.disconnect()

        if(self.checkbox_autokey.isChecked()):
            if (str(self.cb_method.currentText()) == "Encrypt"):
                self.btn_encrypt.clicked.connect(self.autokeyEncrypt)
            else:
                self.btn_encrypt.clicked.connect(self.autokeyDecrypt)

        else:
            if (str(self.cb_method.currentText()) == "Encrypt"):
                self.btn_encrypt.clicked.connect(self.encrypt)
            else:
                self.btn_encrypt.clicked.connect(self.decrypt)

    def encrypt(self):
        if(self.validateKey()):
            text = self.vg.encrypt(self.plaintext.text(), self.key_input.text())
            self.ciphertext.setText(text)
            self.key_input.setStyleSheet('QLineEdit { border-color: #1e1e1e }')

    def decrypt(self):
        if(self.validateKey()):
            text = self.vg.decrypt(self.plaintext.text(), self.key_input.text())
            self.ciphertext.setText(text)
            self.key_input.setStyleSheet('QLineEdit { border-color: #1e1e1e }')

    def autokeyEncrypt(self):
        if(self.validateKey()):
            text = self.vg.autokeyEncrypt(self.plaintext.text(), self.key_input.text())
            self.ciphertext.setText(text)
            self.key_input.setStyleSheet('QLineEdit { border-color: #1e1e1e }')

    def validateKey(self):
        if(self.key_input.text() == ''):
            self.key_input.setPlaceholderText("Key is required")
            self.key_input.setStyleSheet('QLineEdit { border-color: #EC0505 }')
            return False

        return True

    def autokeyDecrypt(self):
        if(self.validateKey()):
            text = self.vg.autokeyDecrypt(self.plaintext.text(), self.key_input.text())
            self.ciphertext.setText(text)
            self.key_input.setStyleSheet('QLineEdit { border-color: #1e1e1e }')
Beispiel #5
0
# K2
from ciphers.vigenere import VigenereTableau, Vigenere

kryptos_alphabet = "KRYPTOSABCDEFGHIJLMNQUVWXZ"
vtableau = VigenereTableau(alphabet=kryptos_alphabet, row_fill=0, col_fill=4)
cipher = Vigenere(tableau=vtableau)

ciphertext = "VFPJUDEEHZWETZYVGWHKKQETGFQJNCEGGWHKK?DQMCPFQZDQMMIAGPFXHQRLGTIMVMZJANQLVKQEDAGDVFRPJUNGEUNAQZGZLECGYUXUEENJTBJLBQCRTBJDFHRRYIZETKZEMVDUFKSJHKFWHKUWQLSZFTIHHDDDUVH?DWKBFUFPWNTDFIYCUQZEREEVLDKFEZMOQQJLTTUGSYQPFEUNLAVIDXFLGGTEZ?FKZBSFDQVGOGIPUFXHHDRKFFHQNTGPUAECNUVPDJMQCLQUMUNEDFQELZZVRRGKFFVOEEXBDMVPNFQXEZLGREDNQFMPNZGLFLPMRJQYALMGNUVPDXVKPDQUMEBEDMHDAFMJGZNUPLGESWJLLAETG"
keyword = "ABSCISSA"
plaintext = cipher.decrypt(ciphertext, keyword)

print "K2"
print ciphertext
print plaintext
def main(argv):
    cipher_type, display_type, ifile, ofile, key_file = parse_cli(argv)
    print('\n == TUCIL 1 KRIPTOGRAFI ==\n')
    print(
        list(cipher_type_list.keys())[cipher_type].upper() +
        ' ENCRYPTION function selected\n')
    plaintext = ''
    key = ''
    ciphertext = ''
    if cipher_type == 4:
        plaintext = read_input_bytes(ifile, 'plaintext')
    else:
        plaintext = read_input(ifile, 'plaintext')
    key = read_key(key_file)

    if cipher_type == 0:
        print("\n==== USING VIGINERE CIPHER ====\n")
        ciphertext = Vigenere().encipher(plaintext, key)
    elif cipher_type == 1:
        print("\n==== USING FULL VIGINERE CIPHER ====\n")
        vigenere_square = read_vigenere_json()
        ciphertext = Vigenere().full_enchiper(plaintext, key, vigenere_square)
    elif cipher_type == 2:
        print("\n==== USING AUTO-KEY VIGINERE CIPHER ====\n")
        ciphertext = Vigenere().auto_key_enchiper(plaintext, key)
    elif cipher_type == 3:
        print("\n==== USING RUNNING-KEY VIGINERE CIPHER ====\n")
        ciphertext = Vigenere().encipher(plaintext, key)
    elif cipher_type == 4:
        print("\n==== USING EXTENDED VIGINERE CIPHER ====\n")
        ciphertext = ExtendedVigenere().encipher(plaintext, key)
    elif cipher_type == 5:
        print("\n==== USING PLAYFAIR CIPHER ====\n")
        no_punc = True
        no_space = True
        if display_type == 0:
            no_punc = False
            no_space = False
        elif display_type == 1:
            no_punc = False

        removed_char = input('Masukkan huruf yang dihilangkan > ').upper()
        placeholder_char = input('Masukkan huruf penyisip > ').upper()
        ciphertext = Playfair().encipher(plaintext,
                                         key,
                                         removed_char,
                                         placeholder_char,
                                         no_punc=no_punc,
                                         no_space=no_space)

    if hasattr(ciphertext, 'decode'):
        # ciphertext is in bytes
        while ofile == '':
            ofile = input('Enter encrytion result save directory:\n> ')
        save_output_bytes(ciphertext, ofile)
        print('Result saved to %s \n' % (ofile))
    else:
        # ciphertext is a string
        ciphertext = arrange_output(ciphertext, display_type)
        print('\nENCRYPTION RESULT:\n' + ciphertext + '\n')
        save_output(ciphertext, ofile)
Beispiel #7
0
write_file('hill_cipher_2x2.txt', output)

plain_list = read_file('hill_plain_3x3.txt')
output = ''
output += '      |2   4  12|\n'
output += 'Key = |9   1   6|\n'
output += '      |7   5   3|\n\n'
for plain in plain_list:
    hill = Hill(plain, [[2, 4, 12], [9, 1, 6], [7, 5, 3]])
    output += hill.encrypt() + '\n'
write_file('hill_cipher_3x3.txt', output)

plain_list = read_file('vigenere_plain.txt')
output = 'Key = pie\t(repeating mode)\n'
for plain in plain_list:
    vigenere = Vigenere(plain, 'pie', False)
    output += vigenere.encrypt() + '\n'

output += '\nKey = aether\t(auto mode)\n'
for plain in plain_list:
    vigenere = Vigenere(plain, 'aether', True)
    output += vigenere.encrypt() + '\n'
output += '\n'
write_file('vigenere_cipher.txt', output)

plain_list = read_file('vernam_plain.txt')
output = 'Key = SPARTANS\n'
for plain in plain_list:
    vernam = Vernam(plain, 'SPARTANS')
    output += vernam.encrypt() + '\n'
write_file('vernam_cipher.txt', output)
Beispiel #8
0
def test_vigenere_algorithm_dec():
    c = Vigenere(key="42")
    assert c.decrypt("bcdø") == "PSRø"
Beispiel #9
0
def test_vigenere_algorithm_enc():
    c = Vigenere(key="42")
    assert c.encrypt("abc\n") == "436\n"
Beispiel #10
0
def test_vigenere_algorithm_dec_enc(a):
    c = Vigenere(key="42")
    assert c.encrypt(c.decrypt(a)) == a