PCBC.swift 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //
  2. // CryptoSwift
  3. //
  4. // Copyright (C) 2014-2017 Marcin Krzyżanowski <marcin@krzyzanowskim.com>
  5. // This software is provided 'as-is', without any express or implied warranty.
  6. //
  7. // In no event will the authors be held liable for any damages arising from the use of this software.
  8. //
  9. // 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:
  10. //
  11. // - 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.
  12. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  13. // - This notice may not be removed or altered from any source or binary distribution.
  14. //
  15. // Propagating Cipher Block Chaining (PCBC)
  16. //
  17. public struct PCBC: BlockMode {
  18. public enum Error: Swift.Error {
  19. /// Invalid IV
  20. case invalidInitializationVector
  21. }
  22. public let options: BlockModeOption = [.initializationVectorRequired, .paddingRequired]
  23. private let iv: Array<UInt8>
  24. public init(iv: Array<UInt8>) {
  25. self.iv = iv
  26. }
  27. public func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock) throws -> CipherModeWorker {
  28. if iv.count != blockSize {
  29. throw Error.invalidInitializationVector
  30. }
  31. return PCBCModeWorker(blockSize: blockSize, iv: iv.slice, cipherOperation: cipherOperation)
  32. }
  33. }
  34. struct PCBCModeWorker: BlockModeWorker {
  35. let cipherOperation: CipherOperationOnBlock
  36. var blockSize: Int
  37. let additionalBufferSize: Int = 0
  38. private let iv: ArraySlice<UInt8>
  39. private var prev: ArraySlice<UInt8>?
  40. init(blockSize: Int, iv: ArraySlice<UInt8>, cipherOperation: @escaping CipherOperationOnBlock) {
  41. self.blockSize = blockSize
  42. self.iv = iv
  43. self.cipherOperation = cipherOperation
  44. }
  45. mutating func encrypt(block plaintext: ArraySlice<UInt8>) -> Array<UInt8> {
  46. guard let ciphertext = cipherOperation(xor(prev ?? iv, plaintext)) else {
  47. return Array(plaintext)
  48. }
  49. prev = xor(plaintext, ciphertext.slice)
  50. return ciphertext
  51. }
  52. mutating func decrypt(block ciphertext: ArraySlice<UInt8>) -> Array<UInt8> {
  53. guard let plaintext = cipherOperation(ciphertext) else {
  54. return Array(ciphertext)
  55. }
  56. let result: Array<UInt8> = xor(prev ?? iv, plaintext)
  57. prev = xor(plaintext.slice, ciphertext)
  58. return result
  59. }
  60. }