Example #1
0
def main():
    while True:
        print "Choose from job"
        print "1.Key Generation"
        print "2.Encrytion"
        print "3.Decryption"
        print "4.Exit"
        choice = sys.stdin.readline()
 
        if (choice == '1\n'): 
            myKeyGenerator = keyGenerator()
            myKeyGenerator.keyGen()
            print "Key Generation Finished\n"
        elif (choice  == '2\n'):
            encryptor = Encryption()
            encryptor.encrypt()
            print "Encryption Finished\n"
        elif (choice == '3\n'):
            decryptor = Decryption()
            decryptor.decrypt()
            print "Decryption Finished\n"
        elif (choice == '4\n'):
            break;
        else: 
            print "invalid input"
            choice = sys.stdin.readline()
Example #2
0
def main2():
    p = Preprocessing()
    keys = "11110111110000001010010111101001101111101000101000000000111111111111000000001111111011011100010101010010101101010101000010111111"
    KEYS = p.Convert128_to_32bits(keys)
    #plain_text = "00000001110101111011011011111011110000000111010111101101101111100010111110011101001101110010100001011000100000100111011001001110"
    plain_text = "00000000000000000000000000000001010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
    print(plain_text)
    EI_S = p.Convert128_to_32bits(plain_text)
    e = Encryption()
    d = Decryption()

    cypher_txt = e.Encrypt(EI_S, KEYS)
    print("\ncypher_txt ", cypher_txt, "\n\n")

    e1, e2, e3, e4 = d.Decrypt(cypher_txt, KEYS)
    decrypted_txt = e1 + e2 + e3 + e4
    print("Decrypted Txt : ", decrypted_txt, "\n\n")
    print(decrypted_txt == plain_text)

    count = 0
    for i in range(128):
        if decrypted_txt[i] != plain_text[i]:
            print(i + 1)

            count += 1

    print(count)
 def __init__(self, objCommon):
     try:
         self.common = objCommon
         self.keyGeneration = KeyGeneration(objCommon)
         self.encryption = Encryption(objCommon)
     except Exception as ex:
         print(
             "An error occurred while initializing class Decryption. Error: ",
             ex)
Example #4
0
    def decode_header(self, raw_header):
        # assume raw_header is bytearray of values
        salt_end = GCM.get_salt_length()
        gcm_end = salt_end + GCM.get_iv_length()
        password_salt = bytes(raw_header[:salt_end])
        iv = bytes(raw_header[salt_end:gcm_end])

        self._gcm = GCM(iv=iv, password_salt=password_salt)
        self._gcm.make_key(self._password)
        del self._password
Example #5
0
def decrypt_cookies(cookies):
    encryption = Encryption()
    decrypted = {}
    for key, value in cookies.iteritems():
        Logger.d("Decrypting " + str((key, value)))
        try:
            decrypted[key] = encryption.decrypt(value)
        except EncryptionError:
            pass
    return decrypted
Example #6
0
    def Receive_Message(self, encryptionNeeded, encryptionAlgorithm, key):
        BUFFER_SIZE = 2048
        receivedMessage = self.connection.recv(BUFFER_SIZE)
        if (encryptionNeeded == True):
            from Encryption import Encryption
            receivedMessage = Encryption().Decrypt_Message(
                key, receivedMessage[:512])

        receivedMessage = receivedMessage.decode()
        #print("Received message:", receivedMessage)
        return (receivedMessage)
Example #7
0
def test_encryption(card_public_key, door_public_key, card_loop_size,
                    door_loop_size, encryption_key):
    card_loop_size1 = Encryption.calc_loop_size(card_public_key)
    door_loop_size1 = Encryption.calc_loop_size(door_public_key)
    assert (card_loop_size == card_loop_size1)
    assert (door_loop_size == door_loop_size1)

    private_key = Encryption.calc_private_key(door_public_key, card_loop_size1)
    assert (private_key == encryption_key)
    assert (encryption_key == Encryption.calc_private_key(
        card_public_key, door_loop_size1))
 def __init__(self):
     try:
         self.__usrInpt = -1
         self.common = Common("KEY.txt", "ENC.txt")
         self.keyGeneration = KeyGeneration(self.common)
         self.encryption = Encryption(self.common)
         self.decryption = Decryption(self.common)
         self.breakEncryption = BreakEncryption(self.common)
     except Exception as ex:
         print("An error occurred while initializing class Main. Error: ",
               ex)
