Пример #1
0
class TestDecrypt(unittest.TestCase):
    
    def setUp(self):
        self.encrypt_instance = Encrypt()
        self.decrypt_instance = Decrypt()

    def test_can_load_private_key(self):
        private_key = self.decrypt_instance.load_privatekey_from_file()
        self.assertTrue(private_key)

    def test_can_decrypt_single_value(self):
        self.encrypt_instance.load_publickey_from_file()
        self.decrypt_instance.load_privatekey_from_file()

        card_number = "5001222244446666"
        encrypted_card_number = self.encrypt_instance.encrypt_value(card_number)
        decrypted_card_number = self.decrypt_instance.decrypt_value(
            encrypted_card_number)
        self.assertEqual(card_number, decrypted_card_number)

    def test_can_apply_full_decrypt(self):
        number = "5001222244446666"
        holder = "Teste Ferreira da Silva"
        cvv = "988"
        encrypted_card_data = encrypt_card_data(holder, number, cvv)

        enc_holder = encrypted_card_data['holder']
        enc_number = encrypted_card_data['number']
        enc_cvv = encrypted_card_data['cvv']

        decrypted_card_data = decrypt_card_data(enc_holder, enc_number, enc_cvv)
        self.assertEqual(number, decrypted_card_data['number'])
        self.assertEqual(holder, decrypted_card_data['holder'])
        self.assertEqual(cvv, decrypted_card_data['cvv'])
Пример #2
0
def DecipherCommonDivisor(first_ciphertext, first_modulo, first_exponent,
                          second_ciphertext, second_modulo, second_exponent):
    common_prime = GCD(first_modulo, second_modulo)
    q1 = first_modulo // common_prime
    q2 = second_modulo // common_prime
    return (Decrypt(first_ciphertext, common_prime, q1, first_exponent),
            Decrypt(second_ciphertext, common_prime, q2, second_exponent))
 def cloud_main(self, file_count):
     with open('encrypted_vectors/feature_vectors.json') as data_file:
         feature_loaded = json.load(data_file)
     with open('encrypted_indices/indices.json') as data_file:
         indices_loaded = json.load(data_file)
     with open('encrypted_query/query_vectors.json') as data_file:
         query_loaded = json.load(data_file)
     d = Decrypt()
     feature_vectors = d.decrypt_indices_vector(bytes(feature_loaded))
     indices = d.decrypt_indices_vector(bytes(indices_loaded))
     query_vectors = d.decrypt_indices_vector(bytes(query_loaded))
     feature_vectors = np.frombuffer(feature_vectors, dtype=int)
     feature_vectors = np.reshape(feature_vectors, (file_count, -1))
     indices = json.loads(indices.decode())
     query_vectors = np.frombuffer(query_vectors, dtype=int)
     query_vectors = np.reshape(query_vectors, (-1, 6))
     print(feature_vectors.shape, indices, query_vectors.shape)
     l = LSH(feature_vectors, indices)
     n_neighbors, result = l.query(query_vectors, 6, 45)
     print(n_neighbors)
     cursor.execute(sql_select_Query)
     records = cursor.fetchall()
     for row in records:
         if row[0] - 1 in result:
             image_name = row[1]
             print(image_name)
             CloudAPISender().cloud_api_sender(image_name)
     # Closing the connection
     conn.close()
Пример #4
0
    def __init__(self, _outputFile: PathModel, _tempFolder: PathModel = None) -> None:
        if _tempFolder is None:
            _tempFolder = _outputFile.temp()
        os.chdir(_tempFolder.path)

        try:
            progress = int(re.findall("file tmp_(.*).mp4",
                                      open('temp.txt', 'r').readlines()[-3])[0])+1
        except:
            progress = 0

        key, M3U8s = M3U8.getAll(self)

        dec = Decrypt(key)

        l = len(M3U8s)
        id = Id(l, progress)

        try:
            for i in range(progress, l):
                file_name = 'tmp_%s.mp4' % id.add()
                print('Processing %d of %d' % (i+1, l))

                url = M3U8s[i].url
                url = "http" + url.removeprefix("https")

                open(file_name, 'wb').write(
                    dec.get(self.getFile(url)))

                open('temp.txt', 'a').write(
                    "file %s\nduration %s\n\n" % (file_name, M3U8s[i].duration))

        except:
            print("Errore nel download dei file\nRiprova in seguito")

        else:
            #            size = 0
            #            st = os.stat_result.
            #            free = st.f_bavail * st.f_frsize
            #            for file_name in os.listdir(tempPath):
            #                size += os.path.getsize(file_name)
            #
            #            if free >= size:
            self._concatenateAll()
