예제 #1
0
def filter_ceasor(request):
    import re
    from decryptionwithoutkey.ngram_score import ngram_score
    fitness = ngram_score('english_quadgrams.txt')  # load our quadgram statistics
    from pycipher import Caesar
    form = CryptoAnalysis()
    if request.method == 'POST':
        form = CryptoAnalysis(request.POST)
        if form.is_valid():
            cipher_text = request.POST['input']
            print(cipher_text)
            cipher_text = str(cipher_text)
            cipher_text = re.sub('[^A-Z]', '', cipher_text.upper())
            all_plain = ceasor(cipher_text)
            scores = []
            for i in range(26):
                scores.append((fitness.score(Caesar(i).decipher(cipher_text)), i))
            key = max(scores)
            filtered_plain = Caesar(key[1]).decipher(cipher_text)
            k=0
            al_p = []
            for i in all_plain:
                for j in i:
                    al_p.append(j)
                al_p.append("\n")
            all_plain = list(all_plain)
            return render(request, 'dwok/ceasor.html', {'form': form,'plain':filtered_plain,'all_plain':all_plain})
            # return HttpResponse(Caesar(key[1]).decipher(cipher_text) + (str)("\n" + all_plain))
        else:
            return HttpResponse("Form is not valid")
    else:
        form = CryptoAnalysis()
    return render(request, 'dwok/ceasor.html', {'form': form})
예제 #2
0
def break_caesar(ctext):
    """
    This function will break the Caesar Cipher with english frequence detect,
    therefore, this will not do well on short cipher QwQ.
    """
    from ngram_score import ngram_score
    fitness = ngram_score('./English_Frequency/quadgram.pickle') # load our quadgram statistics
    # make sure ciphertext has all spacing/punc removed and is uppercase
    ctext = re.sub('[^A-Z]','',ctext.upper())
    # try all possible keys, return the one with the highest fitness
    scores = []
    for i in range(26):
        scores.append((fitness.score(Caesar(i).decipher(ctext)),i))
    print('best candidate with key (a,b) = {}:'.format(str(max_key[1])))
    print(Caesar(max_key[1]).decipher(ctext))
    return max(scores)
예제 #3
0
def main():
    # example ciphertext
    ctext = input("enter cipher text")
    max_key = break_caesar(ctext)

    print('best candidate with key (a,b) = ' + str(max_key[1]) + ':')
    print(Caesar(max_key[1]).decipher(ctext))
예제 #4
0
def cryptanalysis(ctext):
    # Cleaned Text
    ctext = re.sub('[^A-Z]','',ctext.upper())
    scores = []
    for i in range(26):
        scores.append((fitness.score(Caesar(i).decipher(ctext)),i))
    return max(scores)
예제 #5
0
def CaesarCracker(maxkey, ctext):

    for i in range(0, maxkey):
 
        print('\033[1;34m[*]\033[0m Key = ' + str(i) + ' ; Out = ' + Caesar(i).decipher(ctext))
        
    print('\033[1;32m[+]\033[0m Brute Force finished')
예제 #6
0
    def decrypt(self, cipher):
        for c_key in range(1, 26, 1):
            c_decrypt = Caesar(c_key).decipher(cipher, True)
            self._decryptions.append((c_key, c_decrypt))
            print("%s: %s" % (c_key, c_decrypt))
            self.logger.info("%s: %s" % (c_key, c_decrypt))

        pass
예제 #7
0
def break_caesar(ctext):
    # make sure ciphertext has all spacing/punc removed and is uppercase
    ctext = re.sub('[^A-Z]', '', ctext.upper())
    # try all possible keys, return the one with the highest fitness
    scores = []
    for i in range(26):
        scores.append((fitness.score(Caesar(i).decipher(ctext)), i))
    return max(scores)
예제 #8
0
def break_caesar(ctext, scorer):
    original_ctext = ctext
    ctext = re.sub('[^A-Z]','',ctext.upper())
    # try all possible keys, return the one with the highest fitness
    scores = []
    for i in range(26):
        ptext = Caesar(i).decipher(ctext)
        scores.append((replaceLetters(ptext, original_ctext), scorer(ptext),str(i)))
    return sorted(scores, key = lambda x : x[1], reverse = True)
