BlockEncryptor.swift 2.2 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 BlockEncryptor: 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. self.accumulated += bytes
  29. if isLast {
  30. self.accumulated = self.padding.add(to: self.accumulated, blockSize: self.blockSize)
  31. }
  32. var encrypted = Array<UInt8>(reserveCapacity: accumulated.count)
  33. for chunk in self.accumulated.batched(by: self.blockSize) {
  34. if isLast || chunk.count == self.blockSize {
  35. encrypted += self.worker.encrypt(block: chunk)
  36. }
  37. }
  38. // Stream encrypts all, so it removes all elements
  39. self.accumulated.removeFirst(encrypted.count)
  40. if var finalizingWorker = worker as? FinalizingEncryptModeWorker, isLast == true {
  41. encrypted = Array(try finalizingWorker.finalize(encrypt: encrypted.slice))
  42. }
  43. return encrypted
  44. }
  45. func seek(to: Int) throws {
  46. fatalError("Not supported")
  47. }
  48. }