#            else:
#                self._concatenateProgress(l)

            os.chdir(_tempFolder.dir)

            shutil.move("%s\\output.mp4" % _tempFolder.name, _outputFile.path)
            shutil.rmtree(_tempFolder.path)
Пример #5
0
	def __checkKey(self):
		keyValue = hashlib.sha512(self.__keyAccept.get().encode())
		
		with open(".key.txt", 'r') as file:
			key = file.read()

		if keyValue.hexdigest() == key:
			sys.path.insert(1, os.path.join(ROOT_DIR, "Decryptor/"))

			from decrypt import Decrypt
			decryptData = Decrypt(self.__keyAccept.get())
			decryptData.decrypt()
			
			self.root.destroy()
Пример #6
0
def DecipherSmallPrime(ciphertext, modulo, exponent):
    for p in range(2, 1000000):
        if modulo % p == 0:
            q = modulo // p
            return Decrypt(ciphertext, p, q, exponent)

    return "don't know"
Пример #7
0
def upload_file():
    session['filename'] = ""
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files :
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit a empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            PATH = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            file.save(PATH)
            session['filename'] = filename
            text = ""
            with open(Decrypt(PATH).NAME, "r") as f:
                text = f.read()
            print(text)
            return render_template("decrypt.html", text=text)
    else:
        session['filename'] = ""
    return render_template("decrypt.html")
Пример #8
0
def DecipherSmallDiff(ciphertext, modulo, exponent):
    for i in range(1, 1000):
        if is_exact_square(modulo + i**2):
            x = IntSqrt(modulo + i**2)
            big_prime = x + i
            small_prime = x - i
            return Decrypt(ciphertext, small_prime, big_prime, exponent)

    return "don't know"
Пример #9
0
 def run(self):
     try:
         Decrypt(self.stat, self.file, self.top, self.variants)
     except:
         traceback.print_exc()
         exctype, value = sys.exc_info()[:2]
         self.signals.error.emit((exctype, value, traceback.format_exc()))
     else:
         self.signals.result.emit(None)
     finally:
         self.signals.finished.emit()
Пример #10
0
 def cloud_main(self, file_count):
     #establishing the connection
     conn = mysql.connector.connect(user='******',
                                    password='******',
                                    host='127.0.0.1',
                                    database='ImageRetrieval')
     #Creating a cursor object using the cursor() method
     cursor = conn.cursor()
     # Preparing SQL query to select a record from the database.
     sql_select_Query = "select * from images"
     with open('encrypted_vectors/feature_vectors.json') as data_file:
         feature_loaded = json.load(data_file)
     with open('encrypted_indices/indices.json') as data_file:
         indices_loaded = json.load(data_file)
     with open('encrypted_query/query_vectors.json') as data_file:
         query_loaded = json.load(data_file)
     d = Decrypt()
     feature_vectors = d.decrypt_indices_vector(bytes(feature_loaded))
     indices = d.decrypt_indices_vector(bytes(indices_loaded))
     query_vectors = d.decrypt_indices_vector(bytes(query_loaded))
     feature_vectors = np.frombuffer(feature_vectors, dtype=int)
     feature_vectors = np.reshape(feature_vectors, (file_count, -1))
     indices = json.loads(indices.decode())
     query_vectors = np.frombuffer(query_vectors, dtype=int)
     query_vectors = np.reshape(query_vectors, (-1, 6))
     print(feature_vectors.shape, indices, query_vectors.shape)
     l = LSH(feature_vectors, indices)
     n_neighbors, result = l.query(query_vectors, 6, 45)
     print(n_neighbors)
     cursor.execute(sql_select_Query)
     records = cursor.fetchall()
     for row in records:
         if row[0] - 1 in result:
             image_name = row[1]
             print(image_name)
             CloudAPISender().cloud_api_sender(image_name)
     # Closing the connection
     conn.close()