예제 #9
0
def brute(ctext):
    """
    Show all possible 26 character decipher.
    """
    # make sure ciphertext has all spacing/punc removed and is uppercase
    ctext = re.sub('[^A-Z]','',ctext.upper())
    ptxt = []
    for i in range(26):
        ptxt.append(Caesar(i).decipher(ctext))
        print('{i:02} : {}'.format(i,ptxt[i]))
    return ptxt
예제 #10
0
def Decrypt_Ceasar():

    inputMessage = output.get("1.0", END)
    Key = inputKeyBox.get()
    finalMessage = ""
    output_2.delete('1.0', END)
    try:
        finalMessage = Caesar(key=int(Key)).decipher(inputMessage)
    except ValueError:
        messagebox.showinfo('Enter an integer',
                            'In ceasar cipher you must enter an integer')

    output_2.insert(END, finalMessage)  #replace inputMessage with final result
    print("Done")
예제 #11
0
def decipher_caesar(cipher):
    lowestDelta = 1000 # A ridiculously large initial delta in order to ensure a new lowest delta
    bestRotation = 0
    letterFrequencies = letter_frequency(cipher)

    for shift in range(26):
        currentDelta = frequency_delta(letterFrequencies[shift:] + letterFrequencies[:shift], ENGLISH)

        if currentDelta < lowestDelta:
            lowestDelta = currentDelta
            bestRotation = shift

    return {
        'rotation': bestRotation,
        'plain_text': Caesar(bestRotation).decipher(cipher)
    }
예제 #12
0
def decipher_caesar(cipher):
    lowestDelta = 1000
    bestRotation = 0
    letterFrequencies = letter_frequency(cipher)

    for shift in range(26):
        currentDelta = frequency_delta(
            letterFrequencies[shift:] + letterFrequencies[:shift], ENGLISH)

        if currentDelta < lowestDelta:
            lowestDelta = currentDelta
            bestRotation = shift

    return {
        'rotation': bestRotation,
        'plain_text': Caesar(bestRotation).decipher(cipher)
    }
예제 #13
0
def break_caesar_example(plaintext, masker):
    print("#######################################")
    print("######## Caesar cipher example ########")
    print("#######################################")

    key = 13
    ciphertext = Caesar(key).encipher(plaintext)

    print("\nCiphertext:\n---")
    print(masker.extend(ciphertext))
    print("---\n")

    print("\nCracking...\n")
    scorer = NgramScorer(load_ngrams(3))
    breaker = CaesarBreak(scorer)
    decryption, score, key = breaker.guess(ciphertext, 1)[0]
    print("Caesar decryption (key={}, score={}):\n---\n{}---\n".format(
        key, score, masker.extend(decryption)))
예제 #14
0
def caesar_Salad(ciphertext):
    caesar_shift = {}
    for x in range(1, 26):
        caesar_shift[x] = Caesar(x).decipher(ciphertext)
    return caesar_shift
예제 #15
0
        scores.append((fitness.score(Caesar(i).decipher(ctext)), i))
    return max(scores)


# ciphertext
ctext = ""
if (len(sys.argv) >= 2):
    with open(sys.argv[1], "r") as f:
        ctext = str(f.read())
    print("Cipher text: " + ctext)
else:
    print("Usage: " + sys.argv[0] + " filename")
max_key = break_caesar(ctext)

print('best candidate with key (a,b) = ' + str(max_key[1]) + ':')
plaintext = Caesar(max_key[1]).decipher(ctext)
print(plaintext)

print("Cipher spacing and such reconstructed into plaintext:")
restoredplain = ""
pi = 0
for c in ctext:
    if c.isalpha(
    ):  #alphabetic, ie. this character is in the filtered plaintext
        if c.isupper():
            restoredplain = restoredplain + plaintext[pi]
        else:
            restoredplain = restoredplain + plaintext[pi].lower()
        pi = pi + 1
    else:  #some other character
        restoredplain = restoredplain + c
예제 #16
0
def caesar(str):
    n = int(input("Enter the key"))
    print("Your encrypted message is:")
    print(Caesar(key=n).encipher(str))
예제 #17
0
# using pycipher to decrypt

#install pycipher

