BlockEncryptor.swift 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // CryptoSwift
  2. //
  3. // Copyright (C) 2014-2021 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. @usableFromInline
  15. final class BlockEncryptor: Cryptor, Updatable {
  16. private let blockSize: Int
  17. private var worker: CipherModeWorker
  18. private let padding: Padding
  19. // Accumulated bytes. Not all processed bytes.
  20. private var accumulated = Array<UInt8>(reserveCapacity: 16)
  21. private var lastBlockRemainder = 0
  22. @usableFromInline
  23. init(blockSize: Int, padding: Padding, _ worker: CipherModeWorker) throws {
  24. self.blockSize = blockSize
  25. self.padding = padding
  26. self.worker = worker
  27. }
  28. // MARK: Updatable
  29. public func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool) throws -> Array<UInt8> {
  30. self.accumulated += bytes
  31. if isLast {
  32. self.accumulated = self.padding.add(to: self.accumulated, blockSize: self.blockSize)
  33. }
  34. var encrypted = Array<UInt8>(reserveCapacity: accumulated.count)
  35. for chunk in self.accumulated.batched(by: self.blockSize) {
  36. if isLast || chunk.count == self.blockSize {
  37. encrypted += self.worker.encrypt(block: chunk)
  38. }
  39. }
  40. // Stream encrypts all, so it removes all elements
  41. self.accumulated.removeFirst(encrypted.count)
  42. if var finalizingWorker = worker as? FinalizingEncryptModeWorker, isLast == true {
  43. encrypted = Array(try finalizingWorker.finalize(encrypt: encrypted.slice))
  44. }
  45. return encrypted
  46. }
  47. @usableFromInline
  48. func seek(to: Int) throws {
  49. fatalError("Not supported")
  50. }
  51. }