Пример #11
0
    def arguments(self):
        cipher_parse = argparse.ArgumentParser(
            description='Encrypt and Decrypt words', add_help=True)
        cipher_parse.add_argument('-w',
                                  '--word',
                                  dest='word',
                                  action='store',
                                  help='word to encrypt',
                                  required=True)
        cipher_parse.add_argument('-k',
                                  '--key',
                                  dest='key',
                                  action='store',
                                  help='key',
                                  default='marketing')
        group = cipher_parse.add_mutually_exclusive_group(required=True)
        group.add_argument('-e',
                           '--encrypt',
                           dest='type',
                           action='store_true',
                           help='-e to encrypt')
        group.add_argument('-d',
                           '--decrypt',
                           dest='type',
                           action='store_false',
                           help='-d to decrypt')

        args = cipher_parse.parse_args()
        word = str(args.word).lower()
        key = str(args.key).lower()
        # true, Encrypt
        # False, Decrypt

        enter_type = args.type

        if enter_type:
            text_intro = "         +-+-+-+-+-+ +-+-+-+-+-++-+-+-+-+-++-+-+-+-+-+ \n" \
                         + "         |E|n|c|r|y|p|t| |W|o|r|d| |by| |B|4|r|t|\n" \
                         + "        +-+-+-+-+-+ +-+-+-+-+-++-+-+-+-+-++-+-+-+-+-+\n"
            subprocess.run(['echo', text_intro])
            subprocess.run(['echo', 'Processing... \n'])

            dict_splited_word = self.split_and_count(word)
            final_key = self.generate_key_from_password(
                dict_splited_word['without_spaces'], key)

            final_key_1 = self.rearming_text({
                'without_spaces':
                final_key,
                'list_from_spaces':
                dict_splited_word['list_from_spaces']
            })
            encrypted_text = self.generate_encrypted_word(
                dict_splited_word['without_spaces'], final_key)

            encrypted_text_1 = self.rearming_text({
                'without_spaces':
                encrypted_text,
                'list_from_spaces':
                dict_splited_word['list_from_spaces']
            })

            subprocess.run(['echo', "\n Original Text : " + word.upper()])
            subprocess.run(['echo', "\n Original Key : " + key.upper()])
            subprocess.run(
                ['echo', "\n Original Generated Key : " + final_key_1.upper()])
            subprocess.run(
                ['echo', "\n Encrypted Word : " + encrypted_text_1.upper()])

        else:
            text_intro = "         +-+-+-+-+-+ +-+-+-+-+-++-+-+-+-+-++-+-+-+-+-+ \n" \
                         + "         |D|e|c|r|y|p|t| |W|o|r|d| |by| |B|4|r|t|\n" \
                         + "        +-+-+-+-+-+ +-+-+-+-+-++-+-+-+-+-++-+-+-+-+-+\n"
            subprocess.run(['echo', text_intro])
            subprocess.run(['echo', 'Processing... \n'])
            subprocess.run(['echo', 'Decrypt....! \n'])
            decrypt = Decrypt()
            decrypted_word = decrypt.recursive_decrypt(
                message=word, key_pwd=key)['decrypted_word']
            decrypted_list = decrypt.recursive_decrypt(
                message=word, key_pwd=key)['decrypted_list']
            key_pwd_list = decrypt.recursive_decrypt(
                message=word, key_pwd=key)['key_pwd_list']

            subprocess.run(['echo', "\n Encrypted Text : " + word.upper()])
            subprocess.run(['echo', "\n Key : " + key.upper()])
            subprocess.run(
                ['echo', "\n Decrypted Text : " + decrypted_word.upper()])
Пример #12
0
    if answers['test_type'] == 'Test a':

        string = input("Enter your message: ")
        start = timeit.default_timer()

        encrypted_surname = Encrypt.encrypt_a(surname=string)

        end = timeit.default_timer()

        print("Encrypted message: ", encrypted_surname)
        print("---  seconds for encrypting ---", end - start)

        start = timeit.default_timer()

        decrypted_surname = Decrypt.decrypt_a(encrypted_surname)

        end = timeit.default_timer()

        print("Decrypted message: ", decrypted_surname)
        print("---  seconds for decrypting ---", end - start)

    elif answers['test_type'] == 'Test b':

        string = input("Enter your message: ")
        start = timeit.default_timer()

        encrypted_surname = Encrypt.encrypt_b(string)

        end = timeit.default_timer()
def test():
    for url in urls:
        Test = Decrypt(url, headers)
        Test.populate()
        print(Test.dump())
Пример #14
0
 def setUp(self):
     self.encrypt_instance = Encrypt()
     self.decrypt_instance = Decrypt()
Пример #15
0
    parser.add_argument('-f',
                        '--function',
                        help='Enter D for decryption and E for Encryption.',
                        required=True)
    parser.add_argument('-p',
                        '--path',
                        help='Path to file you want to decrypt/encrypt.',
                        required=True)
    args = parser.parse_args()

    path = args.path
    function = args.function.lower()

    if function not in ('e', 'd'):
        raise TypeError('No function found! (You should use either D or E.)')

    key = getpass('Please Enter your Key: ')

    if function == 'e':
        e = Encrypt(filename=path, key=key)
        encrypted_file_path = e.generate_encrypted_file()
        print(
            f'Encryption was successfully finished. encrypted file path is {encrypted_file_path}.'
        )
    else:
        e = Decrypt(filename=path, key=key)
        decrypted_file_path = e.generate_decrypted_file()
        print(
            f'Decryption was successfully finished. decrypted file path is {decrypted_file_path}.'
        )