Exemplo n.º 1
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)
Exemplo n.º 2
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()
 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)
 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)
Exemplo n.º 5
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
Exemplo n.º 7
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)
Exemplo n.º 8
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
Exemplo n.º 9
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})
Exemplo n.º 10
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
Exemplo n.º 11
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 + '.')
Exemplo n.º 12
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})
 def __init__(self, username=None, password=None, *args):
     self.username = username
     self.password = Encryption(password)
     self.extra_data = args
Exemplo n.º 14
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
                                  })
Exemplo n.º 15
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()
Exemplo n.º 16
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()
Exemplo n.º 17
0
 def process_result_value(self, value, dialect):
     if value is not None:
         return Encryption(value, cipher_key)
Exemplo n.º 18
0
def main():
    encryption = Encryption()
    encryption_valid = encryption.get_encryption()
    print(encryption_valid)
Exemplo n.º 19
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"
    )
Exemplo n.º 20
0
from Encryption import Encryption
from Decryption import Decryption
from Encoding import Encoding
# Fix --- Handle One Character -> Also, Build Interface
# Instances of Classes
encryp = Encryption()
decrypt = Decryption()
encode = Encoding()

message = raw_input("Enter your message: ")

count = 0
count2 = 0

while len(message) == 0 and count2 != 1:
    if count2 == 1:
        print "Try again some other time."
    count2 += 1
    message = raw_input("Enter some text for your message: ")

print

while encode.checkCharacters(message) and count2 < 1:
    if count == 1:
        print "There was a character in your message that is not supported.\nPlease try again later."
        break
    count += 1
    print "Please enter only the following characters within your message:\nA-Z\n.\n?\n,\n:\nspace\n'\n_____________________________________________"
    message = raw_input("Re-enter your message: ")

if count < 2 and count2 < 2:
Exemplo n.º 21
0
import string
import random
from Encryption import Encryption

en = Encryption()


class MasterKey:
    def create(self):

        content = "".join(
            random.choices(string.ascii_letters + string.digits, k=64))

        with open("MasterKey.key", "w+") as f:

            f.write(content)
            f.close()

    def get_masterkey(self):

        with open("MasterKey.key", "r") as f:

            return f.read()


def check(masterkey):

    with open("MasterKey.key", "r") as f:

        if masterkey == f.read():