예제 #1
0
def run_genetic_algorithm(key_length,
                          cipher_text,
                          number_of_generations=100,
                          mutation_rate=0.2):
    """
        initialize by generating random keys with given key length
        sort the random keys
        start the generations (iterations) until the top suited key is returned:
            - apply crossover, mutation, sort top keys
        finally return decrypted text using that top 1 sorted key with highest fitness score
    """
    global ct
    ct = cipher_text
    some_keywords_list = []
    lst = generate_random_keys(number_of_keys=7000, key_length=key_length)
    sorted_keywords = top_suitable_keywords(
        number_of_items=600,
        keywords_with_fitness_scores=keywords_and_suitability_score(
            lst, cipher_text))
    for m in range(number_of_generations):
        keywords_pairs = pair_keywords(sorted_keywords)
        keywords_pairs = crossover_and_certain_percent_mutation(
            keywords_pairs, mutation_percent=mutation_rate)
        lst = keywords_pairs.flatten()
        sorted_keywords = top_suitable_keywords(
            number_of_items=30,
            keywords_with_fitness_scores=keywords_and_suitability_score(
                lst, cipher_text))
        if m % 5 == 0:
            some_keywords_list.append(sorted_keywords)
        #print(sorted_keywords)
    return [
        decrypt(cipher_text, keyword=sorted_keywords[0]), some_keywords_list
    ]
예제 #2
0
    def get_content_from_bitplanes(self):
        content = self.get_byte_from_bitplane_array(self.content_bitplane)
        self.content = content[:self.content_length]

        if (self.encrypted and self.key != None):
            self.content = vigenere_cipher.decrypt(self.content, self.key)

        # print (self.content)
        return self.content
def analyze_encrypted_text(text):
    print(f"Used IOC {global_ioc}")
    proposed = ""
    key_len = get_key_len(text)
    print(f"[1/3] ### Key length: {key_len}")
    key = get_key(text, key_len)
    print(f"[2/3] ### Key: {key}")
    proposed = decrypt(key, text)
    print(f"[3/3] ### Finished!")
    return proposed
def keywords_and_suitability_score(keywords, cipher_text):
    """
        get fitness scores of each keyword
        return two lists with keywords and fitness_scores respectively
        this is for successfully getting top suitable keywords from following mentioned function!
    """
    key_fitness_scores = []
    for i in keywords:
        key_fitness_scores.append(fitness_score(decrypt(ciphertext=cipher_text, keyword=i).upper())) 
    return [keywords, key_fitness_scores]
예제 #5
0
    def helper_submission(self,text=None,key=None,option=None):
        import caesar_cipher as CAESAR
        import vigenere_cipher as VIGENERE
        ctext = ""
        if option=="CAESAR ENCRYPTION":
            ctext = CAESAR.encrypt(text,int(key)) #display
        elif option=="CAESAR DECRYPTION":
            ctext = CAESAR.decrypt(text,int(key))
        elif option=="VIGENERE ENCRYPTION":
            ctext = VIGENERE.encrypt(text,key)
        elif option=="VIGENERE DECRYPTION":
            ctext = VIGENERE.decrypt(text,key)
        elif option=="BREAK CAESAR":
            key = CAESAR.breakCaesar(text)
            ctext = CAESAR.decrypt(text,key)
            self.submit_key(key)
        else:
            key = VIGENERE.breakVigenere(text)
            ctext = VIGENERE.decrypt(text,key)
            self.submit_key(key)

        self.submit_text(ctext)
def get_key(ct, key_len):

    key = ['_'] * key_len
    split_text = np.array(get_seq(ct, key_len))
    for i, seq in enumerate(split_text):
        st = float('inf')
        for letter in abc:
            ch2 = chisquare(get_hist(decrypt(letter, seq)),
                            list(UKRAINIAN_LETTER_FREQUENCES.values()))[0]
            if ch2 < st:
                st = ch2
                key[i] = letter

    return ''.join(key)
