StreamEncryptor.swift 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // CryptoSwift
  2. //
  3. // Copyright (C) 2014-2018 Marcin Krzyżanowski <marcin@krzyzanowskim.com>
  4. // This software is provided 'as-is', without any express or implied warranty.
  5. //
  6. // In no event will the authors be held liable for any damages arising from the use of this software.
  7. //
  8. // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
  9. //
  10. // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
  11. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  12. // - This notice may not be removed or altered from any source or binary distribution.
  13. //
  14. final class StreamEncryptor: Cryptor, Updatable {
  15. private let blockSize: Int
  16. private var worker: CipherModeWorker
  17. private let padding: Padding
  18. private var lastBlockRemainder = 0
  19. init(blockSize: Int, padding: Padding, _ worker: CipherModeWorker) throws {
  20. self.blockSize = blockSize
  21. self.padding = padding
  22. self.worker = worker
  23. }
  24. // MARK: Updatable
  25. public func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool) throws -> Array<UInt8> {
  26. var accumulated = Array(bytes)
  27. if isLast {
  28. // CTR doesn't need padding. Really. Add padding to the last block if really want. but... don't.
  29. accumulated = self.padding.add(to: accumulated, blockSize: self.blockSize - self.lastBlockRemainder)
  30. }
  31. var encrypted = Array<UInt8>(reserveCapacity: bytes.count)
  32. for chunk in accumulated.batched(by: self.blockSize) {
  33. encrypted += self.worker.encrypt(block: chunk)
  34. }
  35. // omit unecessary calculation if not needed
  36. if self.padding != .noPadding {
  37. self.lastBlockRemainder = encrypted.count.quotientAndRemainder(dividingBy: self.blockSize).remainder
  38. }
  39. if var finalizingWorker = worker as? FinalizingEncryptModeWorker, isLast == true {
  40. encrypted = Array(try finalizingWorker.finalize(encrypt: encrypted.slice))
  41. }
  42. return encrypted
  43. }
  44. func seek(to: Int) throws {
  45. fatalError("Not supported")
  46. }
  47. }