Example #9
0
    def Crpyto_Encrytor(self, p_text):

        # encrypt it so that it gives out cypher text. which is stored in image

        plain_text = p_text  # input("Enter a plain text : ")
        plain_text += "#####"

        #example : This World shall Know Pain

        print(f"Entered plian Txt : {plain_text}")

        preprocessor = Preprocessing()

        #convert to binary
        plain_2_binary_string = preprocessor.string_2_binary(plain_text)

        #append the length in front of 25 bit
        #prepended_binary_string = preprocessor.prepend_length_of_binary_string(plain_2_binary_string)
        prepended_binary_string = plain_2_binary_string

        #padding with zeroes that binary string so that it is a multiple of 128.
        padded_binary_string = preprocessor.padding_of_text(
            prepended_binary_string)

        #ENCRYPTION
        encryptor = Encryption()

        print(f"Padded Binary string  pt1_txt --> : {padded_binary_string}")
        print('\n\n')

        cipher_text = ""
        pt1_txt = padded_binary_string
        keys = key_generation()
        KEYS = preprocessor.Convert128_to_32bits(keys)

        for i in range(0, len(padded_binary_string), 128):
            string_128_bit = padded_binary_string[i:i + 128]

            #Encryption starts
            EI_S = preprocessor.Convert128_to_32bits(string_128_bit)

            #keys = "11110111110000001010010111101001101111101000101000000000111111111111000000001111111011011100010101010010101101010101000010111111"

            C1, C2, C3, C4 = encryptor.Encrypt(EI_S, KEYS)
            cipher_text += C1 + C2 + C3 + C4

        print("cipher_text\n", cipher_text)
        print('\n')
        print("pt1_txt\n", pt1_txt)
        print("\n\n")

        return cipher_text, keys
Example #10
0
def encrypt_set_cookies(set_cookies, wrap_key):
    encryption = Encryption()
    encrypted = []
    for key, value, metadata in set_cookies:
        Logger.d("Encrypting " + str((key, value, metadata)))
        try:
            encrypted_value = encryption.wrap(value, wrap_key)
        except EncryptionError as e:
            Logger.e("Couldn't encrypt key:%s - value:%s\n\t%s"
                     % (key, value, str(e)))
            encrypted_value = value
        encrypted.append((key, encrypted_value, metadata))
    return encrypted
def execute(hash):
    computer_list = config["hosts"]
    log.info("The command is: %s" % hash)
    enc=Encryption()
    if hash == "start":
        command="bash /home/user/startpoc/sp1_as_user.sh"
    elif hash == "stop":
        #command="killall poclbm.py"
        command="screen -r \n exit"
    else:
        usage()
        sys.exit(1)
    for host in computer_list:
        RC=BTControl(host["name"], host["user"], enc.decrypt(host["pass"]), command)
        RC.start()
Example #12
0
    def encry(self):
        hide_msg = self.msg_box.get('1.0', END).replace('\n', '')
        if self.file_name == '':
            if hide_msg == '':
                self.msg_box.delete('1.0', END)
            self.msg_box.insert(END, 'Please open a bitmap file first.')
            return 0
        elif hide_msg == '':
            self.msg_box.insert(END, 'Input hidden message here.')
            return 0
        elif len(hide_msg) > self.available:
            if self.msg_box.get('1.0', END) != '':
                self.msg_box.delete('1.0', END)
            self.msg_box.insert(
                END, 'Input hidden message is larger than ' +
                str(self.available) + ' bytes.')
            return 0
        else:
            origin_file_name = self.file_name
            # add 'hidden' to new image file name
            new_file_name = self.file_name[:-4] + '_hidden' + self.file_name[
                -4:]
            encryption = Encryption(origin_file_name, new_file_name, hide_msg)
            encryption.run()

            global right_img
            right_img = Image.open(self.file_name)
            w, h = right_img.size
            # resize img
            scale_w = img_display_width / w
            scale_h = img_display_height / h
            scale = min(scale_w, scale_h)
            new_w = math.ceil(scale * w)
            new_h = math.ceil(scale * h)
            img = right_img.resize((new_w, new_h), Image.NEAREST)

            global right_photo
            right_photo = ImageTk.PhotoImage(img)
            self.right_img_canvas.create_image(img_display_width / 2,
                                               img_display_height / 2,
                                               anchor=CENTER,
                                               image=right_photo)

            if self.msg_box.get('1.0', END) != '':
                self.msg_box.delete('1.0', END)
            self.msg_box.insert(END,
                                'Saved new file into ' + new_file_name + '.')
