Пример #1
0
def RenamePassTitle(newPassTitle, lineNum, encryptionKey):
    AESEncryptionKey = Encryptor.BindKey(Encryptor.GetKey(), encryptionKey)
    if (not DoesProgramFileExist(passFile)):
        return False

    #Get Current File
    with open((GetFileLocation() + passFile), "r") as f:
        data = f.readline()
    fileContent = Encryptor.DecryptFile(data, AESEncryptionKey)

    if (lineNum < 0 or lineNum >= len(fileContent)):
        return False

    #Get password locker line
    fullLine = SplitString(fileContent[lineNum], sep2)

    lineToWrite = fullLine[0] + sep2 + Encryptor.AESEncrypt(
        newPassTitle, AESEncryptionKey) + sep2 + fullLine[2]

    #Write back to file
    fileContent[lineNum] = lineToWrite

    writeFileString = Encryptor.EncryptFile(fileContent, AESEncryptionKey)
    with open((GetFileLocation() + passFile), "w") as f:
        f.write(writeFileString)

    return True
Пример #2
0
def GetPassFromFile(index, encryptionKey):
    AESEncryptionKey = Encryptor.BindKey(Encryptor.GetKey(), encryptionKey)
    if (not DoesProgramFileExist(passFile)):
        return None
    with open((GetFileLocation() + passFile), "r") as f:
        dataSet = f.readline()
    #Decrypt file
    data = Encryptor.DecryptFile(dataSet, AESEncryptionKey)

    sepData = SplitString(data[index], sep2)

    foundPass = Encryptor.AESDecrypt(sepData[2], AESEncryptionKey)
    splitData = foundPass.split(userpassSep)

    toReturn = []
    if (splitData[1].lower() != "null"):
        toReturn.append("USER: "******"PASS: "******"null"):
        toReturn.append("Additional: " + splitData[2])
    #Add group to return
    if (sepData[0].lower() != "null"):
        toReturn.append("")
        toReturn.append("In group: " + sepData[0])
    return toReturn
Пример #3
0
    def __init__(self, root):

        self.encryptor = Encryptor()
        self.decryptor = Decryptor()

        self.root = root
        self.width = 400
        self.height = 160
        self.screen_width = self.root.winfo_screenwidth()
        self.screen_height = self.root.winfo_screenheight()
        self.x = (self.screen_width / 2) - (self.width / 2)
        self.y = ((self.screen_height / 2) - (self.height / 2)) * 0.6
        self.root.geometry("%dx%d+%d+%d" % (self.width, self.height, self.x, self.y))

        self.root.configure(background='#3B3B3B')
        self.root.title("timi")
        self.root.resizable(False, False)

        self.input_entry = Entry(self.root, font="Arial 10", relief="flat")
        self.input_entry.place(x=40, y=18, width=320, height=25)

        self.encrypt_button = Button(self.root, command=self.encrypt, fg="#000000", font="Arial 8 bold", activeforeground="#FFFFFF",
                             activebackground="#ADADAD", bg="#D3D3D3", text='encrypt', relief="flat")
        self.encrypt_button.place(x=120, y=55, width=70)

        self.decrypt_button = Button(self.root, command=self.decrypt, fg="#000000", font="Arial 8 bold", activeforeground="#FFFFFF",
                                     activebackground="#ADADAD", bg="#D3D3D3", text='decrypt', relief="flat")
        self.decrypt_button.place(x=210, y=55, width=70)

        self.scrollbar = Scrollbar(root)
        self.output_field = Text(root, height=3)
        self.scrollbar.place(x=342, y=92, width=18, height=52)
        self.output_field.place(x=40, y=92, width=300)
        self.output_field.config(yscrollcommand=self.scrollbar.set)
        self.scrollbar.config(command=self.output_field.yview)
Пример #4
0
def CreateTestFile():
    if (not DoesProgramFileExist(testFile, workingPath)):
        #If test file doesn't exist, create one
        toWrite = Encryptor.AESEncrypt("PASS", Encryptor.GetKey())
        checkFile = open(workingPath + testFile, "w+")
        checkFile.write(toWrite + "\n")
        checkFile.close()
