Twofish.swift 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Twofish.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 Twofish
  21. public final class Twofish: Cipher {
  22. private var context: twofish_context
  23. public init(key: Bytes, iv: Bytes) throws {
  24. guard key.lenght <= TWOFISH_KEYSIZE else {
  25. throw CryptoError.keyLenght(expecting: "Less or equal to \(TWOFISH_KEYSIZE)", got: key.lenght)
  26. }
  27. guard iv.lenght == TWOFISH_IVSIZE else {
  28. throw CryptoError.ivLenght(expecting: "Equal to \(TWOFISH_IVSIZE)", got: iv.lenght)
  29. }
  30. context = twofish_context()
  31. twofish_setup(&context, key.rawValue, iv.rawValue, twofish_options_default)
  32. }
  33. public func encrypt(data: Bytes) throws -> Bytes {
  34. let output_length = twofish_get_output_length(&context, lenght(data))
  35. var out = Bytes(lenght: Int(output_length))
  36. twofish_encrypt(&context, data.rawValue, lenght(data), &out.rawValue, output_length)
  37. return out
  38. }
  39. public func decrypt(data: Bytes) throws -> Bytes {
  40. var out = Bytes(lenght: data.lenght)
  41. var output_length = data.lenght
  42. twofish_decrypt(&context, data.rawValue, output_length, &out.rawValue, &output_length)
  43. return out.prefix(output_length)
  44. }
  45. }