class Main:
    #Constructor for Main class
    def __init__(self):
        try:
            self.__usrInpt = -1
            self.common = Common("KEY.txt", "ENC.txt")
            self.keyGeneration = KeyGeneration(self.common)
            self.encryption = Encryption(self.common)
            self.decryption = Decryption(self.common)
            self.breakEncryption = BreakEncryption(self.common)
        except Exception as ex:
            print("An error occurred while initializing class Main. Error: ",
                  ex)

    #String Representation
    def __str__(self):
        return "usrInpt: " + str(self.__usrInpt) + ", keyGeneration: " + str(self.keyGeneration) + ", common: " + str(self.common) + \
    ", encryption: " + str(self.encryption) + ", decryption: " + str(self.decryption) + ", breakEncryption: " + str(self.breakEncryption)

    #User interface
    def Start(self):
        try:
            while self.__usrInpt != 0:
                print("\nMain Menu:\n",\
                      "\n1. Generate Keys (Elgamal Algorithm)",\
                      "\n2. Encrypt Message (Requires Reciever's Public Key)",\
                      "\n3. Decrypt Message (Requires Receiver's Private Key)",\
                      "\n4. Break Encryption & Decipher Message (Baby Step Giant Step Algorithm)",\
                      "\n0. Exit",\
                      "\nPlease enter a digit corresponding to the step")
                userEntered = input("(e.g. 1/2/../0): ")
                result = self.common.IsInteger(userEntered)

                if result is False:
                    self.__usrInpt = -1
                else:
                    self.__usrInpt = result

                if self.__usrInpt == 1:
                    self.keyGeneration.GenerateAndStoreKeys()
                elif self.__usrInpt == 2:
                    self.encryption.EncryptMessage()
                elif self.__usrInpt == 3:
                    self.decryption.DecryptMessage()
                elif self.__usrInpt == 4:
                    self.breakEncryption.BreakEncryptionGetMessage()
                elif self.__usrInpt == 0:
                    print("\nExiting...")
                else:
                    print("\nInvalid Input entered! Please retry.")
        except Exception as ex:
            print(
                "An error occurred in function Main.Start while processing. Error: ",
                ex)
        finally:
            print("\nThank you!", \
                  "\nPython project on Encryption, Decryption and Man-In-The-Middle attack implementation", \
                  "\nsubmitted by Aayush Garg [email protected]")
Example #14
0
    def decrypt_and_save_data(self, raw_data, destination_file):
        decrypted = self._gcm.decrypt(
            raw_data[self.get_header_length():-GCM.get_tag_length()])
        # with open("temp", "wb") as f:
        #     f.write(decrypted)
        self._gcm.decrypt_finalize()

        with open(destination_file, "wb") as f:
            f.write(decrypted)
Example #15
0
 def Send_Message(self, encryptionNeeded, encryptionAlgorithm, key,
                  message):
     if encryptionNeeded == True:
         from Encryption import Encryption
         message = Encryption.Encrypt_Message(self, key, message)
     try:
         self.connection.send(message.encode())
     except:
         self.connection.send(message)
Example #16
0
    def __init__(self):
        from Communication import Communication
        from Encryption import Encryption

        PORT_NUMBER = 12371
        self.connections = []

        # [1] Generate asymmetric key pair
        strHostPrivateKey, strHostPublicKey = Encryption().Generate_RSA_Keys(
            keySize=4096, exponent=65537)
        self.Dump_Keys(strHostPrivateKey, strHostPublicKey, "host")
        #hostPublicKey = self.Load_Key(keyName="Public", keyType="host")
        hostPrivateKey = self.Load_Key("Private", "host")
        blacklist = []

        while True:

            # [2] Listen for attempted client connections
            clientConnection, address = self.Listen_For_Connection(PORT_NUMBER)
            communication = Communication(clientConnection)
            print(address[0], "has connected", end="\n\n")
            if address[0] in blacklist:
                print("Attempted connection from black listed source",
                      address[0],
                      end="\n\n")
                communication.Close_Connection()
                continue

                # [3] Send unencrypted public key
            communication.Send_Message(False, None, None, strHostPublicKey)
            #self.Send_Message(connection=clientConnection, encryptionNeeded=False, encryptionAlgorithm=None, key=None, message=publicKey, messageType="key")

            # [4] Receive client's public key and decrypt with host privatekey
            strClientPublicKey = communication.Receive_Message(
                False, None, None)
            self.Dump_Keys(None, strClientPublicKey, "client")
            clientPublicKey = self.Load_Key("Public", "client")

            # [5] Ask User what they would like to do: signup / login .. Return the logged in user
            # if user was unsuccessful at logging in, close connection and wait for new connection
            userID = self.Get_User_Option(communication, clientPublicKey,
                                          hostPrivateKey)
            if userID is None:
                print("No user logged in, looking for another connection")
                blacklist.append(address[0])
                print("Added", address[0], "to blacklist")
                communication.Close_Connection()

            else:
                print("Starting blackjack")
                from BlackJack_Host import BlackJack
                hostBlackJack = BlackJack(communication, userID,
                                          clientPublicKey, hostPrivateKey)
                communication.Close_Connection()
    def __init__(self):
        self.lg = logging.getLogger(__name__)

        self.conn = sqlite3.connect("passwords.db")

        self.c = self.conn.cursor()

        from Encryption import Encryption

        self.en = Encryption()
        pass