Пример #5
0
def CreateAccount():
    console.out(16, 0.03)

    askCommand = True
    while (askCommand):
        newUser = input("")
        newPass = ""
        if (not ParseForCommand(newUser)):
            askCommand = False

    doesMatch = False
    while (not doesMatch):
        console.out(21)
        newPass = getpass.getpass("")
        if (not ParseForCommand(newPass)
            ):  #Only run rest of routine if input was not a command
            console.out(22)
            check = getpass.getpass("")

            if (newPass == check):
                doesMatch = True
            else:
                console.out(23)

    newSalt = Encryptor.GenerateSALT()
    encPass = Encryptor.OneWayEncryptor(newPass, newSalt)
    FileHandler.CreateUserAccount(newUser, encPass, newSalt)
Пример #6
0
def encrypt(fileName, key):
    with open(fileName, "r+b") as file2Encrypt:
        data = file2Encrypt.read()
        encryptor = Encryptor(key, iv)  
        cipherText = encryptor.encrypt(data)
        cipherText = base64.b64encode(cipherText)
        with open("{}.enc".format(fileName), "wb") as encryptedFile:
            encryptedFile.write(cipherText)
    os.remove(fileName)
Пример #7
0
def CheckTestFile():
    if (not DoesProgramFileExist(testFile, workingPath)):
        #file doesn't exist, cannot perform check
        return False
    else:
        with open(workingPath + testFile) as f:
            checkFound = f.readline()
        passCheck = Encryptor.AESDecrypt(checkFound, Encryptor.GetKey())
        if (passCheck == "PASS"):
            return True
    return False
Пример #8
0
def decrypt(fileName, key):
    try:
        with open(fileName, "r+b") as file2Decrypt:
                data = base64.b64decode(file2Decrypt.read())
                decryptor = Encryptor(key, data[:AES.block_size])
                plainText = decryptor.decrypt(data)
                with open(fileName[:-4], "wb") as decryptedFile:
                    decryptedFile.write(plainText)
        os.remove(fileName)
    except:
        print("Cannot decrypt this file")
Пример #9
0
 def __init__(self, user, passw):
     salt = enc.GenerateSALT()
     self.sessionSALT = salt
     self.user = enc.AESEncrypt(user, salt)
     self.passw = enc.AESEncrypt(passw, salt)
     self.toClear = False
     
     #Define all commands, add to self
     commandList = []
     for cmds in GetCommandList():            
         commandList.append(CommandInfo.Command(cmds[0], getattr(self, cmds[0]), cmds[1], cmds[2], cmds[3], cmds[4]))
     self.commandList = commandList
Пример #10
0
 def run(self):
     try:
         #            Logger.log("Encrypting focus : page = " + str(self.page) + " count = " + str(self.count) + " guid = " + str(int(m.hexdigest(), 16)))
         m = hashlib.md5()
         m.update((self.fileName + ":" + str(self.page) + ":" +
                   str(self.count)).encode('utf-8'))
         getChord = self.chord.locateSuccessor(int(m.hexdigest(), 16), True)
         #Check to make sure the file guid is located in the respective node.
         if getChord.guid == self.chord.guid:
             #                Logger.printLog("Encrypt page = " + str(self.page) + " count = " + str(self.count) + " guid = " + str(int(m.hexdigest(), 16)))
             #No need for chain encryption if count is a total of 1, if it's greater then it'll do a chain encryption
             if self.count == 1:
                 #                   Logger.log("page = " + str(self.page) + " count = initial")
                 RSACipher, cipherText, IV, tag = Encryptor.initialize(
                     self.data)
             else:
                 #                    Logger.log("page = " + str(self.page) + " count =" + str(count))
                 for y in self.chord.keychain:
                     if y["Chord"] == self.prevKey:
                         for x in self.chainEncryption:
                             if x["Set"] == self.count - 1:
                                 RSACipher, cipherText, IV, tag = Encryptor.chainInitialize(
                                     b64decode(x["RSACipher"]),
                                     b64decode(self.data),
                                     b64decode(x["IV"]),
                                     b64decode(x["Tag"]), y["Key"])
             self.chainEncryption.append({
                 'Set': self.count,
                 'RSACipher': RSACipher,
                 'IV': IV,
                 'Tag': tag
             })
             #If the encryption happens the MAX_CHAIN_ENCRPYTION amount of times, then it will be finished, else it will chainEncrpyt again
             if self.count == constant.MAX_CHAIN_ENCRYPTION:
                 tokenHash = hashlib.md5()
                 combo = str(int(m.hexdigest(), 16)) + ":" + str(self.token)
                 tokenHash.update(combo.encode('utf-8'))
                 getChord.createPage(cipherText, int(int(m.hexdigest(),
                                                         16)),
                                     int(tokenHash.hexdigest(), 16),
                                     self.chainEncryption)
             else:
                 getChord.chainEncrypt(self.fileName, cipherText,
                                       self.count + 1, self.chainEncryption,
                                       self.page, self.token,
                                       self.chord._guid)
         else:
             getChord.chainEncrypt(self.fileName, self.data, self.count,
                                   self.chainEncryption, self.page,
                                   self.token, self.prevKey)
     except Exception as e:
         print(str(e))
