2
0

StreamEncryptor.swift 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 = padding.add(to: accumulated, blockSize: blockSize - lastBlockRemainder)
  30. }
  31. var encrypted = Array<UInt8>(reserveCapacity: bytes.count)
  32. for chunk in accumulated.batched(by: blockSize) {
  33. encrypted += worker.encrypt(block: chunk)
  34. }
  35. // omit unecessary calculation if not needed
  36. if padding != .noPadding {
  37. lastBlockRemainder = encrypted.count.quotientAndRemainder(dividingBy: 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. }