StreamEncryptor.swift 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. // Accumulated bytes. Not all processed bytes.
  19. private var accumulated = Array<UInt8>(reserveCapacity: 16)
  20. private var lastBlockRemainder = 0
  21. init(blockSize: Int, padding: Padding, _ worker: CipherModeWorker) throws {
  22. self.blockSize = blockSize
  23. self.padding = padding
  24. self.worker = worker
  25. }
  26. // MARK: Updatable
  27. public func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool) throws -> Array<UInt8> {
  28. accumulated = Array(bytes)
  29. if isLast {
  30. // CTR doesn't need padding. Really. Add padding to the last block if really want. but... don't.
  31. accumulated = padding.add(to: accumulated, blockSize: blockSize - lastBlockRemainder)
  32. }
  33. var encrypted = Array<UInt8>(reserveCapacity: bytes.count)
  34. for chunk in accumulated.batched(by: blockSize) {
  35. encrypted += worker.encrypt(block: chunk)
  36. }
  37. // omit unecessary calculation if not needed
  38. if padding != .noPadding {
  39. lastBlockRemainder = encrypted.count.quotientAndRemainder(dividingBy: blockSize).remainder
  40. }
  41. if var finalizingWorker = worker as? FinalizingModeWorker, isLast == true {
  42. encrypted = try finalizingWorker.finalize(encrypt: encrypted.slice)
  43. }
  44. return encrypted
  45. }
  46. func seek(to: Int) throws {
  47. fatalError("Not supported")
  48. }
  49. }