Пример #11
0
def GetPasswordGroups(encryptionKey):
    AESEncryptionKey = Encryptor.BindKey(Encryptor.GetKey(), encryptionKey)
    if (not DoesProgramFileExist(passFile)):
        return None
    with open((GetFileLocation() + passFile), "r") as f:
        dataSet = f.readline()
    #Decrypt file
    data = Encryptor.DecryptFile(dataSet, AESEncryptionKey)
    groups = []
    for i in range(0, len(data)):
        foundGroup = SplitString(data[i], sep2)[0]
        if (foundGroup[0] != "#" and foundGroup.lower() != "null"):
            groups.append(foundGroup)
    return groups
Пример #12
0
def GetPasswordTitle(searchTerm, encryptionKey):
    AESEncryptionKey = Encryptor.BindKey(Encryptor.GetKey(), encryptionKey)
    if (not DoesProgramFileExist(passFile)):
        return None
    with open((GetFileLocation() + passFile), "r") as f:
        encDataSet = f.readline()
    dataSet = Encryptor.DecryptFile(encDataSet, AESEncryptionKey)
    for idx, data in enumerate(dataSet):
        if (data != "" and data[0] != "#"):
            title = SplitString(data, sep2)[1]
            foundTitle = Encryptor.AESDecrypt(title, AESEncryptionKey).lower()
            if (searchTerm.lower() == foundTitle):
                return idx
    return -1
Пример #13
0
    def __init__(self):
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # self.server_socket.settimeout(3)
        self.address = ()
        self.max_supported_devices = 3
        self.buff = 1024
        self.home_path = ''
        self.store_path = ''
        self.client = None

        # 读取配置文件
        self.readConfig()

        # 绑定地址
        self.server_socket.bind(self.address)
        # 最多三台设备
        self.server_socket.listen(int(self.max_supported_devices))

        # 初始化加密器
        self.encryptor_generator = Encryptor.AES_MD5()

        self.file_tree = filetree.FileTree()
        self.file_tree.setStorePath(self.store_path)
        self.file_tree.setHomePath(self.home_path)

        self.download_list = []

        self.load_gerenator = load.Load(self.buff)
Пример #14
0
def readBucket(bucketID, maxDataLength):
    if not os.path.exists(home + bucketLoc):
        os.makedirs(home + bucketLoc)

    inputFile = open(home + bucketLoc + str(bucketID), "rb")         # rb = read binary
    #bytesIn = inputFile.read()
    bytesIn = pickle.load(inputFile)		
    inputFile.close()
    if encrypt:
        bytesIn = Encryptor.decrypt(bytesIn, key)

    result = []
    while True:
        leafBytes = bytesIn[:4]
        bytesIn = bytesIn[4:]
        if leafBytes == b"":
            break                                             # break if end of file
        segIDBytes = bytesIn[:4]
        bytesIn = bytesIn[4:]
        dataLength = int.from_bytes(bytesIn[:4], byteorder = "little")
        bytesIn = bytesIn[4:]
        data = bytesIn[:dataLength]
        bytesIn = bytesIn[maxDataLength:]
        result.append(Block.Block(int.from_bytes(leafBytes, byteorder = "little"), int.from_bytes(segIDBytes, byteorder = "little"), data))
    
    return result
