Exemple #1
0
def Decrypt_Playfair():

    inputMessage = ""
    key = ""
    finalMessage = ""
    output_2.delete('1.0', END)
    inputMessage = output.get("1.0", END)
    Key = inputKeyBox.get()

    if inputMessage == "" or Key == "":
        messagebox.showinfo('Input Error',
                            'You must enter both key and message')
    else:
        if len(set(Key)) == len(Key) and len(Key) == 25:
            finalMessage = Playfair(Key).decipher(inputMessage)
        else:
            messagebox.showinfo(
                'Input Error',
                'For playcipher, the key must be 25 different letters')

    output_2.insert(END, finalMessage)  #replace inputMessage with final result
    print("Done")
if cipher_scheme == '1':
    """Caesar cipher."""
    if encryption_type == "E":
        e_msg = Caesar(key=-3).encipher(message)
        print("Encrypted Message: ", e_msg)

    elif encryption_type == "D":
        d_msg = Caesar(key=-3).decipher(message)
        print("Decrypted Message: ", d_msg)

if cipher_scheme == '2':
    """Substitution cipher."""
    off = int(input("Enter Key: "))
    if encryption_type == "E":
        e_msg = Caesar(key=off).encipher(message)
        print("Encrypted Message: ", e_msg)

    elif encryption_type == "D":
        d_msg = Caesar(key=off).decipher(message)
        print("Decrypted Message: ", d_msg)

if cipher_scheme == '3':
    """Playfair cipher"""
    if encryption_type == "E":
        e_msg = Playfair(key='HELOWRDABCFGIJKMNPSTUVXYZ').encipher(message)
        print("Encrypted Message: ", e_msg)

    elif encryption_type == "D":
        d_msg = Playfair(key='HELOWRDABCFGIJKMNPSTUVXYZ').decipher(message)
        print("Decrypted Message: ", d_msg)
Exemple #3
0
def playfair_decode(s):
    """Decode"""
    return Playfair().decipher(s)
Exemple #4
0
import socket
from pycipher import Playfair

s = socket.socket()
host = "127.0.0.1"
port = 12358
s.bind((host, port))
s.listen(5)
while True:
    c, a = s.accept()
    print("addr : ", a)
    rcv_pwd = c.recv(1024)
    rcv_pwd = str(rcv_pwd.decode("utf-8"))
    if (Playfair("cdabefhgkijlmnoprqstuvzwxy").encipher("hello") == rcv_pwd):
        print("password successful")
    else:
        print("wrong password ")
    c.close()
#Public-key cryptography
elif code_type == "Keys":
    print("Input public_key: ")
    public_key = input("Public key \n")
    while len(public_key) != 6:
        if len(public_key) > 6:
            print("Error! Public key's are 6 characters long!")
        else:
            print("Error! Public key's are 6 characters long!")
        public_key = input("Public key \n")
    print("Input private key:")
    private_key = input("Private key \n")
    while len(private_key) != 2:
        if len(private_key) > 2:
            print("Error! Public key's are 2 characters long!")
        else:
            print("Error! Public key's are 2 characters long!")
        private_key = input("Private key \n")

    decoded_message += str(int(private_key) * int(public_key))

#Playfair Cipher
#check out kanpurpython.wordpress.com/2017/08/22/playfair-cipher-using-python/
elif code_type == "Playfair":
    print("Input coded message:")
    message = input("Coded message \n")
    decoded_message += Playfair("cdabefhgkijlmnoprqstuvzwxy").decipher(message)

print("Decoded message: \n" + decoded_message.title())
print("You welcome.")
Exemple #6
0
def playfairencode(importx, infilepath, outfilepath, inputformat, export, raw,
                   key):

    if importx == 'file':

        f = open(infilepath, 'r')
        raw = f.read()
        f.close()

    elif importx == 'print':

        raw = raw

    else:

        print('\033[1;31m[-]\033[0m Unknown error.')
        return False

    inp = raw

    if inputformat == 'base64':

        iput = base64.b64decode(inp)

    elif inputformat == 'raw':

        iput = inp

    elif inputformat == 'base32':

        iput = base64.b32decode(inp)

    elif inputformat == 'base16':

        iput = base64.b16decode(inp)

    elif inputformat == 'base58':

        iput = base58.b58decode(inp)

    elif inputformat == 'base85':

        print('\033[1;31m[-]\033[0m Option not available yet')

    elif inputformat == 'hex':

        iput = inp.decode('hex')

    elif inputformat == 'dec':

        print('\033[1;31m[-]\033[0m Option not available yet')

    elif inputformat == 'octal':

        print('\033[1;31m[-]\033[0m Option not available yet')

    elif inputformat == 'binary':

        iput = text_from_bits(inp)

    else:

        print('\033[1;31m[-]\033[0m Unknown error.')
        return False

    output = Playfair(key=key).encipher(iput)

    if export == 'file':

        f = open(outfilepath, 'w')
        f.write(output)
        f.close()
        return True

    elif export == 'print':

        return output

    else:

        print('\033[1;31m[-]\033[0m Unknown error.')
        return False