예제 #7
0
def bruteVigKey(etxt):
    f = open('dictionary.txt')
    wrds = f.readlines()
    f.close()
    for i in wrds:
        wrd = i.strip()
        ptext = vigenere_cipher.decrypt(wrd, etxt)
        if detectEnglish.isEnglish(ptext, wordPercentage=40):
            print(f"\nPossible decrypted text: {ptext}")
            willcontinue = input("Enter T to terminate brute attack or just press Enter to continue: ")
            if 'T' in willcontinue.upper():
                return ptext
            else:
                pass
def vigenere():
    '''
        Approach: same as that of Caesar cipher listed above.
    '''
    if request.method == 'POST':
        plain_text = request.form['plain_text']
        cipher_text = request.form['cipher_text']
        function = str(request.form.get('choices'))
        keyword = str(request.form["keyword"])
        if function == "Encrypt":
            return render_template('vigenere.html', data=[plain_text, vigenere_cipher.encrypt(plain_text, keyword)])
        if function == "Decrypt":
            return render_template('vigenere.html', data=[vigenere_cipher.decrypt(cipher_text, keyword), cipher_text])
        if str(function) == "Crack":
            return render_template('genetic_algo.html', data=[cipher_text])
    return render_template("vigenere.html", data=["Plain Text", "Cipher Text"])
예제 #9
0
def analyze_encrypted_text(text):
    text = text.lower()
    text = [l for l in text if l in ntoa]

    key_length = analyze_key_length(text)
    # print("Key length: {}".format(key_length))

    key = [0 for i in range(key_length)]
    for i in range(key_length):
        chunk = text[i::key_length]
        chsq = [INF for j in range(ALPH_LEN)]
        for shift in range(ALPH_LEN):
            chsq[shift] = chi_squared(chunk, shift)
        key[i] = ntoa[chsq.index(min(chsq))]
    # print("Key: {}".format("".join(key)))
    proposed = vc.decrypt(text, ''.join(key))
    return proposed
def hack(message):
    fo = open('dict.txt')
    words = fo.readlines()
    fo.close()
    for word in words:
        word = word.strip()
        decrypted = vigenere_cipher.decrypt(message, word)
        if detectEnglish.isEnglish(decrypted, wordPercentage=40.0):
            print()
            print('Possible encryption break:')
            print('Key ' + str(word) + ':' + decrypted[:100])
            print()
            print('Enter D for done, or just press Enter to continue breaking:')
            response = input('> ')
            if response.lower().startswith('d'):
                return decrypted
    return None
예제 #11
0
def vignere():
    '''
    :input:
        {
            'process_type': 'encryption'\'decryption',
            'key': <string>,
            'text': <raw/encrypted message>
        }
    :return:
        {
            'status': 'success'/'failure',
            'msg': NA/<error message>,
            'text': NA/<encrypted/decrypted message>
    '''
    try:
        req_body = request.get_json()
        process_type = req_body.get('process_type')
        if process_type == 'encryption':
            cipher = vigenere_cipher.encrypt(req_body.get('text'), req_body.get('key'))
            return {
                'status': 'success',
                'text': cipher
            }
        elif process_type == 'decryption':
            cipher = vigenere_cipher.decrypt(req_body.get('text'), req_body.get('key'))
            return {
                'status': 'success',
                'text': cipher
            }
        else:
            return {
                'status': 'failure',
                'msg': 'invalid process type! Process type can only be encryption or decryption for Vigenere cipher.'
            }
    except Exception as e:
        return {
            'status': 'failure',
            'msg': f'Process failed! Reason: {e}'
        }
예제 #12
0
    def get_header_from_bitplanes(self):
        self.header = self.get_byte_from_bitplane_array(self.header_bitplane)

        if (self.encrypted and self.key != None):
            self.header = vigenere_cipher.decrypt(self.header, self.key)

        self.header = self.header.decode('utf-8', errors="ignore")

        header_chunk = self.header.split(';')
        #print(header_chunk)
        self.conjugate_list = []
        # if header_chunk[0] != '':
        # 	for conjugate_pos in header_chunk[0].split(','):
        # 		self.conjugate_list.append(int(conjugate_pos))

        self.file_name = header_chunk[0]
        self.file_extension = header_chunk[1]
        self.content_length = int(header_chunk[2])
        # print(self.conjugate_list)
        # print(self.content_length)
        # print(self.file_extension)
        # print(self.file_name)

        return self.header