Пример #15
0
def files_decrypt(key, folder):
    for file in folder:
        find_folder(folder, file['title'])
        e_text = file.GetContentString()
        d_text = Encryptor.decrypt(e_text.encode(), key)
        file.SetContentString(d_text.decode())
        file.Upload()
Пример #16
0
 def GenPass(self, params):
     wait = True
     #Generate password
     while(wait):
         generatedPassword = enc.GeneratePassword(params)
         console.out(48)
         console.SlowPrint(generatedPassword, 0.03, ">")
         console.out(49)
         inputVal = input("")
         if(inputVal.lower()=="n" or inputVal.lower()=="no"):
             wait = False
     #Give option to save password
     
     console.out(50)
     inputVal = input("")
     if(inputVal.lower()=="y" or inputVal.lower()=="yes"):
         titleSelected = False
         passTitles = File.GetPasswordTitles(self.GetFileEncryptionKey())
         while(not titleSelected):
             console.out(51) #Get user to enter a title
             inputVal = input("")
             if(inputVal.lower() == "c"):
                 return None #Quit routine
             if(passTitles == None or inputVal not in passTitles):
                 titleSelected = True            
         
         state = File.AmmendPasswordFile(inputVal, generatedPassword, self.GetFileEncryptionKey())
         if(state):
             console.PrintList([38, "Use 'EditPass' to add more information to this stored password"], 0.02)
         else:
             console.out(39)    
         
     console.out(2)
Пример #17
0
def reset(key, folder, client_handler, sym_key_filename):
    DriveManager.files_decrypt(key, folder)
    new_key = Encryptor.generate_key()
    with open(sym_key_filename, 'wb') as key_file:
        key_file.write(new_key)
    client_handler.change_key(new_key)
    DriveManager.files_encrypt(new_key, folder)
Пример #18
0
def main():
    '''
        - sets up local Google webserver to automatically receive
          authentication code from user and authorizes by itself.
    '''
    gauth = GoogleAuth()
    gauth.LoadCredentialsFile("credentials.txt")

    if gauth.credentials is None or gauth.access_token_expired:
        # Creates local webserver and auto handles authentication.
        gauth.LocalWebserverAuth()

    else:
        gauth.Authorize()

    gauth.SaveCredentialsFile("credentials.txt")

    # Create GoogleDrive instance with authenticated GoogleAuth instance.
    drive = GoogleDrive(gauth)

    key = Encryptor.generate_key()
    folder = drive.ListFile({
        'q':
        "'//drive folder id' in parents and trashed=false"
    }).GetList()

    #testing if I can get the encryption and decryption properly
    encrypt_all_files(key, folder)
    decrypt_all_files(key, folder)
    list_all_files(folder)
    delete_all_files(folder)
Пример #19
0
    def run(self):
        while True:
            connection = self.listener.accept()
            message = []
            try:
                message = connection.recv()
            except:
                pass
            if len(message) == 3:
                self.lock.acquire()
                if message[0] in self.users:
                    client_address = ('localhost', message[1])
                    response = Client(client_address,
                                      authkey=b'secret password')

                    public_key = KeySaver.load_public_key(message[2])
                    encrypted_key = Encryptor.encrypt_symmetric_key(
                        public_key, self.key)

                    response.send(encrypted_key)
                    response.close()
                else:
                    print('Unauthorised access by %s' % (message[0]))
                self.lock.release()

            connection.close()
Пример #20
0
def encrypt_all_files(key, folder):
    for file1 in folder:
        plain_text = file1.GetContentString()
        encrypted_text = Encryptor.encrypt(plain_text.encode(), key)
        file1.SetContentString(encrypted_text.decode())
        file1.Upload()
        print(encrypted_text)
