Salsa20.swift 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Salsa20.swift
  2. // This file is part of KeePass.swift
  3. //
  4. // Copyright © 2021 Maxime Epain. All rights reserved.
  5. //
  6. // KeePass.swift 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. // KeePass.swift 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 KeePass.swift. If not, see <https://www.gnu.org/licenses/>.
  18. import Binary
  19. import Foundation
  20. import Sodium
  21. public final class Salsa20 {
  22. public let key: Bytes
  23. public let nonce: Bytes
  24. public init(key: Bytes, iv nonce: Bytes) throws {
  25. guard key.lenght == crypto_stream_salsa20_KEYBYTES else {
  26. throw CryptoError.keyLenght(expecting: "Equal \(crypto_stream_salsa20_KEYBYTES)", got: key.lenght)
  27. }
  28. guard nonce.lenght == crypto_stream_salsa20_NONCEBYTES else {
  29. throw CryptoError.ivLenght(expecting: "Equal \(crypto_stream_salsa20_NONCEBYTES)", got: nonce.lenght)
  30. }
  31. self.key = key
  32. self.nonce = nonce
  33. }
  34. }
  35. extension Salsa20: Cipher {
  36. public func encrypt(data: Bytes) throws -> Bytes {
  37. var out = Bytes(lenght: lenght(data))
  38. crypto_stream_salsa20_xor(&out.rawValue, data.rawValue, lenght(data), nonce.rawValue, key.rawValue)
  39. return out
  40. }
  41. public func decrypt(data: Bytes) throws -> Bytes {
  42. try encrypt(data: data)
  43. }
  44. }