Beispiel #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)
Beispiel #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.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)
 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)
    def main(self):
        responce = input(
            "If you want to encrypt a file type Y? If you want to input data to be encrypted type N. If you want to decrypt data type NN. Y/N/NN "
        ).upper().strip()

        while ((responce != "Y") and (responce != "N") and (responce != "NN")):
            print("\nResponce must be either Y/N/NN")
            responce = input(
                "If you want to encrypt a file type Y? If you want to input data to be encrypted type N. If you want to decrypt data type NN. Y/N/NN "
            ).upper().strip()

        if responce == "Y":  # encrypt existing file
            filePath = self.__fileHandler()

            encryption = EncryptFile(filePath)
            encryption.encAlg(filePath, encryption.encFile())

            responce = self.__responceHandler(
                "Do you want to delete the unencrypted file? Y/N (Y is recommended) "
            )

            if responce == "Y":
                os.remove(os.path.join(self.__PATH, filePath))

        elif responce == "NN":  # decrypt an encrypted file
            filePath = self.__fileHandler()
            outName = input("Enter name of output file: ")

            while os.path.exists(outName):
                responce = self.__responceHandler(
                    f"Are you sure you want to overwrite {outName}? Y/N ")

                if responce == "Y":
                    break

            decrypt = Decryption()
            decrypt.decrypt(filePath, outName)

            responce = self.__responceHandler(
                "Do you want to delete the encrypted file Y/N ")
            if responce == "Y":
                os.remove(filePath)

        else:  # encrypt user input
            data = input("Enter data to be encryped: ")
            encData = EncryptInput(data)
            encData.encAlg(outName=encData.encData())

            os.remove(os.path.join(self.__PATH, "data.txt"))
 def __init__(self, encryption_encoded_key, integrity_encoded_key):
     iv_length = 16
     is_length = 4
     byte_length = 16
     self.decrypt = Decryption.__init__(self, encryption_encoded_key,
                                        integrity_encoded_key, iv_length,
                                        is_length, byte_length)
Beispiel #7
0
 def decry(self):
     if self.file_name == '':
         if self.msg_box.get('1.0', END) != '':
             self.msg_box.delete('1.0', END)
         self.msg_box.insert(END, 'Please open a bitmap file first.')
         return 0
     elif self.available < 1:
         if self.msg_box.get('1.0', END) != '':
             self.msg_box.delete('1.0', END)
         self.msg_box.insert(END, 'This image is too short to hide message.')
         return 0
     else:
         decryption = Decryption(self.file_name)
         decry_msg = decryption.run()
         if self.msg_box.get('1.0', END) != '':
             self.msg_box.delete('1.0', END)
         self.msg_box.insert(END, 'Hidden message: "' + decry_msg + '".')
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]")
 def decryption( self, long_ciphertext ):
     res = Decryption.run( self, long_ciphertext );
     if "error" in res:
         return res;
     else:
         return {
             'idfa'     : res["plaintext"],
             'datetime' : res["datetime"],
         };
 def decryption(self, long_ciphertext):
     res = Decryption.run( self, long_ciphertext );
     if "error" in res:
         return res;
     else:
         return {
             'hyperlocal': self.decrypt_hyper_local( res["plaintext"] ),
             'datetime'  : res["datetime"],
         };
 def decryption(self, long_ciphertext):
     res = Decryption.run(self, long_ciphertext)
     if "error" in res:
         return res
     else:
         return {
             'idfa': res["plaintext"],
             'datetime': res["datetime"],
         }
 def decryption( self, long_ciphertext ):
     res = Decryption.run( self, long_ciphertext );
     if "error" in res:
         return res;
     else:
         price = unpack(">Q", res["plaintext"]);
         return {
             'price'    :   price[0],
             'datetime' :   res["datetime"],
         };
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)
Beispiel #14
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"
    )
 def __init__( self, encryption_encoded_key, integrity_encoded_key):
     iv_length   = 16;
     is_length   = 4; 
     byte_length = 20;
     self.decrypt = Decryption.__init__( self, encryption_encoded_key, integrity_encoded_key, iv_length, is_length, byte_length );
Beispiel #16
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()
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:
Beispiel #18
0
    def Crpyto_Decryptor(
        self, cipher_text, k, flag
    ):  #this flag value will tell whether the cypher text you are giving is original (flag==0) or else its is flag==1 is appended by its length i.e whether it is extracted from the stegeo image
        # 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.

        #Also note the argument k is for keys

        preprocessor = Preprocessing()

        # #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)
        ct_text = 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 )

        if flag == 1:
            cypher_txt_after_extraction = preprocessor.extract_real_binary_string(
                cipher_text)
        else:
            cypher_txt_after_extraction = cipher_text

        #DECRYPTION
        padded_pt_text = ""
        keys = k
        KEYS = preprocessor.Convert128_to_32bits(keys)

        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"

            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)
        real_pt_text = 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"
        )
        return (ct_text, real_plain_text)