Пример #21
0
    def __init__(self):
        super(FileNode, self).__init__()
        self.path = ''
        self.md5 = ''

        # 初始化加密器
        self.encryptor_generator = Encryptor.AES_MD5()
Пример #22
0
    def __init__(self, buff):

        self.buff = buff
        self.client = None

        # 初始化加密器
        self.encryptor_generator = Encryptor.AES_MD5()
Пример #23
0
def readBucket(bucketID, maxDataLength):
    if not os.path.exists(home + bucketLoc):
        os.makedirs(home + bucketLoc)

    inputFile = open(home + bucketLoc + str(bucketID),
                     "rb")  # rb = read binary
    #bytesIn = inputFile.read()
    bytesIn = pickle.load(inputFile)
    inputFile.close()
    if encrypt:
        bytesIn = Encryptor.decrypt(bytesIn, key)

    result = []
    while True:
        leafBytes = bytesIn[:4]
        bytesIn = bytesIn[4:]
        if leafBytes == b"":
            break  # break if end of file
        segIDBytes = bytesIn[:4]
        bytesIn = bytesIn[4:]
        dataLength = int.from_bytes(bytesIn[:4], byteorder="little")
        bytesIn = bytesIn[4:]
        data = bytesIn[:dataLength]
        bytesIn = bytesIn[maxDataLength:]
        result.append(
            Block.Block(int.from_bytes(leafBytes, byteorder="little"),
                        int.from_bytes(segIDBytes, byteorder="little"), data))

    return result
Пример #24
0
def CreateSecurityFile(EncrpytedPassKey, AESKey):
    if (DoesProgramFileExist(securityFile)):
        os.remove(GetFileLocation() +
                  securityFile)  #Old file is useless, remove it if it exists
    #Now build file contents
    fileContents = [
        "#Active Session, DO NOT EDIT",
        Encryptor.AESEncrypt("Security_Session_Key", Encryptor.GenerateSALT())
    ]
    encKey = Encryptor.AESEncrypt(
        EncrpytedPassKey, AESKey)  #Again, doesn't need to be overly secure
    fileContents.append(encKey)

    sessionFile = open((GetFileLocation() + securityFile), "w+")
    for x in fileContents:
        sessionFile.write(x + "\n")
    sessionFile.close()
Пример #25
0
def decrypt_all_files(key, folder):
    for file1 in folder:
        find_folder(folder, file1['title'])
        print('title: %s, id: %s' % (file1['title'], file1['id']))
        encrypted_text = file1.GetContentString()
        decrypted_text = Encryptor.decrypt(encrypted_text.encode(), key)
        file1.SetContentString(decrypted_text.decode())
        file1.Upload()
        print(decrypted_text)
Пример #26
0
def ReadSecurityFile(AESKey):
    if (not DoesProgramFileExist(securityFile)):
        return None  #This should never happen (only with tampering)
    try:
        with open((GetFileLocation() + securityFile), "r") as f:
            lines = f.readlines()
        return Encryptor.AESDecrypt(lines[2], AESKey)
    except:
        return None
Пример #27
0
    def __init__(self):
        self.store_path = ''
        self.home_path = ''
        self.download_list = []
        self.local_files_list = []
        self.remove_list = []

        # 初始化加密器
        self.encryptor_generator = Encryptor.AES_MD5()
Пример #28
0
def DeletePassword(passIndex, encryptionKey):
    AESEncryptionKey = Encryptor.BindKey(Encryptor.GetKey(), encryptionKey)
    #Read all from file
    if (not DoesProgramFileExist(passFile)):
        return None
    with open((GetFileLocation() + passFile), "r") as f:
        encDataSet = f.readline()
    data = Encryptor.DecryptFile(encDataSet, AESEncryptionKey)
    #Remove unwanted password
    del data[passIndex]
    try:
        #Re-write file
        encDataSet = Encryptor.EncryptFile(data, AESEncryptionKey)
        with open((GetFileLocation() + passFile), "w") as f:
            f.write(encDataSet)
        return True
    except:
        return False
 def deleteCustomData(self):
     temp_encryptor = Encryptor.Encryptor("")
     if self.DatabaseTable.selectionModel().hasSelection():
         data_id = self.DatabaseTable.currentRow()+1
         temp_encryptor.deleteCustomData(data_id)
         print("tried to delete with id: " + str(data_id))
         self.LoadData()
     else:
         print("Select Credentials to delete")