Example #18
0
    def get(self, request):
        with connection.cursor() as cursor:
            seller_id = request.session['user_id']
            cursor.execute(
                '''SELECT P.product_name, T.transaction_date, U.username 
                              FROM transaction T, product P, user U WHERE T.seller_id = "{}" 
                              AND P.product_id = T.product_id AND T.buyer_id = U.user_id'''
                .format(seller_id))

            orders_result = cursor.fetchall()

            encryption = Encryption()

            orders_result = [(order[0], order[1],
                              encryption.decrypt(order[2][2:-1].encode()))
                             for order in orders_result]

            return render(request=request,
                          template_name=self.template_name,
                          context={'orders_result': orders_result})
Example #19
0
class Encoder:

    MODES = {'GCM': 8}

    def __init__(self,
                 password,
                 source_image_folder_path,
                 destination_image_folder_path,
                 mode='GCM'):
        self.mode = Encoder.MODES[mode]
        self.source_image_folder_path = source_image_folder_path
        self.destination_image_folder_path = destination_image_folder_path
        if os.path.exists(self.destination_image_folder_path):
            shutil.rmtree(self.destination_image_folder_path)
        os.makedirs(self.destination_image_folder_path)

        self.gcm = GCM()
        self.gcm.make_key(password)
        self.transcriber = Transcriber(self.mode, source_image_folder_path,
                                       destination_image_folder_path)

    def encode_file(self, file_path):
        with open(file_path, 'rb') as source:
            file_bytes = source.read()
            encrypted = self.gcm.encrypt(file_bytes)
            tag = self.gcm.encrypt_finalize()

        header = self.gcm.password_salt + self.gcm.iv

        full_length = len(header) + len(encrypted) + len(tag)
        # if not self.transcriber.can_fit_bytes(full_length):
        #     print("Not enough images to store the necessary data")
        #     exit()
        self.transcriber.choose_needed_images(full_length)

        print("full length", full_length, full_length * 8)

        self.transcriber.set_encoding(header + encrypted + tag)
        # with open("encode-test", "wb") as f:
        #     f.write(header + encrypted + tag)
        self.transcriber.finish_encoding()
Example #20
0
class Decoder:

    MODES = {'GCM': 8}
    MODE_LENGTH = 1

    def __init__(self, password, image_folder_path):
        self.image_folder_path = image_folder_path
        self.mode = None
        self._gcm = None
        self._password = password
        self._data_length = 0

        self.extractor = Extractor(image_folder_path)

    def get_header_length(self):
        return GCM.get_iv_length() + GCM.get_salt_length()

    def decode_header(self, raw_header):
        # assume raw_header is bytearray of values
        salt_end = GCM.get_salt_length()
        gcm_end = salt_end + GCM.get_iv_length()
        password_salt = bytes(raw_header[:salt_end])
        iv = bytes(raw_header[salt_end:gcm_end])

        self._gcm = GCM(iv=iv, password_salt=password_salt)
        self._gcm.make_key(self._password)
        del self._password

    def get_tag(self, raw_data):
        tag = bytes(raw_data[-GCM.get_tag_length():])
        self._gcm.set_tag(tag)

    def decrypt_and_save_data(self, raw_data, destination_file):
        decrypted = self._gcm.decrypt(
            raw_data[self.get_header_length():-GCM.get_tag_length()])
        # with open("temp", "wb") as f:
        #     f.write(decrypted)
        self._gcm.decrypt_finalize()

        with open(destination_file, "wb") as f:
            f.write(decrypted)

    def decode_file(self, file_path):

        raw_data = self.extractor.load_images()
        # with open("decode-test", "wb") as f:
        #     f.write(raw_data)

        raw_header = raw_data[:self.get_header_length()]
        self.decode_header(raw_header)
        self.get_tag(raw_data)

        self.decrypt_and_save_data(raw_data, file_path)
Example #21
0
    def _convert(self, value):
        """Returns a Encryption object from the given string.

        PasswordHash instances or None values will return unchanged.
        Strings will be hashed and the resulting PasswordHash returned.
        Any other input will result in a TypeError.
        """
        if isinstance(value, Encryption):
            return value
        elif isinstance(value, basestring):
            return Encryption.new(value, self.cipher_key)
        elif value is not None:
            raise TypeError(
                'Cannot convert {} to a EncryptedValue'.format(type(value)))