from pycipher import Caesar

ctf = Caesar(key=19).decipher('VMY{vtxltkvbiaxkbltlnulmbmnmbhgvbiaxk}')

print(ctf.lower())

#ctfcaesarcipherisasubstitutioncipher
예제 #18
0
print(string[::-1])

#exercise 4: Leetspeak

l337 = {"A": "4", "E": "3", "G": "6", "I": "1", "O": "0", "S": "5", "T": "7"}

lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam semper purus nec semper suscipit. Ut cursus cursus nisl vel tincidunt. Maecenas cursus placerat purus ac ultrices. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam eget viverra mi. Fusce sodales vel ex eget ullamcorper. Maecenas eget sem ex. Mauris ullamcorper, tortor ornare hendrerit feugiat, enim enim auctor velit, eget gravida lacus nisl vitae quam. Nulla quam diam, maximus interdum tortor et, ornare laoreet mi. Donec ullamcorper, arcu non tempus dignissim, mi enim luctus ipsum, quis tincidunt tortor ante id nunc. Maecenas vehicula ligula ullamcorper, cursus felis sed, imperdiet magna. Vestibulum pulvinar nulla ut neque molestie sodales. Quisque nibh felis, congue et nisl sit amet, varius mollis arcu."

lorem = lorem.upper()

for key, value in l337.items():
    lorem = lorem.replace(key, value)

#exercise 5: long-long vowels

vowels = {'ee': 'eeeee', 'oo': 'ooooo'}

words = "good cheese stuff"

for key, value in vowels.items():
    words = words.replace(key, value)

#exercise 6: Caesar C
from pycipher import Caesar

code = Caesar(key=13).encipher('you must unlearn what you have learned')
uncode = Caesar(key=13).decipher(code)
#############

# use ord() and chr()
예제 #19
0
)
"""Selecting cipher."""

encryption_type = input(
    "Select Encryption/Decryption:\n-->E - Encryption \n-->D - Decryption\n")
"""Selecting encryption/decryption."""

message = input("Enter Message:\n")
"""Message to encrypt/decrypt."""

from pycipher import Caesar, Playfair

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)
예제 #20
0
        my_leetspeak.append("3")
    elif char == "G":
        my_leetspeak.append("6")
    elif char == "I":
        my_leetspeak.append("1")
    elif char == "O":
        my_leetspeak.append("0")
    elif char == "S":
        my_leetspeak.append("5")
    elif char == "T":
        my_leetspeak.append("7")
    else:
        my_leetspeak.append(char)

print(''.join(str(letter) for letter in my_leetspeak))

# 5. Long-long Vowels
my_long_vowels_list = []
for letter in my_string:
    if letter.lower() in ("a", "e", "i", "o", "u"):
        my_long_vowels_list.append(letter * 5)
    else:
        my_long_vowels_list.append(letter)

print(''.join(str(letter) for letter in my_long_vowels_list))

# 6. Caesar Cipher
from pycipher import Caesar
code = "lbh zhfg hayrnea jung lbh unir yrnearq"
print(Caesar(key=13).decipher(code))
예제 #21
0
   date:          2019/8/30
-------------------------------------------------
   Change Activity:
                   2019/8/30:
-------------------------------------------------
"""
"""
Decrypt the following text 
Aipgsqi fego, xlmw pizip mw rsx ew iewc ew xli pewx fyx wxmpp rsx xss gleppirkmrk. Ws ks elieh erh irxiv xlmw teww: wlmjxxlexpixxiv
"""
from pycipher import Caesar

str = "Aipgsqi fego, xlmw pizip mw rsx ew iewc ew xli pewx fyx wxmpp rsx xss gleppirkmrk. Ws ks elieh erh irxiv xlmw teww: wlmjxxlexpixxiv"

for i in range(1, 26):
    c = Caesar(key=i)
    print(c.decipher(str, keep_punct=True))

# letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
# for key in range(len(letters)):
# 	translated = ''
# 	translated = translated.upper()
# 	for symbol in str:
# 		if symbol in letters:
# 			num = letters.find(symbol)
# 			num -= key
# 			translated += letters[num]
# 		else:
# 			translated += symbol
# 	print("key #%s : %s" % (key, translated))
"""
예제 #22
0
        print("1", end='')
    elif string4[x] == "O":
        print("0", end='')
    elif string4[x] == "S":
        print("5", end='')
    elif string4[x] == "T":
        print("7", end='')
    else:
        print(string4[x], end='')
