Argon2.swift 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Argon2.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 Argon2
  21. public final class Argon2: KeyDerivation {
  22. public let salt: Bytes
  23. public let parallelism: UInt32
  24. public let memory: UInt32
  25. public let iterations: UInt32
  26. public let version: UInt32
  27. public init(salt: Bytes, parallelism: UInt32, memory: UInt32, iterations: UInt32, version: UInt32) {
  28. self.salt = salt
  29. self.parallelism = parallelism
  30. self.memory = memory
  31. self.iterations = iterations
  32. self.version = version
  33. }
  34. public func derive(key: Bytes) throws -> Bytes {
  35. var out = Bytes(lenght: 32)
  36. let result = argon2_hash(iterations,
  37. memory,
  38. parallelism,
  39. key.rawValue, key.lenght,
  40. salt.rawValue, salt.lenght,
  41. &out.rawValue, out.lenght,
  42. nil, 0,
  43. Argon2_d,
  44. version)
  45. let code = argon2_error_codes(result)
  46. guard code == ARGON2_OK else { throw CryptoError.argon(code) }
  47. return out
  48. }
  49. }