NCEntoToEndInterface.swift 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. //
  2. // NCEntoToEndInterface.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 03/04/17.
  6. // Copyright © 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import Foundation
  24. class NCEntoToEndInterface : NSObject, OCNetworkingDelegate {
  25. struct e2eMetadata: Codable {
  26. struct metadataKey: Codable {
  27. let metadataKeys: [String: String]
  28. let version: Int
  29. }
  30. struct sharingKey: Codable {
  31. let recipient: [String: String]
  32. }
  33. struct filesKey: Codable {
  34. let initializationVector: String
  35. let authenticationTag: String
  36. let metadataKey: Int
  37. let encrypted: String
  38. }
  39. let files: [String: filesKey]
  40. let metadata: metadataKey
  41. let sharing: sharingKey?
  42. }
  43. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  44. override init() {
  45. }
  46. // --------------------------------------------------------------------------------------------
  47. // MARK: Initialize
  48. // --------------------------------------------------------------------------------------------
  49. @objc func initEndToEndEncryption() {
  50. // Clear all keys
  51. CCUtility.clearAllKeysEnd(toEnd: appDelegate.activeAccount)
  52. let metadataNet: CCMetadataNet = CCMetadataNet.init(account: appDelegate.activeAccount)
  53. metadataNet.action = actionGetEndToEndPublicKeys
  54. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  55. }
  56. func getPrivateKeyCipher() {
  57. let metadataNet: CCMetadataNet = CCMetadataNet.init(account: appDelegate.activeAccount)
  58. metadataNet.action = actionGetEndToEndPrivateKeyCipher
  59. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  60. }
  61. func getPublicKeyServer() {
  62. let metadataNet: CCMetadataNet = CCMetadataNet.init(account: appDelegate.activeAccount)
  63. metadataNet.action = actionGetEndToEndServerPublicKey
  64. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  65. }
  66. // --------------------------------------------------------------------------------------------
  67. // MARK: Manage PublicKey
  68. // --------------------------------------------------------------------------------------------
  69. func getEndToEndPublicKeysSuccess(_ metadataNet: CCMetadataNet!) {
  70. CCUtility.setEndToEndPublicKey(appDelegate.activeAccount, publicKey: metadataNet.key)
  71. // Request PrivateKey chiper to Server
  72. getPrivateKeyCipher()
  73. }
  74. func getEndToEndPublicKeysFailure(_ metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  75. switch errorCode {
  76. case 400:
  77. appDelegate.messageNotification("E2E get publicKey", description: "bad request: unpredictable internal error", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  78. case 404:
  79. guard let csr = NCEndToEndEncryption.sharedManager().createCSR(appDelegate.activeUserID, directoryUser: appDelegate.directoryUser) else {
  80. appDelegate.messageNotification("E2E Csr", description: "Error to create Csr", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  81. return
  82. }
  83. let metadataNet: CCMetadataNet = CCMetadataNet.init(account: appDelegate.activeAccount)
  84. metadataNet.action = actionSignEndToEndPublicKey;
  85. metadataNet.key = csr;
  86. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  87. case 409:
  88. appDelegate.messageNotification("E2E get publicKey", description: "forbidden: the user can't access the public keys", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  89. default:
  90. appDelegate.messageNotification("E2E get publicKey", description: message as String!, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  91. }
  92. }
  93. func signEnd(toEndPublicKeySuccess metadataNet: CCMetadataNet!) {
  94. CCUtility.setEndToEndPublicKey(appDelegate.activeAccount, publicKey: metadataNet.key)
  95. // Request PrivateKey chiper to Server
  96. getPrivateKeyCipher()
  97. }
  98. func signEnd(toEndPublicKeyFailure metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  99. switch errorCode {
  100. case 400:
  101. appDelegate.messageNotification("E2E sign publicKey", description: "bad request: unpredictable internal error", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  102. case 409:
  103. appDelegate.messageNotification("E2E sign publicKey", description: "conflict: a public key for the user already exists", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  104. default:
  105. appDelegate.messageNotification("E2E sign publicKey", description: message as String!, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  106. }
  107. }
  108. func deleteEnd(toEndPublicKeySuccess metadataNet: CCMetadataNet!) {
  109. appDelegate.messageNotification("E2E delete publicKey", description: "Success", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.success, errorCode: 0)
  110. }
  111. func deleteEnd(toEndPublicKeyFailure metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  112. appDelegate.messageNotification("E2E delete publicKey", description: message, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  113. }
  114. // --------------------------------------------------------------------------------------------
  115. // MARK: Manage PrivateKey
  116. // --------------------------------------------------------------------------------------------
  117. func getEndToEndPrivateKeyCipherSuccess(_ metadataNet: CCMetadataNet!) {
  118. // request Passphrase
  119. var passphraseTextField: UITextField?
  120. let alertController = UIAlertController(title: NSLocalizedString("_e2e_passphrase_request_title_", comment: ""), message: NSLocalizedString("_e2e_passphrase_request_message_", comment: ""), preferredStyle: .alert)
  121. //TEST
  122. /*
  123. if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
  124. let fileURL = dir.appendingPathComponent("privatekey.txt")
  125. //writing
  126. do {
  127. try metadataNet.key.write(to: fileURL, atomically: false, encoding: .utf8)
  128. }
  129. catch {/* error handling here */}
  130. }
  131. */
  132. //
  133. let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
  134. let passphrase = passphraseTextField?.text
  135. let publicKey = CCUtility.getEndToEndPublicKey(self.appDelegate.activeAccount)
  136. guard let privateKey = (NCEndToEndEncryption.sharedManager().decryptPrivateKey(metadataNet.key, passphrase: passphrase, publicKey: publicKey)) else {
  137. self.appDelegate.messageNotification("E2E decrypt privateKey", description: "Serious internal error to decrypt Private Key", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: 0)
  138. return
  139. }
  140. // privateKey
  141. print(privateKey)
  142. // Save to keychain
  143. CCUtility.setEndToEndPrivateKey(self.appDelegate.activeAccount, privateKey: privateKey)
  144. CCUtility.setEndToEndPassphrase(self.appDelegate.activeAccount, passphrase:passphrase)
  145. // request publicKey Server()
  146. self.getPublicKeyServer()
  147. })
  148. let cancel = UIAlertAction(title: "Cancel", style: .cancel) { (action) -> Void in
  149. }
  150. alertController.addAction(ok)
  151. alertController.addAction(cancel)
  152. alertController.addTextField { (textField) -> Void in
  153. passphraseTextField = textField
  154. passphraseTextField?.placeholder = "Enter passphrase (12 words)"
  155. }
  156. appDelegate.activeMain.present(alertController, animated: true)
  157. }
  158. func getEndToEndPrivateKeyCipherFailure(_ metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  159. switch errorCode {
  160. case 400:
  161. appDelegate.messageNotification("E2E get privateKey", description: "bad request: unpredictable internal error", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  162. case 404:
  163. // message
  164. let e2ePassphrase = NYMnemonic.generateString(128, language: "english")
  165. let message = "\n" + NSLocalizedString("_e2e_settings_view_passphrase_", comment: "") + "\n\n" + e2ePassphrase!
  166. let alertController = UIAlertController(title: NSLocalizedString("_e2e_settings_title_", comment: ""), message: NSLocalizedString(message, comment: ""), preferredStyle: .alert)
  167. let OKAction = UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default) { action in
  168. var privateKey : NSString?
  169. guard let privateKeyChiper = NCEndToEndEncryption.sharedManager().encryptPrivateKey(self.appDelegate.activeUserID, directoryUser: self.appDelegate.directoryUser, passphrase: e2ePassphrase, privateKey: &privateKey) else {
  170. self.appDelegate.messageNotification("E2E privateKey", description: "Serious internal error to create PrivateKey chiper", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  171. return
  172. }
  173. let metadataNet: CCMetadataNet = CCMetadataNet.init(account: self.appDelegate.activeAccount)
  174. metadataNet.action = actionStoreEndToEndPrivateKeyCipher
  175. metadataNet.key = privateKey! as String
  176. metadataNet.keyCipher = privateKeyChiper
  177. metadataNet.password = e2ePassphrase
  178. self.appDelegate.addNetworkingOperationQueue(self.appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  179. }
  180. alertController.addAction(OKAction)
  181. appDelegate.activeMain.present(alertController, animated: true)
  182. case 409:
  183. appDelegate.messageNotification("E2E get privateKey", description: "forbidden: the user can't access the private key", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  184. default:
  185. appDelegate.messageNotification("E2E get privateKey", description: message as String!, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  186. }
  187. }
  188. func storeEnd(toEndPrivateKeyCipherSuccess metadataNet: CCMetadataNet!) {
  189. CCUtility.setEndToEndPrivateKey(appDelegate.activeAccount, privateKey: metadataNet.key)
  190. CCUtility.setEndToEndPassphrase(appDelegate.activeAccount, passphrase:metadataNet.password)
  191. // request publicKey Server()
  192. self.getPublicKeyServer()
  193. }
  194. func storeEnd(toEndPrivateKeyCipherFailure metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  195. switch errorCode {
  196. case 400:
  197. appDelegate.messageNotification("E2E store privateKey", description: "bad request: unpredictable internal error", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  198. case 409:
  199. appDelegate.messageNotification("E2E store privateKey", description: "conflict: a private key for the user already exists", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  200. default:
  201. appDelegate.messageNotification("E2E store privateKey", description: message as String!, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  202. }
  203. }
  204. func deleteEnd(toEndPrivateKeySuccess metadataNet: CCMetadataNet!) {
  205. appDelegate.messageNotification("E2E delete privateKey", description: "Success", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.success, errorCode: 0)
  206. }
  207. func deleteEnd(toEndPrivateKeyFailure metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  208. appDelegate.messageNotification("E2E delete privateKey", description: message, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  209. }
  210. // --------------------------------------------------------------------------------------------
  211. // MARK: Manage Server PublicKey
  212. // --------------------------------------------------------------------------------------------
  213. func getEndToEndServerPublicKeySuccess(_ metadataNet: CCMetadataNet!) {
  214. CCUtility.setEndToEndPublicKeyServer(appDelegate.activeAccount, publicKey: metadataNet.key)
  215. // All OK Activated flsg on Manage EndToEnd Encryption
  216. NotificationCenter.default.post(name: Notification.Name("reloadManageEndToEndEncryption"), object: nil)
  217. }
  218. func getEndToEndServerPublicKeyFailure(_ metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  219. switch (errorCode) {
  220. case 400:
  221. appDelegate.messageNotification("E2E Server publicKey", description: "bad request: unpredictable internal error", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  222. case 404:
  223. appDelegate.messageNotification("E2E Server publicKey", description: "Server publickey doesn't exists", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  224. case 409:
  225. appDelegate.messageNotification("E2E Server publicKey", description: "forbidden: the user can't access the Server publickey", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  226. default:
  227. appDelegate.messageNotification("E2E Server publicKey", description: message as String!, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  228. }
  229. }
  230. // --------------------------------------------------------------------------------------------
  231. // MARK: Manage Mark/Delete Encrypted Folder
  232. // --------------------------------------------------------------------------------------------
  233. @objc func markEndToEndFolderEncrypted(_ url: String, fileID: String, token: String?) -> Bool {
  234. var token : NSString? = token as NSString?
  235. if let error = NCNetworkingSync.sharedManager().lockEnd(toEndFolderEncrypted: appDelegate.activeUser, userID: appDelegate.activeUserID, password: appDelegate.activePassword, url: url , fileID: fileID, token: &token) as NSError? {
  236. appDelegate.messageNotification("E2E Mark folder as encrypted", description: error.localizedDescription+" code \(error.code)", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: error.code)
  237. return false
  238. }
  239. if let error = NCNetworkingSync.sharedManager().markEnd(toEndFolderEncrypted: appDelegate.activeUser, userID: appDelegate.activeUserID, password: appDelegate.activePassword, url: url, fileID: fileID) as NSError? {
  240. appDelegate.messageNotification("E2E Mark folder as encrypted", description: error.localizedDescription+" code \(error.code)", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: error.code)
  241. return false
  242. }
  243. if let error = NCNetworkingSync.sharedManager().unlockEnd(toEndFolderEncrypted: appDelegate.activeUser, userID: appDelegate.activeUserID, password: appDelegate.activePassword, url: url, fileID: fileID, token: token! as String) as NSError? {
  244. appDelegate.messageNotification("E2E Mark folder as encrypted", description: error.localizedDescription+" code \(error.code)", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: error.code)
  245. return false
  246. }
  247. return true
  248. }
  249. @objc func deletemarkEndToEndFolderEncrypted(_ url: String, fileID: String, token: String?) -> Bool {
  250. var token : NSString? = token as NSString?
  251. if let error = NCNetworkingSync.sharedManager().lockEnd(toEndFolderEncrypted: appDelegate.activeUser, userID: appDelegate.activeUserID, password: appDelegate.activePassword, url: url , fileID: fileID, token: &token) as NSError? {
  252. appDelegate.messageNotification("E2E Remove mark folder as encrypted", description: error.localizedDescription+" code \(error.code)", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: error.code)
  253. return false
  254. }
  255. if let error = NCNetworkingSync.sharedManager().deletemarkEnd(toEndFolderEncrypted: appDelegate.activeUser, userID: appDelegate.activeUserID, password: appDelegate.activePassword, url: url, fileID: fileID) as NSError? {
  256. appDelegate.messageNotification("E2E Remove mark folder as encrypted", description: error.localizedDescription+" code \(error.code)", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: error.code)
  257. return false
  258. }
  259. if let error = NCNetworkingSync.sharedManager().unlockEnd(toEndFolderEncrypted: appDelegate.activeUser, userID: appDelegate.activeUserID, password: appDelegate.activePassword, url: url, fileID: fileID, token: token! as String) as NSError? {
  260. appDelegate.messageNotification("E2E Remove mark folder as encrypted", description: error.localizedDescription+" code \(error.code)", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: error.code)
  261. return false
  262. }
  263. return true
  264. }
  265. // --------------------------------------------------------------------------------------------
  266. // MARK: Manage Metadata
  267. // --------------------------------------------------------------------------------------------
  268. func getEndToEndMetadataSuccess(_ metadataNet: CCMetadataNet!) {
  269. guard let privateKey = CCUtility.getEndToEndPrivateKey(appDelegate.activeAccount) else {
  270. appDelegate.messageNotification("E2E Get Metadata Success", description: "Serious internal error: PrivareKey not found", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: 0)
  271. return
  272. }
  273. guard let main = appDelegate.listMainVC[metadataNet.serverUrl] as? CCMain else {
  274. appDelegate.messageNotification("E2E Get Metadata Success", description: "Serious internal error: Main not found", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: 0)
  275. return
  276. }
  277. guard let e2eMetaDataJSON = decoderMetadata(metadataNet.encryptedMetadata, privateKey: privateKey) else {
  278. return
  279. }
  280. // Assign e2eMetaDataJSON for ServerUrl Main
  281. main.e2eMetaDataJSON = e2eMetaDataJSON
  282. // Reload data source
  283. main.reloadDatasource(metadataNet.serverUrl)
  284. }
  285. func getEndToEndMetadataFailure(_ metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  286. // Unauthorized
  287. if (errorCode == kOCErrorServerUnauthorized) {
  288. appDelegate.openLoginView(appDelegate.activeMain, loginType: loginModifyPasswordUser)
  289. } else if (errorCode != 404) {
  290. appDelegate.messageNotification("E2E Get metadata", description: message as String!, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  291. }
  292. }
  293. @objc func getEndToEndMetadata(_ metadata: tableMetadata) {
  294. let metadataNet: CCMetadataNet = CCMetadataNet.init(account: appDelegate.activeAccount)
  295. metadataNet.action = actionGetEndToEndMetadata;
  296. metadataNet.fileID = metadata.fileID;
  297. guard let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID) else {
  298. appDelegate.messageNotification("E2E Get metadata", description: "Serious internal error: ServerURL not found", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: 0)
  299. return
  300. }
  301. metadataNet.serverUrl = serverUrl
  302. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  303. }
  304. // --------------------------------------------------------------------------------------------
  305. // MARK: Encode / Decode JSON Metadata
  306. // --------------------------------------------------------------------------------------------
  307. @objc func encoderMetadata(_ recordsE2eEncryption: [tableE2eEncryption], publicKey: String, version: Int) -> String? {
  308. let jsonEncoder = JSONEncoder.init()
  309. var files = [String: e2eMetadata.filesKey]()
  310. // Create "files"
  311. for recordE2eEncryption in recordsE2eEncryption {
  312. let plainEncrypted = recordE2eEncryption.key+"|"+recordE2eEncryption.fileName+"|"+recordE2eEncryption.mimeType+"|"+",\(recordE2eEncryption.version)"
  313. guard let encryptedData = NCEndToEndEncryption.sharedManager().encryptAsymmetricString(plainEncrypted, publicKey: publicKey) else {
  314. appDelegate.messageNotification("E2E encore metadata", description: "Serious internal error in creation \"encrypted\" key", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: 0)
  315. return nil
  316. }
  317. let e2eMetadataFilesKey = e2eMetadata.filesKey(initializationVector: recordE2eEncryption.initializationVector, authenticationTag: recordE2eEncryption.authenticationTag, metadataKey: 0, encrypted: String(data: encryptedData, encoding: .utf8)!)
  318. files.updateValue(e2eMetadataFilesKey, forKey: recordE2eEncryption.fileNameIdentifier)
  319. }
  320. // Create "metadata"
  321. let e2eMetadataKey = e2eMetadata.metadataKey(metadataKeys: ["0":"dcccecfvdfvfvsfdvefvefvefvefvefv"], version: version)
  322. // Create final Json e2emetadata
  323. let e2emetadata = e2eMetadata(files: files, metadata: e2eMetadataKey, sharing: nil)
  324. do {
  325. let jsonData = try jsonEncoder.encode(e2emetadata)
  326. let jsonString = String(data: jsonData, encoding: .utf8)
  327. print("JSON String : " + jsonString!)
  328. return jsonString
  329. } catch let error {
  330. appDelegate.messageNotification("E2E encore metadata", description: "Serious internal error in encoding metadata ("+error.localizedDescription+")", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: 0)
  331. }
  332. return nil
  333. }
  334. // let dataDecoded : NSData = NSData(base64Encoded: encrypted, options: NSData.Base64DecodingOptions(rawValue: 0))!
  335. @objc func decoderMetadata(_ e2eMetaDataJSON: String, privateKey: String) -> String? {
  336. let jsonDecoder = JSONDecoder.init()
  337. let data = e2eMetaDataJSON.data(using: .utf8)
  338. do {
  339. let response = try jsonDecoder.decode(e2eMetadata.self, from: data!)
  340. let files = response.files
  341. let metadata = response.metadata
  342. //let sharing = response.sharing
  343. var planMetadataKeys = [String:String]()
  344. for metadataKeys in metadata.metadataKeys {
  345. guard let metadataKeysData : NSData = NSData(base64Encoded: metadataKeys.value, options: NSData.Base64DecodingOptions(rawValue: 0)) else {
  346. appDelegate.messageNotification("E2E decode metadata", description: "Serious internal error in decoding metadata", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: 0)
  347. return nil
  348. }
  349. guard let metadataKey = NCEndToEndEncryption.sharedManager().decryptAsymmetricData(metadataKeysData as Data!, privateKey: privateKey) else {
  350. appDelegate.messageNotification("E2E decode metadata", description: "Serious internal error in decoding metadata", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: 0)
  351. return nil
  352. }
  353. planMetadataKeys[metadataKeys.key] = metadataKey
  354. }
  355. for file in files {
  356. let fileNameIdentifier = file.key
  357. let element = file.value as e2eMetadata.filesKey
  358. let iv = element.initializationVector
  359. let tag = element.authenticationTag
  360. let encrypted = element.encrypted
  361. let metadataKeysKey = element.metadataKey
  362. let key = planMetadataKeys["\(metadataKeysKey)"]
  363. guard let decyptedMetadata = NCEndToEndEncryption.sharedManager().decryptMetadata(encrypted, privateKey: key, initializationVector: iv, authenticationTag: tag) else {
  364. appDelegate.messageNotification("E2E decode metadata", description: "Serious internal error in decoding metadata", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: 0)
  365. return nil
  366. }
  367. print(decyptedMetadata)
  368. }
  369. print(response)
  370. } catch let error {
  371. appDelegate.messageNotification("E2E decode metadata", description: "Serious internal error in decoding metadata ("+error.localizedDescription+")", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: 0)
  372. return nil
  373. }
  374. return e2eMetaDataJSON
  375. }
  376. }