print(" ")

#Exercise 5. Long-long vowels
string5 = input("Let's elongate our vowels.  ")
for x in range(len(string5)):
    if x + 1 == len(string5):
        print(string5[x])
    elif string5[x] + string5[x + 1] == "aa" or string5[x] + string5[
            x + 1] == "ee" or string5[x] + string5[x + 1] == "oo":
        print((string5[x] + string5[x + 1]) * 2 + string5[x], end='')
    else:
        print(string5[x], end='')

#Exercise 6. Caesar Cipher
#To decrypt your message, the key must be 13. Message reads: "you must unlearn what you have learned"
from pycipher import Caesar
codeMessage = input("Enter your commands and I'll encrypt them.  ")
oneUseKey = int(input("Enter a number to use as the key: "))
print(Caesar(key=oneUseKey).encipher(codeMessage))
decodeMessage = input("I can decrypt any replies you receive:  ")
print(Caesar(key=oneUseKey).decipher(decodeMessage))
예제 #23
0
        self.floor = log10(0.01 / self.N)

    def score(self, text):
        """ compute the score of text """
        score = 0
        ngrams = self.ngrams.__getitem__
        for i in xrange(len(text) - self.L + 1):
            if text[i:i + self.L] in self.ngrams:
                score += ngrams(text[i:i + self.L])
            else:
                score += self.floor
        return score


fitness = ngram_score('quadgrams.txt')


def break_caesar(ctext):
    ctext = re.sub('[^A-Z]', '', ctext.upper())
    scores = []
    for i in range(26):
        scores.append((fitness.score(Caesar(i).decipher(ctext)), i))
    return max(scores)


ctext = 'YMJHFJXFWHNUMJWNXTSJTKYMJJFWQNJXYPSTBSFSIXNRUQJXYHNUMJWX'
max_key = break_caesar(ctext)

print('best candidate with key (a,b) = ' + str(max_key[1]) + ':')
print(Caesar(max_key[1]).decipher(ctext))
예제 #24
0
from pycipher import Caesar
for i in range(1,128):
	str_result = Caesar(key=i).decipher('gmbh{4d850d5c3c2756f67b91cbe8f046eebd}')
	print (" [" + str(i) + "] " + str_result + '\n')
input()
예제 #25
0
def break_caesar(ctext):
    ctext = re.sub('[^A-Z]', '', ctext.upper())
    scores = []
    for i in range(26):
        scores.append((fitness.score(Caesar(i).decipher(ctext)), i))
    return max(scores)
예제 #26
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
예제 #27
0
def caesar_decode(string, key):
    plaintext = Caesar(int(key)).decipher(string, keep_punct=True)
    return plaintext
예제 #28
0
    def score(self,text):
        #Computing score of a text
        score = 0
        ngrams = self.ngrams.__getitem__
        for i in xrange(len(text)-self.L+1):
            if text[i:i+self.L] in self.ngrams: score += ngrams(text[i:i+self.L])
            else: score += self.floor          
        return score
       

fitness = ngram_score('quadgrams.txt')
      
def cryptanalysis(ctext):
    # Cleaned Text
    ctext = re.sub('[^A-Z]','',ctext.upper())
    scores = []
    for i in range(26):
        scores.append((fitness.score(Caesar(i).decipher(ctext)),i))
    return max(scores)

print "Enter text and key:"    
input_text = raw_input()
key_val = input()
ctext = Caesar(key=key_val).encipher(input_text)#'YMJHFJXFWHNUMJWNXTSJTKYMJJFWQNJXYPSTBSFSIXNRUQJXYHNUMJWX'
print "Ciphered Text:"+ctext
max_key = cryptanalysis(ctext)

print 'Solution: '+str(max_key[1])
print Caesar(max_key[1]).decipher(ctext)
def to_encrypt(text, delta):
    return Caesar(key=delta).encipher(text).lower()
예제 #30
0
 def decipher(self, text, key):
     return Caesar(key).decipher(text)