KeePass.swift 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 -> some Database {
  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: UInt32 = try stream.read()
  36. switch format {
  37. case KDB.FileFormat:
  38. return AnyDatabase( try KDB.Database(from: stream, compositeKey: compositeKey) )
  39. case KDBX.BetaFileFormat, KDBX.FileFormat:
  40. return AnyDatabase ( try KDBX.File(from: stream, compositeKey: compositeKey) )
  41. default:
  42. throw KeePassError.invalidFileFormat
  43. }
  44. }
  45. public static func open(contentOf xml: URL) throws -> some Database {
  46. try KDBX.File(xml: xml)
  47. }
  48. }