Пример #30
0
 def jinenastaveniklice(self, data):
     #dela zajimave veci, ale jen v urcitem pripade
     self.cli.generate_shared_secret(int(data.decode()),
                                     echo_return_key=True)
     superklic = str(self.cli.shared_secret)
     xy = hashlib.sha256(superklic.encode()).hexdigest()[:32]
     print("2222222222222222222222222222")
     self.cislo = 2
     print(xy)
     self.mujAES = Encryptor.Encryptor(xy)
Пример #31
0
def GetPasswordTitles(encryptionKey, byGroup="NULL"):
    AESEncryptionKey = Encryptor.BindKey(Encryptor.GetKey(), encryptionKey)
    if (not DoesProgramFileExist(passFile)):
        return None
    with open((GetFileLocation() + passFile), "r") as f:
        encDataSet = f.readline()
    titles = []
    dataSet = Encryptor.DecryptFile(encDataSet, AESEncryptionKey)
    for data in dataSet:
        if (data != "" and data[0] != "#"):
            splitData = SplitString(data, sep2)
            title = splitData[1]
            if (byGroup != "NULL"):
                if (splitData[0].lower() == byGroup.lower()):
                    titles.append(Encryptor.AESDecrypt(title,
                                                       AESEncryptionKey))
            else:
                titles.append(Encryptor.AESDecrypt(title, AESEncryptionKey))
    return titles
Пример #32
0
def writeBucket(bucketID, blocks, maxDataLength):
    if not os.path.exists(home + bucketLoc):
        os.makedirs(home + bucketLoc)
    result = b""
    for block in blocks:
        result += writeBlock(block, maxDataLength)
    
    if encrypt:
        result = Encryptor.encrypt(result, key)
    		
    outputFile = open(home + bucketLoc + str(bucketID), "wb")        # wb = write binary
    #outputFile.write(result)
    pickle.dump(result, outputFile)	
    outputFile.close()
Пример #33
0
def ORAMvsNormal():
    numTests = 1000
    oram = UserFileSys.UserFileSys(1301, 3, 65536, 100, 1.8, 2.0, 2.2, 1)
    oram._oram.autoResize = False
	
    for i in range (2,13):
        createTestFile(1 << i)		
        oram.write("TestFiles/test" + str(1 << i) + ".txt")
        
    total = 0
    totalSize = 0
    for i in range(numTests):
        fileName = getFile()
        totalSize += int(fileName[14:fileName.index(".")])
        start = time.clock()
        oram.read(fileName)
        timeTaken = time.clock() - start    
        total += timeTaken
    print(total)
    print ("Throughput Disk + ORAM + Encryption: " + str(totalSize/total))


    total = 0
    totalSize = 0
    for i in range(numTests):
        fileName = getFile()
        totalSize += int(fileName[14:fileName.index(".")])
        inputFile = open(fileName, "rb")
        data = inputFile.read()
        inputFile.close()
        start = time.clock()
        data = Encryptor.encrypt(data, key)
        outputFile = open(fileName[:-4] + "_encrypted.txt", "wb")
        pickle.dump(data, outputFile)
        outputFile.close()
        inputFile = open(fileName[:-4] + "_encrypted.txt", "rb")
        data = pickle.load(inputFile)
        inputFile.close()
        data = Encryptor.decrypt(data, key)
        timeTaken = time.clock() - start
        total += timeTaken
    print(total)
    print("Throughput Disk + Encryption: " + str(totalSize/total))

        
    total = 0
    totalSize = 0
    for i in range(numTests):
        start = time.clock()
        fileName = getFile()
        totalSize += int(fileName[14:fileName.index(".")])
        file = open(fileName, "r")
        data = file.read()
        file.close()
        file = open(fileName, "w")
        file.write(data)
        file.close()		
        total += (time.clock()-start)
    avg = total/numTests
    print(total)
    print ("Throughput Disk: " + str(totalSize/total))