瀏覽代碼

Update server side file encryption

kevin 8 月之前
父節點
當前提交
be66c7dfa3

+ 2 - 1
NexilisLite/NexilisLite/Source/Download.swift

@@ -88,7 +88,8 @@ public class Download {
                             let documentDir = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
                             let url = documentDir.appendingPathComponent(filename)
                             //print("write file \(url.path)")
-                            try successResponse.write(to: url)
+                            let dResponse = try FileEncryption.shared.decryptToMemory(successResponse, MasterKeyUtil.shared.getServerKey())
+                            try dResponse.write(to: url)
                             Nexilis.removeDownload(forKey: filename)
                             completion(filename,100)
                         }

+ 43 - 4
NexilisLite/NexilisLite/Source/FileEncryption.swift

@@ -33,6 +33,46 @@ public class FileEncryption {
         }
     }
     
+    func readSecure(filename: String) throws -> Data? {
+        let fileManager = FileManager.default
+        let documentDir = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
+        let secureDir = documentDir.appendingPathComponent("secure")
+        let fileURL = secureDir.appendingPathComponent(filename)
+        return try decryptToMemory(fileURL)
+    }
+    
+    func writeSecure(filename: String? = nil, fileURL : URL? = nil) throws -> [Any]? {
+        let fileManager = FileManager.default
+        let documentDir = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
+        let secureDir = documentDir.appendingPathComponent("secure")
+        guard let inputFilename = filename ?? fileURL?.lastPathComponent else { return nil }
+        let inputURL = fileURL ?? documentDir.appendingPathComponent(inputFilename)
+        let outputURL = secureDir.appendingPathComponent(inputFilename)
+        guard let data = encryptFile(inputURL) else { return nil }
+        try data.write(to: outputURL)
+        do {
+            try fileManager.removeItem(at: inputURL)
+            print("File deleted successfully")
+        } catch {
+            print("Error deleting file: \(error)")
+        }
+        return [outputURL.lastPathComponent, outputURL]
+    }
+    
+    func isSecureExists(filename: String) -> Bool {
+        let fileManager = FileManager.default
+        do {
+            let documentDir = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
+            let secureDir = documentDir.appendingPathComponent("secure")
+            let outputURL = secureDir.appendingPathComponent(filename)
+            return fileManager.fileExists(atPath: outputURL.path)
+        } catch {
+            return false
+        }
+        
+        
+    }
+    
     func wipeData(_ data: inout Data) {
         data.resetBytes(in: 0..<data.count)
         data.count = 0
@@ -97,7 +137,7 @@ public class FileEncryption {
             return try AES.GCM.open(sealedBox, using: MasterKeyUtil.shared.getMasterKey())
         } catch {
             print("Decryption failed: \(error)")
-            return nil
+            return encryptedData
         }
     }
 
@@ -106,10 +146,9 @@ public class FileEncryption {
         return decryptToMemory(encryptedData)
     }
     
-    func decryptToMemory(_ encryptedURL: URL, _ key: SymmetricKey) throws -> Data? {
+    func decryptToMemory(_ encryptedData: Data, _ key: SymmetricKey) throws -> Data {
         let keyData = key.withUnsafeBytes { Data($0) }
         
-        let encryptedData = try Data(contentsOf: encryptedURL)
         let iv = encryptedData.prefix(kCCBlockSizeAES128)
         let cipherText = encryptedData.suffix(from: kCCBlockSizeAES128)
         let decryptedData = Data(count: cipherText.count + kCCBlockSizeAES128)
@@ -136,7 +175,7 @@ public class FileEncryption {
         }
 
         guard status == kCCSuccess else {
-            throw NSError(domain: "DecryptionError", code: Int(status), userInfo: nil)
+            return encryptedData
         }
 
         finalData.count = numBytesDecrypted

+ 19 - 4
NexilisLite/NexilisLite/Source/Network.swift

@@ -195,18 +195,33 @@ public class Network {
     public func uploadHTTP(_ endUrl: String, files: [URL] = [], filename: [String] = [], parameters: [String : Any] = [:], completion: @escaping (Bool, Double, [String:Any]?)->()) -> UploadRequest {
         
         var filesIn = [URL]()
+        var filesTempServer = [URL]()
         filesIn.append(contentsOf: files)
-        
         if !filename.isEmpty {
             do {
                 let fileManager = FileManager.default
                 let documentDir = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
+                let tempDir = documentDir.appendingPathComponent("temp")
+                if !fileManager.fileExists(atPath: tempDir.path) {
+                    do {
+                        try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true, attributes: nil)
+                    } catch {
+                        print("Error creating directory: \(error)")
+                    }
+                }
                 for name in filename {
                     let fileDir = documentDir.appendingPathComponent(name)
                     let path = fileDir.path
                     if FileManager.default.fileExists(atPath: path) {
                         let fileURL = URL(fileURLWithPath: path)
+                        let filenameServer = "\(name)"
+                        let fileDirServer = tempDir.appendingPathComponent(filenameServer)
+                        let fileURLServer = URL(fileURLWithPath: fileDirServer.path)
+                        try FileEncryption.shared.encryptFile(fileURL, fileURLServer, MasterKeyUtil.shared.getServerKey())
+//                        let dataSecure = try FileEncryption.shared.encryptFile(fileURL)
+//                        dataSecure?.write(to: fileURLSecure)
                         filesIn.append(fileURL)
+                        filesTempServer.append(fileURLServer)
                     }
                 }
             }
@@ -237,8 +252,8 @@ public class Network {
                 //print(multipartFormData)
             }
             
-            for i in 0..<filesIn.count {
-                multipartFormData.append(filesIn[i], withName: "file\(i+1)", fileName: filesIn[i].lastPathComponent, mimeType: "application/octet-stream")
+            for i in 0..<filesTempServer.count {
+                multipartFormData.append(filesTempServer[i], withName: "file\(i+1)", fileName: filesTempServer[i].lastPathComponent, mimeType: "application/octet-stream")
                 Nexilis.putUploadFile(forKey: filesIn[i].lastPathComponent, uploader: self)
                 //print(multipartFormData)
             }
@@ -247,7 +262,7 @@ public class Network {
         .responseJSON { result in
             if let response = result.response, response.statusCode == 200, let successResponse = result.value as? [String:Any] {
                 //print("Response success")
-                for url in filesIn {
+                for url in filesTempServer {
                     Nexilis.removeUploadFile(forKey: url.lastPathComponent)
                 }
                 completion(true,100,successResponse)