Example #1
0
def AutokeyBF(ctext, dictionary, ch, ch2):

    if ch == 'True':

        f = open(dictionary, 'r')
        keys = f.readlines()
        print('\033[1;34m[*]\033[0m Starting Brute Force Attack...')
        for i in keys:
            try:
                out = Autokey(i[:-1]).decipher(ctext)
                if ch2 in out:
                    print('\033[1;32m[+]\033[0m Key = ' + i[:-1] +
                          ' ; Out = ' + out)
                    break
                    exit()
                print('\033[1;34m[*]\033[0m Key = ' + i[:-1] + ' ; Out = ' +
                      out)
            except:
                print('\033[1;34m[*]\033[0m Key = ' + i[:-1] +
                      ' ; Err.: KeyError')

    else:

        f = open(dictionary, 'r')
        keys = f.readlines()

        for i in keys:
            try:
                out = Autokey(i[:-1]).decipher(ctext)
                print('\033[1;34m[*]\033[0m Key = ' + i[:-1] + ' ; Out = ' +
                      out)
            except:
                print('\033[1;34m[*]\033[0m Key = ' + i[:-1] +
                      ' ; Err.: KeyError')
        print('\033[1;32m[+]\033[0m Brute Force finished.')
Example #2
0
def AutokeyCracker(ctext, q1gram, t1gram):

    qgram = ngram_score(q1gram)
    trigram = ngram_score(t1gram)
    ctext = re.sub(r'[^A-Z]', '', ctext.upper())

    class nbest(object):
        def __init__(self, N=1000):
            self.store = []
            self.N = N

        def add(self, item):
            self.store.append(item)
            self.store.sort(reverse=True)
            self.store = self.store[:self.N]

        def __getitem__(self, k):
            return self.store[k]

        def __len__(self):
            return len(self.store)

    N = 100
    for KLEN in range(3, 20):
        rec = nbest(N)

        for i in permutations('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 3):
            key = ''.join(i) + 'A' * (KLEN - len(i))
            pt = Autokey(key).decipher(ctext)
            score = 0
            for j in range(0, len(ctext), KLEN):
                score += trigram.score(pt[j:j + 3])
            rec.add((score, ''.join(i), pt[:30]))

        next_rec = nbest(N)
        for i in range(0, KLEN - 3):
            for k in xrange(N):
                for c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
                    key = rec[k][1] + c
                    fullkey = key + 'A' * (KLEN - len(key))
                    pt = Autokey(fullkey).decipher(ctext)
                    score = 0
                    for j in range(0, len(ctext), KLEN):
                        score += qgram.score(pt[j:j + len(key)])
                    next_rec.add((score, key, pt[:30]))
            rec = next_rec
            next_rec = nbest(N)
        bestkey = rec[0][1]
        pt = Autokey(bestkey).decipher(ctext)
        bestscore = qgram.score(pt)
        for i in range(N):
            pt = Autokey(rec[i][1]).decipher(ctext)
            score = qgram.score(pt)
            if score > bestscore:
                bestkey = rec[i][1]
                bestscore = score
        print('\033[1;34m[*]\033[0m Score = ' + str(bestscore) +
              ' ; Iteration = ' + str(KLEN) + ' ; Key = ' + bestkey +
              ' ; Out = ' + Autokey(bestkey).decipher(ctext))
Example #3
0
 def test_encipher(self):
     keys = ('GERMAN', 'CIPHERS')
     plaintext = ('abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz',
                  'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz')
     ciphertext = ('gftpesgikmoqsuwyacegikmoqsuwyacegikmoqsuwyacegikmoqs',
                   'cjrkiwyhjlnprtvxzbdfhjlnprtvxzbdfhjlnprtvxzbdfhjlnpr')
     for i, key in enumerate(keys):
         enc = Autokey(key).encipher(plaintext[i])
         self.assertEqual(enc.upper(), ciphertext[i].upper())
Example #4
0
 def test_encipher(self):
     keys = ('GERMAN',
             'CIPHERS')
     plaintext = ('abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz',
                  'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz')
     ciphertext = ('gftpesgikmoqsuwyacegikmoqsuwyacegikmoqsuwyacegikmoqs',
                   'cjrkiwyhjlnprtvxzbdfhjlnprtvxzbdfhjlnprtvxzbdfhjlnpr')
     for i,key in enumerate(keys):
         enc = Autokey(key).encipher(plaintext[i])
         self.assertEqual(enc.upper(), ciphertext[i].upper())
Example #5
0
def vigenere(request):
    if request.method == 'POST':
        key = request.POST['key']
        input = request.POST['input']
        type1 = request.POST['type']
        output = ""
        if key == '0':
            output = "请输入Key??"
            return HttpResponse(output)
        if type1 == "ve":
            output = Vigenere(key).encipher(input)
        elif type1 == "vd":
            output = Vigenere(key).decipher(input)
        elif type1 == "ae":
            output = Autokey(key).encipher(input)
        elif type1 == "ad":
            output = Autokey(key).decipher(input)
        else:
            output = "客官您是什么操作呀??"
        return HttpResponse(output)
    else:
        return render(request, 'vigenere.html')
Example #6
0
def Decrypt_AutoKey():
    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:
        finalMessage = Autokey(Key).decipher(inputMessage)

    output_2.insert(END, finalMessage)  #replace inputMessage with final result
    print("Done")
    def __getitem__(self, k):
        return self.store[k]

    def __len__(self):
        return len(self.store)


#init
N = 100
for KLEN in range(3, 20):
    rec = nbest(N)

    for i in permutations('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 3):
        key = ''.join(i) + 'A' * (KLEN - len(i))
        pt = Autokey(key).decipher(ctext)
        score = 0
        for j in range(0, len(ctext), KLEN):
            score += trigram.score(pt[j:j + 3])
        rec.add((score, ''.join(i), pt[:30]))

    next_rec = nbest(N)
    for i in range(0, KLEN - 3):
        for k in xrange(N):
            for c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
                key = rec[k][1] + c
                fullkey = key + 'A' * (KLEN - len(key))
                pt = Autokey(fullkey).decipher(ctext)
                score = 0
                for j in range(0, len(ctext), KLEN):
                    score += qgram.score(pt[j:j + len(key)])
Example #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
Example #9
0
from pycipher import Autokey

if __name__ == "__main__":
    d = Autokey('AutomaticKey')
    s = 'fftu{2028mb39927wn1f96o6e12z03j58002p}'
    ans = d.decipher(s)
    print(ans)
    def __getitem__(self, k):
        return self.store[k]

    def __len__(self):
        return len(self.store)


#init
N = 100
for KLEN in range(3, 20):
    rec = nbest(N)

    for i in permutations('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 3):
        key = ''.join(i) + 'A' * (KLEN - len(i))
        pt = Autokey(key).decipher(ctext)
        score = 0
        for j in range(0, len(ctext), KLEN):
            score += trigram.score(pt[j:j + 3])
        rec.add((score, ''.join(i), pt[:30]))

    next_rec = nbest(N)
    for i in range(0, KLEN - 3):
        for k in range(N):
            for c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
                key = rec[k][1] + c
                fullkey = key + 'A' * (KLEN - len(key))
                pt = Autokey(fullkey).decipher(ctext)
                score = 0
                for j in range(0, len(ctext), KLEN):
                    score += qgram.score(pt[j:j + len(key)])