PCBC.swift 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. //
  2. // PCBM.swift
  3. // CryptoSwift
  4. //
  5. // Created by Marcin Krzyzanowski on 08/03/16.
  6. // Copyright © 2016 Marcin Krzyzanowski. All rights reserved.
  7. //
  8. // Propagating Cipher Block Chaining (PCBC)
  9. //
  10. struct PCBCModeWorker: BlockModeWorker {
  11. typealias Element = Array<UInt8>
  12. let cipherOperation: CipherOperationOnBlock
  13. private let iv: Element
  14. private var prev: Element?
  15. init(iv: Array<UInt8>, cipherOperation: CipherOperationOnBlock) {
  16. self.iv = iv
  17. self.cipherOperation = cipherOperation
  18. }
  19. mutating func encrypt(plaintext: Array<UInt8>) -> [UInt8] {
  20. guard let ciphertext = cipherOperation(block: xor(prev ?? iv, plaintext)) else {
  21. return plaintext
  22. }
  23. prev = xor(plaintext, ciphertext)
  24. return ciphertext ?? []
  25. }
  26. mutating func decrypt(ciphertext: Array<UInt8>) -> [UInt8] {
  27. guard let plaintext = cipherOperation(block: ciphertext) else {
  28. return ciphertext
  29. }
  30. let result = xor(prev ?? iv, plaintext)
  31. self.prev = xor(plaintext, ciphertext)
  32. return result
  33. }
  34. }