KeePass.swift 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // KeePass.swift
  2. // This file is part of KeePassKit.
  3. //
  4. // Copyright © 2019 Maxime Epain. All rights reserved.
  5. //
  6. // KeePassKit is free software: you can redistribute it and/or modify
  7. // it under the terms of the GNU General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // KeePassKit is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU General Public License
  17. // along with KeePassKit. If not, see <https://www.gnu.org/licenses/>.
  18. import Foundation
  19. import Binary
  20. import KDB
  21. import KDBX
  22. public let FileSignature: UInt32 = 0x9AA2D903
  23. public enum FileFormat: UInt32, Streamable {
  24. case kdb = 0xB54BFB65
  25. case prekdbx = 0xB54BFB66
  26. case kdbx = 0xB54BFB67
  27. }
  28. public class KeePass {
  29. public static func open(contentOf url: URL, compositeKey: CompositeKey) throws -> AnyDatabase {
  30. let bytes = try Bytes(contentsOf: url)
  31. let stream = Input(bytes: bytes)
  32. guard try stream.read() == FileSignature else {
  33. throw KeePassError.invalidFileFormat
  34. }
  35. let format = try stream.read() as FileFormat
  36. switch format {
  37. case .kdb:
  38. return AnyDatabase( try KDB.Database(from: stream, compositeKey: compositeKey) )
  39. case .prekdbx, .kdbx:
  40. return AnyDatabase ( try KDBX.File(from: stream, compositeKey: compositeKey) )
  41. }
  42. }
  43. public static func open(contentOf xml: URL) throws -> AnyDatabase {
  44. return AnyDatabase ( try KDBX.File(xml: xml) )
  45. }
  46. }