Exemple #7
0
import socket
from pycipher import Playfair

s = socket.socket()
host = "127.0.0.1"
port = 12358
s.connect((host, port))

msg = str(input("Password: "******"cdabefhgkijlmnoprqstuvzwxy").encipher(msg)
print(msg)
s.send(bytes(msg, 'utf-8'))
s.close()
"""
Output
===============

➜  A6 python3 server.py
addr :  ('127.0.0.1', 51571)
password successful
addr :  ('127.0.0.1', 51572)
wrong password



➜  A6 python3 client.py
Password: hello
IDOVTE
➜  A6 python3 client.py
Password: world
XNVREV
Exemple #8
0
def encrypt(keycodeLines, encryptionDirection, plaintextContents):
    for i in range(len(keycodeLines)):  #Iterate over the keycode.
        if (encryptionDirection == "encrypt"):
            splitLine = keycodeLines[i].split()
        else:
            splitLine = keycodeLines[len(keycodeLines) - 1 - i].split(
            )  #This ensures that if the encryption direction is set to decrypt, that this for loop reads the keycode.txt from end to beginning.

        # print("Line " + str(i) + " is " + keycodeLines[i] + " and the split line is: " + str(splitLine)) # This was an old debugging line that may be useful in the future.
        if (splitLine[0] == "caesar"):
            if (int(splitLine[1]) > 25 or int(splitLine[1]) < 1):
                print("Keycode line: " + str(i + 1) +
                      ": Caesar shift detected on keycode line " + str(i) +
                      " attempting to shift by value " + splitLine[1] + ".")
                sys.exit()
            else:
                originalPlaintext = plaintextContents
                if (debug):
                    print("Keycode line: " + str(i + 1) +
                          ": Caesar shift detected with an argument of " +
                          splitLine[1] + ".")
                if (encryptionDirection == "encrypt"):
                    plaintextContents = Caesar(int(
                        splitLine[1])).encipher(plaintextContents)
                else:
                    plaintextContents = Caesar(int(
                        splitLine[1])).decipher(plaintextContents)
                if (debug):
                    print("Keycode line: " + str(i + 1) + ": Caesar shifted " +
                          originalPlaintext + " by " + splitLine[1] +
                          " with a result of " + plaintextContents + ".")
        elif (splitLine[0] == "vigenere"):
            if (type(splitLine[1] != str)):
                originalPlaintext = plaintextContents
                if (debug):
                    print("Keycode line: " + str(i + 1) +
                          ": Vigenère shift detected with an argument of " +
                          splitLine[1] + ".")
                if (encryptionDirection == "encrypt"):
                    plaintextContents = Vigenere(
                        splitLine[1]).encipher(plaintextContents)
                else:
                    plaintextContents = Vigenere(
                        splitLine[1]).decipher(plaintextContents)
                if (debug):
                    print("Keycode line: " + str(i + 1) +
                          ": Vigenère shifted " + originalPlaintext + " by " +
                          splitLine[1] + " with a result of " +
                          plaintextContents + ".")
            else:
                print("Keycode line: " + str(i + 1) +
                      ": Vigenère shift detected on keycode line " + str(i) +
                      " attempting to use key that is not a string.")
        elif (splitLine[0] == "porta"):
            if (type(splitLine[1] != str)):
                originalPlaintext = plaintextContents
                if (debug):
                    print("Keycode line: " + str(i + 1) +
                          ": Porta cipher detected with an argument of " +
                          splitLine[1] + ".")
                if (encryptionDirection == "encrypt"):
                    plaintextContents = Porta(
                        splitLine[1]).encipher(plaintextContents)
                else:
                    plaintextContents = Porta(
                        splitLine[1]).decipher(plaintextContents)
                if (debug):
                    print("Keycode line: " + str(i + 1) +
                          ": Vigenère shifted " + originalPlaintext + " by " +
                          splitLine[1] + " with a result of " +
                          plaintextContents + ".")
            else:
                print("Keycode line: " + str(i + 1) +
                      ": Vigenère shift detected on keycode line " + str(i) +
                      " attempting to use key that is not a string.")
        elif (splitLine[0] == "adfgx"):
            if (
                    len(splitLine[1]) != 25
            ):  # This makes sure that the keysquare's length is exactly 25.
                print(
                    "Keycode line: " + str(i + 1) +
                    ": ADFGX cipher detected on keycode line " + str(i) +
                    " attempting to use keysquare that is not 25 characters long."
                )
                sys.exit()
            else:
                originalPlaintext = plaintextContents
                if (debug):
                    print("Keycode line: " + str(i + 1) +
                          ": ADFGX cipher detected with a keysquare of " +
                          splitLine[1] + " and a keyword of " + splitLine[2] +
                          ".")
                if (encryptionDirection == "encrypt"):
                    plaintextContents = ADFGX(
                        splitLine[1], splitLine[2]).encipher(plaintextContents)
                else:
                    plaintextContents = ADFGX(
                        splitLine[1], splitLine[2]).decipher(plaintextContents)
                if (debug):
                    print("Keycode line: " + str(i + 1) + ": ADFGX ciphered " +
                          originalPlaintext + " by a keysquare of " +
                          splitLine[1] + " and a keyword of " + splitLine[2] +
                          " with a result of " + plaintextContents + ".")
        elif (
                splitLine[0] == "adfgvx"
        ):  #The first argument is the keysquare, and the second argument is the keyword.
            if (
                    len(splitLine[1]) != 36
            ):  # This makes sure that the keysquare's length is exactly 36.
                print(
                    "Keycode line: " + str(i) +
                    ": ADFGVX cipher detected on keycode line " + str(i) +
                    " attempting to use keysquare that is not 25 characters long, but is instead "
                    + str(len(splitLine[1])) + " characters long.")
                sys.exit()
            else:
                originalPlaintext = plaintextContents
                if (debug):
                    print("Keycode line: " + str(i + 1) +
                          ": ADFGVX cipher detected with a keysquare of " +
                          splitLine[1] + " and a keyword of " + splitLine[2] +
                          ".")
                if (encryptionDirection == "encrypt"):
                    plaintextContents = ADFGVX(
                        splitLine[1], splitLine[2]).encipher(plaintextContents)
                else:
                    plaintextContents = ADFGVX(
                        splitLine[1], splitLine[2]).decipher(plaintextContents)
                if (debug):
                    print("Keycode line: " + str(i + 1) +
                          ": ADFGVX ciphered " + originalPlaintext +
                          " by a keysquare of " + splitLine[1] +
                          " and a keyword of " + splitLine[2] +
                          " with a result of " + plaintextContents + ".")
        elif (splitLine[0] == "affine"):
            if ((int(splitLine[2]) < 1) or (int(splitLine[2]) > 25)):
                print(
                    "Keycode line: " + str(i + 1) +
                    ": Affine cipher detected on keycode line " + str(i) +
                    " attempting to use b value outside of the range of 1-25.")
                sys.exit()
            elif ((int(splitLine[1]) == 13) or (int(splitLine[1]) % 2 != 1)
                  or (int(splitLine[1]) > 25) or (int(splitLine[1]) < 1)):
                print(
                    "Keycode line: " + str(i + 1) +
                    ": Affine cipher detected on keycode line " + str(i) +
                    " attempting to use an a value outside of the range of 1-25, that is even, or that is 13, all of which are not permitted."
                )
                sys.exit()
            else:
                originalPlaintext = plaintextContents
                if (debug):
                    print("Keycode line: " + str(i + 1) +
                          ": Affine cipher detected with an a value of " +
                          splitLine[1] + " and a b value of " + splitLine[2] +
                          ".")
                if (encryptionDirection == "encrypt"):
                    plaintextContents = Affine(
                        int(splitLine[1]),
                        int(splitLine[2])).encipher(plaintextContents)
                else:
                    plaintextContents = Affine(
                        int(splitLine[1]),
                        int(splitLine[2])).decipher(plaintextContents)
                if (debug):
                    print("Keycode line: " + str(i + 1) +
                          ": Affine ciphered " + originalPlaintext +
                          " by value a " + splitLine[1] + " and value b " +
                          splitLine[2] + " with a result of " +
                          plaintextContents + ".")
        elif (
                splitLine[0] == "autokey"
        ):  #TODO: The autokey cipher actually doesn't have any requirements for the key, but will be configured to set off a ton of warnings assuming the config flags allow for it.
            originalPlaintext = plaintextContents
            if (debug):
                print("Keycode line: " + str(i + 1) +
                      ": Autokey cipher detected with an key of " +
                      splitLine[1] + ".")
            if (encryptionDirection == "encrypt"):
                plaintextContents = Autokey(
                    splitLine[1]).encipher(plaintextContents)
            else:
                plaintextContents = Autokey(
                    splitLine[1]).decipher(plaintextContents)
            if (debug):
                print("Keycode line: " + str(i + 1) + ": Autokey ciphered " +
                      originalPlaintext + " by key of " + splitLine[1] +
                      " for a result of " + plaintextContents + ".")
        elif (splitLine[0] == "atbash"):
            originalPlaintext = plaintextContents
            if (debug):
                print("Keycode line: " + str(i + 1) +
                      ": Autokey cipher detected.")
            if (encryptionDirection == "encrypt"):
                plaintextContents = Affine(25, 25).encipher(plaintextContents)
            else:
                plaintextContents = Affine(25, 25).decipher(plaintextContents)
            if (debug):
                print("Keycode line: " + str(i + 1) + ": Atbash ciphered " +
                      originalPlaintext + " for a result of " +
                      plaintextContents + ".")
        elif (splitLine[0] == "beaufort"):
            if (type(splitLine[1] == str)):
                originalPlaintext = plaintextContents
                if (debug):
                    print("Keycode line: " + str(i + 1) +
                          ": Beaufort shift detected with an argument of " +
                          splitLine[1] + ".")
                if (encryptionDirection == "encrypt"):
                    plaintextContents = Beaufort(
                        splitLine[1]).encipher(plaintextContents)
                else:
                    plaintextContents = Beaufort(
                        splitLine[1]).decipher(plaintextContents)
                if (debug):
                    print("Keycode line: " + str(i + 1) +
                          ": Beaufort shifted " + originalPlaintext + " by " +
                          splitLine[1] + " with a result of " +
                          plaintextContents + ".")
            else:
                print("Keycode line: " + str(i + 1) +
                      ": Beaufort shift detected on keycode line " + str(i) +
                      " attempting to use key that is not a string.")
        elif (splitLine[0] == "bifid"):
            if (
                    len(splitLine[1]) != 25
            ):  # This makes sure that the keysquare's length is exactly 25.
                print(
                    "Keycode line: " + str(i + 1) +
                    ": Bifid cipher detected on keycode line " + str(i) +
                    " attempting to use keysquare that is not 25 characters long."
                )
                sys.exit()
            else:
                originalPlaintext = plaintextContents
                if (debug):
                    print("Keycode line: " + str(i + 1) +
                          ": Bifid cipher detected with a keysquare of " +
                          splitLine[1] + " and a keyword of " + splitLine[2] +
                          ".")
                if (encryptionDirection == "encrypt"):
                    plaintextContents = Bifid(splitLine[1], int(
                        splitLine[2])).encipher(plaintextContents)
                else:
                    plaintextContents = Bifid(splitLine[1], int(
                        splitLine[2])).decipher(plaintextContents)
                if (debug):
                    print("Keycode line: " + str(i + 1) + ": Bifid ciphered " +
                          originalPlaintext + " by a keysquare of " +
                          splitLine[1] + " and a keyword of " + splitLine[2] +
                          " with a result of " + plaintextContents + ".")
        elif (splitLine[0] == "coltrans"):
            if (type(splitLine[1] != str)
                ):  # Check that the encryption key is a string.
                originalPlaintext = plaintextContents
                if (debug):
                    print(
                        "Keycode line: " + str(i + 1) +
                        ": Columnar transposition shift detected with an argument of "
                        + splitLine[1] + ".")
                if (encryptionDirection == "encrypt"):
                    plaintextContents = ColTrans(
                        splitLine[1]).encipher(plaintextContents)
                else:
                    plaintextContents = ColTrans(
                        splitLine[1]).decipher(plaintextContents)
                if (debug):
                    print("Keycode line: " + str(i + 1) +
                          ": Columnar transposition shifted " +
                          originalPlaintext + " by " + splitLine[1] +
                          " with a result of " + plaintextContents + ".")
            else:
                print(
                    "Keycode line: " + str(i + 1) +
                    ": Columnar transposition shift detected on keycode line "
                    + str(i) + " attempting to use key that is not a string.")
        elif (splitLine[0] == "foursquare"):
            if (
                    len(splitLine[1]) != 25
            ):  # This makes sure that the keysquare's length is exactly 25.
                print(
                    "Foursquare cipher detected on keycode line " + str(i) +
                    " attempting to use keysquare that is not 25 characters long."
                )
                sys.exit()
            elif (len(splitLine[2]) != 25):
                print(
                    "Foursquare cipher detected on keycode line " + str(i) +
                    " attempting to use keysquare that is not 25 characters long."
                )
                sys.exit()
            else:
                originalPlaintext = plaintextContents
                if (debug):
                    print("Foursquare cipher detected with a keysquare of " +
                          splitLine[1] + " and a keyword of " + splitLine[2] +
                          ".")
                if (encryptionDirection == "encrypt"):
                    plaintextContents = Foursquare(
                        key1=splitLine[1],
                        key2=splitLine[2]).encipher(plaintextContents)
                else:
                    plaintextContents = Foursquare(
                        key1=splitLine[1],
                        key2=splitLine[2]).decipher(plaintextContents)
                if (debug):
                    print("Foursquare ciphered " + originalPlaintext +
                          " by a keysquare of " + splitLine[1] +
                          " and a keyword of " + splitLine[2] +
                          " with a result of " + plaintextContents + ".")
        elif (splitLine[0] == "playfair"):
            if (
                    len(splitLine[1]) != 25
            ):  # This makes sure that the keysquare's length is exactly 25.
                print(
                    "Keycode line: " + str(i + 1) +
                    ": Playfair cipher detected on keycode line " + str(i) +
                    " attempting to use keysquare that is not 25 characters long."
                )
                sys.exit()
            else:
                originalPlaintext = plaintextContents
                if (encryptionDirection == "encrypt"):
                    plaintextContents = Playfair(
                        splitLine[1]).encipher(plaintextContents)
                else:
                    plaintextContents = Playfair(
                        splitLine[1]).decipher(plaintextContents)
                if (debug):
                    print("Keycode line: " + str(i + 1) +
                          ": Playfair ciphered " + originalPlaintext +
                          " by a keysquare of " + splitLine[1] +
                          " with a result of " + plaintextContents + ".")
        elif (
                splitLine[0] == "railfence"
        ):  #TODO: Fix this so that it throws an error if the key is a bad length relative to the plaintext.
            if (splitLine[1].isdigit() == False):
                print("Keycode line: " + str(i + 1) +
                      ": Railfence cipher detected on keycode line " + str(i) +
                      " with a non-numerical key.")
                sys.exit()
            elif (
                    int(splitLine[1]) < 1
            ):  # This makes sure that the keysquare's length is exactly 25.
                print("Keycode line: " + str(i + 1) +
                      ": Railfence cipher detected on keycode line " + str(i) +
                      " attempting to use a key less than 0.")
                sys.exit()
            else:
                originalPlaintext = plaintextContents
                if (encryptionDirection == "encrypt"):
                    plaintextContents = Railfence(int(
                        splitLine[1])).encipher(plaintextContents)
                else:
                    plaintextContents = Railfence(int(
                        splitLine[1])).decipher(plaintextContents)
                if (debug):
                    print("Keycode line: " + str(i + 1) +
                          ": Railfence ciphered " + originalPlaintext +
                          " by a key of " + splitLine[1] +
                          " with a result of " + plaintextContents + ".")
        elif (splitLine[0] == "rot13"):
            originalPlaintext = plaintextContents
            if (debug):
                print("Keycode line: " + str(i + 1) +
                      ": Rot13 cipher detected.")
            if (encryptionDirection == "encrypt"):
                plaintextContents = Rot13().encipher(plaintextContents)
            else:
                plaintextContents = Rot13().decipher(plaintextContents)
            if (debug):
                print("Keycode line: " + str(i + 1) + ": Rot13 ciphered " +
                      originalPlaintext + " with a result of " +
                      plaintextContents + ".")
        elif (splitLine[0] == "simplesub"):
            if (
                    len(splitLine[1]) != 26
            ):  # This makes sure that the keysquare's length is exactly 25.
                print(
                    "Keycode line: " + str(i + 1) +
                    ": Simple substitution cipher detected on keycode line " +
                    str(i) +
                    " attempting to use key that is not 26 characters long.")
                sys.exit()
            else:
                originalPlaintext = plaintextContents
                if (debug):
                    print(
                        "Keycode line: " + str(i + 1) +
                        ": Simple substitution cipher detected with a key of "
                        + splitLine[1] + ".")
                if (encryptionDirection == "encrypt"):
                    plaintextContents = SimpleSubstitution(
                        splitLine[1]).encipher(plaintextContents)
                else:
                    plaintextContents = SimpleSubstitution(
                        splitLine[1]).decipher(plaintextContents)
                if (debug):
                    print("Keycode line: " + str(i + 1) +
                          ": Simple substitution ciphered " +
                          originalPlaintext + " by a key of " + splitLine[1] +
                          " with a result of " + plaintextContents + ".")
    if (i == (len(keycodeLines) - 1)):
        # print(plaintextContents) #A debug catch that you may find useful later.
        return plaintextContents
Exemple #9
0
 def decode(self, message, key):
     try:
         return Playfair(key).decipher(message)
     except:
         return None
############################################  
波利比奥斯方阵密码
  1  2  3  4   5
1 A  B  C  D   E 
2 F  G  H  I/J K
3 L  M  N  O   P
4 Q  Q  S  T   U
5 V  W  X  Y   Z 
加密实例:
明文: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
密文: 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
Exemple #11
0
from pycipher import Playfair
print Playfair('zgptfoihmuwdrcnykeqaxvsbl').encipher('defend the east wall of the castle')
print Playfair('zgptfoihmuwdrcnykeqaxvsbl').decipher('RKPAWRPMYSELZCLFXUZFRSNQBPSA')
        self.key = list(s)


key = Key()
fitness = ns.ngram_score('quadgrams.txt')
best_score = -20000.0
max_score = -20000.0
best_txt = ""
max_txt = ""
best_key = ""
max_key = ""
for i in range(50):
    T = (50.0 - i) / 5
    for j in range(10000):
        new_key = key.getNewKey()
        decrypted_txt = Playfair(key=new_key).decipher(ciphertext)
        the_score = fitness.score(decrypted_txt)
        dF = the_score - max_score
        if (dF >= 0):
            max_score = the_score
            max_key = new_key
            key.setKey(new_key)
            max_txt = decrypted_txt
        elif (T > 0):
            prob = exp(dF / T)
            if (prob > 1.0 * random.randrange(10) / 10):
                key.setKey(new_key)
                max_key = new_key
                max_txt = decrypted_txt
                max_score = the_score
Exemple #13
0

def swap_parent(parent):
    parent = list(parent)
    a = randint(0, len(parent) - 1)
    _b = randint(0, len(parent) - 2)
    b = _b + 1 if _b >= a else _b
    parent[a], parent[b] = parent[b], parent[a]
    return "".join(parent)


# 1. Generate a random key, called the 'parent', decipher
# the ciphertext using this key
parent = ''.join(sample(ascii_uppercase, 26)).replace("J", "")
parent = "GONPLRSHEAIKTDMBCUQFYWXZV"
parent_deciphered = Playfair(parent).decipher(CIPHERTEXT)

# 2. Rate the fitness of the deciphered text, store the result
fitness = ns('english_bigrams.txt')
parent_fitness = fitness.score(parent_deciphered)

# 3. for(TEMP = 10;TEMP >= 0; TEMP = TEMP - STEP)
TEMP = 10
STEP = 1
maximum_fitness = parent_fitness
while TEMP >= 1:
    TEMP = TEMP - STEP
    print("Current temperature: {}".format(TEMP))
    # for (count = 50,000; count>0; count--)
    for count in reversed(range(50000)):
        # Change the parent key slightly (e.g. swap two