예제 #13
0
'''
CAESAR CIPHER TESTS
'''
print("***CAESAR ENCRYPTION***")
print(CAESAR.encrypt("a",26*1222)=="a")
print(CAESAR.encrypt("a",27)=="b")
print(CAESAR.encrypt("a",25)=="z")
print(CAESAR.encrypt("z",25)=="y")
print(CAESAR.encrypt("z",27)=="a")
print(CAESAR.encrypt("a",26*26)=="a")
print(CAESAR.encrypt("a",27*27)=="b")
print(CAESAR.encrypt("a",25)=="z")
print(CAESAR.encrypt("a",625)=="b")
print(CAESAR.encrypt("z",27*3)=="c")
print("\n***CAESAR DECRYPTION***")
print(CAESAR.decrypt("a",26*1222)=="a")
print(CAESAR.decrypt("b",27)=="a")
print(CAESAR.decrypt("z",25)=="a")
print(CAESAR.decrypt("y",25)=="z")
print(CAESAR.decrypt("a",27)=="z")
print(CAESAR.decrypt("a",26*26)=="a")
print(CAESAR.decrypt("b",27*27)=="a")
print(CAESAR.decrypt("z",25)=="a")
print(CAESAR.decrypt("b",625)=="a")
print(CAESAR.decrypt("c",27*3)=="z")
print("\n***VIGENERE DECRYPTION***")
print(VIGENERE.decrypt("DM FR QS XU CF DM MZSY M BRUHK MFSY XU CF DM FR QS XU JRMDZ ZY SXF UFQ XIEL DM FR QS XU CF DM MDZJR UCTFS QZYZ YY CF DM FR QS XU CF KUGGQW MM TFF NY EJPF NZRW KILWW RYVQAZA SQMQ DLXL XYK F KYCCJ TQAZS ZMJGD LTCELK ICCQ UAGV YG KIL XG EGLWX KILWKQFW F YDCE TGAIFT A TUKJ KYOIKK UFC LWF SFZ AXF XJL MFC TX KIL NX UNJ YZQ FRXL FBZSY U YMJJ PI YJZQBVMW XU CF DM FR QS XU ETO KIL PFAQ KMW FOEJ QAOCQ TQ MDZJRCEL KAIE","smurf")
=="la la la la la la sing a happy song la la la la la la smurf it all day long la la la la la la smurf along with me la la la la la la simple as can be next time youre feeling blue just let a smile begin happy things will come to you so smurf yourself a grin oooooo i hate smurfs ill get you ill get all of you if its the last thing i ever do hehehehe la la la la la la now you know the tune youll be smurfing soon")
print("\n***VIGENERE BREAK***")
print(VIGENERE.breakVigenere("DM FR QS XU CF DM MZSY M BRUHK MFSY XU CF DM FR QS XU JRMDZ ZY SXF UFQ XIEL DM FR QS XU CF DM MDZJR UCTFS QZYZ YY CF DM FR QS XU CF KUGGQW MM TFF NY EJPF NZRW KILWW RYVQAZA SQMQ DLXL XYK F KYCCJ TQAZS ZMJGD LTCELK ICCQ UAGV YG KIL XG EGLWX KILWKQFW F YDCE TGAIFT A TUKJ KYOIKK UFC LWF SFZ AXF XJL MFC TX KIL NX UNJ YZQ FRXL FBZSY U YMJJ PI YJZQBVMW XU CF DM FR QS XU ETO KIL PFAQ KMW FOEJ QAOCQ TQ MDZJRCEL KAIE")=="smurf")
예제 #14
0
 def test_decrypt_lowercase(self):
     decrypted_text = decrypt('jthklopibv', 'iitibm')
     self.assertEqual(decrypted_text, 'BLOCKCHAIN')
예제 #15
0
 def test_decrypt(self):
     decrypted_text = decrypt('JTHKLOPIBV', 'IITIBM')
     self.assertEqual(decrypted_text, 'BLOCKCHAIN')
예제 #16
0
def decrypt_with_suitable_keywords(CText):
    mylist = []
    for i in kList:
        mylist.append(decrypt(CText, i))
    data3 = dict(zip(kList, mylist))
    return data3