CBC.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. // Cipher-block chaining (CBC)
  16. //
  17. public struct CBC: 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 let customBlockSize: Int? = nil
  25. public init(iv: Array<UInt8>) {
  26. self.iv = iv
  27. }
  28. public func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock, encryptionOperation: @escaping CipherOperationOnBlock) throws -> CipherModeWorker {
  29. if self.iv.count != blockSize {
  30. throw Error.invalidInitializationVector
  31. }
  32. return CBCModeWorker(blockSize: blockSize, iv: self.iv.slice, cipherOperation: cipherOperation)
  33. }
  34. }
  35. struct CBCModeWorker: BlockModeWorker {
  36. let cipherOperation: CipherOperationOnBlock
  37. var blockSize: Int
  38. let additionalBufferSize: Int = 0
  39. private let iv: ArraySlice<UInt8>
  40. private var prev: ArraySlice<UInt8>?
  41. init(blockSize: Int, iv: ArraySlice<UInt8>, cipherOperation: @escaping CipherOperationOnBlock) {
  42. self.blockSize = blockSize
  43. self.iv = iv
  44. self.cipherOperation = cipherOperation
  45. }
  46. mutating func encrypt(block plaintext: ArraySlice<UInt8>) -> Array<UInt8> {
  47. guard let ciphertext = cipherOperation(xor(prev ?? iv, plaintext)) else {
  48. return Array(plaintext)
  49. }
  50. self.prev = ciphertext.slice
  51. return ciphertext
  52. }
  53. mutating func decrypt(block ciphertext: ArraySlice<UInt8>) -> Array<UInt8> {
  54. guard let plaintext = cipherOperation(ciphertext) else {
  55. return Array(ciphertext)
  56. }
  57. let result: Array<UInt8> = xor(prev ?? self.iv, plaintext)
  58. self.prev = ciphertext
  59. return result
  60. }
  61. }