Example #22
0
class StartPageView(View):
    template_name = 'start_page.html'
    loginForm = LoginForm
    signupForm = SignUpForm
    encryption = Encryption()

    def get(self, request):
        if request.session.get('user_id') is not None:
            return redirect('homepage_view')

        login_form = self.loginForm()
        signup_form = self.signupForm()
        return render(request=request,
                      template_name=self.template_name,
                      context={'login_form': login_form,
                               'signup_form': signup_form})
Example #23
0
    def __init__(self,
                 password,
                 source_image_folder_path,
                 destination_image_folder_path,
                 mode='GCM'):
        self.mode = Encoder.MODES[mode]
        self.source_image_folder_path = source_image_folder_path
        self.destination_image_folder_path = destination_image_folder_path
        if os.path.exists(self.destination_image_folder_path):
            shutil.rmtree(self.destination_image_folder_path)
        os.makedirs(self.destination_image_folder_path)

        self.gcm = GCM()
        self.gcm.make_key(password)
        self.transcriber = Transcriber(self.mode, source_image_folder_path,
                                       destination_image_folder_path)
Example #24
0
    def build_response(self, entries=[]):
        try:
            from Encryption import Encryption

            en = Encryption()

            #print(f"{en.decrypt(entries[0])} | {en.decrypt(entries[1])} | {en.decrypt(entries[2])}")
            print(f"{entries[0]} | {entries[1]} | {entries[2]}")
            import subprocess
            import clipboard
            clipboard.copy(entries[1])
            print("Password has been copied to your clipboard")

        except TypeError as e:

            pass
Example #25
0
    def crypt(argv):
        message = bitarray()
        with argv.Sourcefile as fh:
            message.fromfile(fh)

        key = bitarray()
        with argv.Keyfile as fh:
            key.fromfile(fh)

        start_time = datetime.now()

        encrypted = Encryption.encrypt(message, key)

        time_elapsed = datetime.now() - start_time
        print('Time elapsed (hh:mm:ss.ms) {}'.format(time_elapsed))

        with argv.Destinationfile as fh:
            encrypted.tofile(fh)
Example #26
0
    def post(self, request):

        form = self.searchForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            with connection.cursor() as cursor:
                if data['search_filter'][0] == 'C':
                    cursor.execute(
                        '''SELECT C.cat_name, S.store_name, C.cat_descr, S.store_id, C.cat_id
                          FROM store S, category C, store_categories SC 
                          WHERE SC.category_id IN 
                          (SELECT cat_id FROM category WHERE cat_name LIKE "%%{}%%")
                          AND S.store_id = SC.store_id
                          AND C.cat_id = SC.category_id'''.format(
                            data['search_item']))

                    categories_result = cursor.fetchall()

                    return render(request=request,
                                  template_name=self.buyer_template_name,
                                  context={
                                      'categories_result': categories_result,
                                      'search_form': form
                                  })

                elif data['search_filter'][0] == 'S':
                    cursor.execute(
                        '''SELECT S.store_name, S.create_date, U.username, S.store_id 
                            FROM store S, user U WHERE S.store_name LIKE "%%{}%%" 
                            AND U.user_id = S.owner_id
                            '''.format(data['search_item']))

                    store_result = cursor.fetchall()

                    encryption = Encryption()

                    store_result = [
                        (store[0], store[1],
                         encryption.decrypt(store[2][2:-1].encode()), store[3])
                        for store in store_result
                    ]

                    return render(request=request,
                                  template_name=self.buyer_template_name,
                                  context={
                                      'store_result': store_result,
                                      'search_form': form
                                  })

                else:
                    cursor.execute(
                        '''SELECT P.product_name, P.product_specs, P.product_price, 
                          P.number_in_stock, S.store_name, C.cat_name, P.product_id
                          FROM  product P, store_categories SC, store S, category C  
                          WHERE P.product_name LIKE "%%{}%%"
                          AND C.cat_id = P.category_id
                          AND SC.category_id = P.category_id 
                          AND S.store_id = SC.store_id'''.format(
                            data['search_item']))

                    product_result = cursor.fetchall()

                    return render(request=request,
                                  template_name=self.buyer_template_name,
                                  context={
                                      'product_result': product_result,
                                      'search_form': form
                                  })
Example #27
0
 *				 facebook	: /viral4ever
 *				 google+	: /+ViralJoshi
 *				 twitter	: /viralhj
 *				 linkedin	: /in/viralj
 *
 *
 */

 required python version :    Python 3.0+
"""

from Encryption import Encryption   # Importing custom Encryption class
from Decryption import Decryption   # Importing custom Decryption class
import time     # Importing for time delay

a = str(input("Please enter ENCRYPTION or DECRYPTION : ")).lower()  # Need user input to know next action

"""
Action for Encryption or Decryption
starts from here.
"""
if a == "encryption":
    b = str(input("Please enter a string : "))
    Encryption.encryption(b)
elif a == "decryption":
    Decryption.decryption()
else:
    print("Wrong answer! Good bye...")
    time.sleep(1)
    exit()
Example #28
0
 def get_header_length(self):
     return GCM.get_iv_length() + GCM.get_salt_length()
Example #29
0
# 加密调用代码

from Encryption import Encryption
enc = Encryption('Debug\H128_data.dat')
enc.encryption()

# 解密调用代码

from Decrypt import Decrypt
dec = Decrypt('Debug\H128_data.dat')
dec.decrypt()
Example #30
0
    def send_email(self):
        try:
            self.receiver = self.param_3.get()
            self.subject = self.param_4.get()
            self._send_text = self.param_5.get("0.0", "end")
        except Exception as e:
            print "RECEIVER INTO ERROR ->", str(e)
        print self.receiver, self.subject, self._send_text
        # 加入文本消息
        msg = MIMEMultipart()
        msg['From'] = 'WUD_EMAIL_SYSTEM <' + self.user + '>'
        msg['To'] = self.receiver
        msg['Subject'] = self.subject
        _send_text = Encryption().Encry_text(str(self._send_text))  # AES加密后的密文
        _send_text = MIMEText(_send_text, 'plain', 'utf-8')
        msg.attach(_send_text)

        # 加密文件
        cipher_path = []
        for path in self.path:
            cipher_path.append(Encryption().Encry_file(path))  # 加密图片文件
        self.path[:] = []
        for path in cipher_path:
            self.path.append(path)  # 将加密后的附件路径添加至发送列表

        # 添加附件 文件路径不能包含中文
        if len(self.path) != 0:
            try:
                for file_path in self.path:
                    print file_path
                    file_part = MIMEApplication(open(file_path, 'rb').read())
                    file_part.add_header('Content-Disposition',
                                         'attachment',
                                         filename=file_path)
                    msg.attach(file_part)
                print "ADD SUCCESS"
            except Exception as e:
                print "ADD FILE ERROR ->", str(e)

        self.server.set_debuglevel(1)
        self.server = smtplib.SMTP(self.Smtp_Server, 25)  # 与邮件服务器重新建立连接
        self.server.login(self.user, self.passwd)  # 重新登入
        self.remain_windows = Tk()
        self.remain_windows.title("提示消息")
        try:
            self.server.sendmail(self.user, self.receiver, msg.as_string())
            self.server.quit()
            remain_lable = Frame(self.remain_windows)
            Label(remain_lable, text="Send Success!").pack(fill="y",
                                                           expand="yes")
            remain_lable.pack()
            self.remain_windows.mainloop()
        except Exception as e:
            print "Send Error - >", str(e)
            remain_lable = Frame(self.remain_windows)
            Label(remain_lable, text="Send Failed!").pack(fill="y",
                                                          expand="yes")
            remain_lable.pack()
            self.remain_windows.mainloop()

        exit_button = Frame(self.remain_windows)
        Button(exit_button, text="Confirm",
               command=self.destory_windows).pack()
        exit_button.pack()
Example #31
0
 def process_result_value(self, value, dialect):
     if value is not None:
         return Encryption(value, cipher_key)
Example #32
0
 def get_tag(self, raw_data):
     tag = bytes(raw_data[-GCM.get_tag_length():])
     self._gcm.set_tag(tag)
Example #33
0
def main():
    # For the integration testing I will take plain txt from usr converting into binary string giving it to Encryption block to
    # encrypt it so that it gives out cypher text. which is tored in image
    # after extraaction of cypher txt from stegeo img it will be given to the decryption module
    # Decryptor decrypt it to yield plain txt.

    plain_text = input("Enter a plain text : ")

    #example : This World shall Know Pain

    print(f"Entered plian Txt : {plain_text}")

    preprocessor = Preprocessing()

    #convert to binary
    plain_2_binary_string = preprocessor.string_2_binary(plain_text)

    #append the length in front of 25 bit
    prepended_binary_string = preprocessor.prepend_length_of_binary_string(
        plain_2_binary_string)

    #padding with zeroes that binary string so that it is a multiple of 128.
    padded_binary_string = preprocessor.padding_of_text(
        prepended_binary_string)

    #ENCRYPTION
    encryptor = Encryption()

    print(f"Padded Binary string  pt1_txt --> : {padded_binary_string}")
    print('\n\n')

    cipher_text = ""
    pt1_txt = padded_binary_string

    for i in range(0, len(padded_binary_string), 128):
        string_128_bit = padded_binary_string[i:i + 128]

        #Encryption starts
        EI_S = preprocessor.Convert128_to_32bits(string_128_bit)

        keys = "11110111110000001010010111101001101111101000101000000000111111111111000000001111111011011100010101010010101101010101000010111111"
        KEYS = preprocessor.Convert128_to_32bits(keys)

        C1, C2, C3, C4 = encryptor.Encrypt(EI_S, KEYS)
        cipher_text += C1 + C2 + C3 + C4

    print("cipher_text\n", cipher_text)
    print('\n')
    print("pt1_txt\n", pt1_txt)
    print("\n\n")
    ct_text = cipher_text

    #prepended the length of cypher text in front of 25 bit i.e first 25 bit shows length of cypher text
    prepended_cypher_txt = preprocessor.prepend_length_of_binary_string(
        cipher_text)

    #padd it now this cypher txt -->prepended_cypher_txt to padded_cypher_txt
    padded_cypher_txt = preprocessor.padding_of_text(prepended_cypher_txt)

    #Now the padded cypher text -->padded_cypher_txt   will go inside the image and image will be called after insertion as
    #steogo image

    #Now we have to extract LSB of whole image (or it can be modified / optimized further )

    cypher_txt_after_extraction = preprocessor.extract_real_binary_string(
        padded_cypher_txt)

    #DECRYPTION
    padded_pt_text = ""

    decryptor = Decryption()

    for i in range(0, len(cypher_txt_after_extraction), 128):
        cypher_128_bit = cypher_txt_after_extraction[i:i + 128]
        #print("###",i , i+128 , string_128_bit)
        #print('\n\n')

        CT_S = preprocessor.Convert128_to_32bits(cypher_128_bit)
        keys = "11110111110000001010010111101001101111101000101000000000111111111111000000001111111011011100010101010010101101010101000010111111"
        KEYS = preprocessor.Convert128_to_32bits(keys)
        #print("\n\nKEYS : ",KEYS)

        #print('\n\n')

        E1, E2, E3, E4 = decryptor.Decrypt(CT_S, KEYS)
        padded_pt_text += E1 + E2 + E3 + E4

    print("padded_pt_text\n", padded_pt_text)
    print('\n')

    print("Ab bata jara ", end="")
    print(pt1_txt == padded_pt_text)

    #Now extracting actual binary string from padded plain txt
    real_pt_text = preprocessor.extract_real_binary_string(padded_pt_text)

    #Now convert this real plain txt into Ascii text
    real_plain_text = preprocessor.binary_2_string(real_pt_text)

    print(
        f"\n\n\n\n\n\n\n\n\n After all the actual text was :--> {real_plain_text}\n\n\n\n\n\n\n\n\n"
    )
class BreakEncryption:
    #Constructor for BreakEncryption class
    def __init__(self, objCommon):
        try:
            self.common = objCommon
            self.encryption = Encryption(objCommon)
            self.keyGeneration = KeyGeneration(objCommon)
            self.decryption = Decryption(objCommon)
        except Exception as ex:
            print(
                "An error occurred while initializing class BreakEncryption. Error: ",
                ex)

    #String Representation
    def __str__(self):
        return "No member variables other than member objects to classes"

    #4. Break encryption and get original message using Baby Step Giant Step algorithm
    def BreakEncryptionGetMessage(self):
        try:
            print("\nIf your listening to somebody's conversation as a Man In The Middle",\
                  "and wish to break an encrypted message,")
            print(
                "you must have the knowledge of encrypted message and the header sent to the Reciever."
            )

            #Read Encrypted Message and Header from the file
            tupleEncMsgHead = self.encryption.ReadEncryptedMessageAndHeader()

            if len(tupleEncMsgHead) > 0:
                print(
                    "\nThe public key of the Receiver is required to break an encryption."
                )
                print(
                    "The Public Keys are usually publicly available via Key Hosting Services."
                )

                #Read public key from file
                receiversKeys = self.keyGeneration.ReadReceiversKeys(False)

                if len(receiversKeys) > 0:
                    encryptedMessage, header = tupleEncMsgHead[
                        0], tupleEncMsgHead[1]
                    primitiveElement = receiversKeys[0]
                    primitiveRaisedSecretModPrime = receiversKeys[1]
                    randomPrime = receiversKeys[2]

                    print(
                        "\nBreaking Encyption (using Baby Step Giant Step Algorithm)..."
                    )
                    self.__PerformBabyStepGiantStep(
                        encryptedMessage, header, primitiveElement,
                        primitiveRaisedSecretModPrime, randomPrime)

        except Exception as ex:
            print(
                "An error occurred in function BreakEncryption.BreakEncryptionGetMessage while processing. Error: ",
                ex)

    #To perform Baby-Step-Giant-Step algorithm using Receiver's public keys and Header to break Encryption
    #   and get the original message
    def __PerformBabyStepGiantStep(self, encryptedMessage, header,
                                   primitiveElement,
                                   primitiveRaisedSecretModPrime, randomPrime):
        try:
            randomVar = self.__ComputePowerVariable(header, primitiveElement,
                                                    randomPrime)
            #print("randomVar:", randomVar)
            if randomVar == -1:
                print(
                    "\nBaby Step Giant Step failed to break encryption for given Public Key and Header combination."
                )
                print(
                    "Please try again for a different Receiever\'s Public Key and Header combination..."
                )
            else:
                #Encrypted Message = message * (c^b mod p) mod p
                #message = Encrypted Message * Inverse of (c^b mod p) mod p

                #c^b mod p
                primitiveRaisedSecRaisedRandomModPrime = self.common.GetExponentiation(
                    primitiveRaisedSecretModPrime, randomVar, randomPrime)
                #print("primitiveRaisedSecRaisedRandomModPrime:", primitiveRaisedSecRaisedRandomModPrime)
                #message = Encrypted Message * Inverse of (c^b mod p) mod p
                message = (encryptedMessage *
                           self.decryption.GetInverseModPrime(
                               primitiveRaisedSecRaisedRandomModPrime,
                               randomPrime)) % randomPrime
                print("\nCracked Original Message:", message)

        except Exception as ex:
            print(
                "An error occurred in function BreakEncryption.__PerformBabyStepGiantStep while processing. Error: ",
                ex)

    #In the equation a = b ^ c mod n, below function computes 'c'
    # Representationally: answerVar = baseVar ^ powerVar Mod prime
    def __ComputePowerVariable(self, answerVar, baseVar, prime):
        try:
            dictLHS, dictRHS = {}, {}
            m = int(math.ceil(math.sqrt(prime - 1)))
            #print("m:", m)
            invBaseVar = self.decryption.GetInverseModPrime(baseVar, prime)
            #print("invBaseVar:", invBaseVar)
            invBaseVarRaisedm = self.common.GetExponentiation(
                invBaseVar, m, prime)
            #print("invBaseVarRaisedm:", invBaseVarRaisedm)

            #answerVar * (invBaseVar ^ m) ^ i  =  baseVar ^ j
            #where 0 <= i <=m
            #and 0 <= j < m

            #All L.H.S. values of equation answerVar * (invBaseVar ^ m) ^ i  =  baseVar ^ j
            for i in range(m + 1):
                valueLHS = (self.common.GetExponentiation(
                    invBaseVarRaisedm, i, prime) * answerVar) % prime
                dictLHS[i] = valueLHS

            #All R.H.S. values of equation answerVar * (invBaseVar ^ m) ^ powerVar  =  baseVar ^ otherPowerVar
            for j in range(m):
                valueRHS = self.common.GetExponentiation(baseVar, j, prime)
                dictRHS[j] = valueRHS

            listCombinationTuple = [(i, j) for i in dictLHS for j in dictRHS
                                    if dictLHS[i] == dictRHS[j]]
            #print("listCombinationTuple:", listCombinationTuple)
            if len(listCombinationTuple) > 0:
                powerVar = int((listCombinationTuple[0][0] * m) +
                               listCombinationTuple[0][1])
            else:
                #Baby-Step-Giant-Step algorithm failed to crack encryption
                powerVar = -1
            #print("powerVar:", powerVar)
            return powerVar
        except Exception as ex:
            print(
                "An error occurred in function BreakEncryption.__ComputePowerVariable while processing. Error: ",
                ex)
# Date: 07 March 2016
# Written By: Phantom Raspberry Blower

# serial number (key): 0000000021adc001
# email password (crypt): JLFC3HeJQtU=
# (iv): PRB StrikesAgain

from SystemInfoNew import SystemInfo
from Encryption import Encryption
from SendEmail import SendEmail

si = SystemInfo()
serial = si.get_cpu_serial()

enc = Encryption(serial)
dec = Encryption(serial)
se = SendEmail(True)

# Fetch the configuration settings defined by the user
tree = et.parse(self.addon_data_path + 'script.force-install-all-ep/settings.xml')
root = tree.getroot()
# Iterate through the settings
for setting in root.findall('setting'):
  if setting.get('id') == 'email_key':
    enc_pass = enc.encrypt_msg(setting.get('value')

password = enc.decrypt_msg(enc_pass)

enc_msg = enc.encrypt_msg(si.get_system_info())