CTR.swift 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  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. // Counter (CTR)
  16. public struct CTR: StreamMode {
  17. public enum Error: Swift.Error {
  18. /// Invalid IV
  19. case invalidInitializationVector
  20. }
  21. public let options: BlockModeOption = [.initializationVectorRequired, .useEncryptToDecrypt]
  22. private let iv: Array<UInt8>
  23. private let counter: Int
  24. public init(iv: Array<UInt8>, counter: Int = 0) {
  25. self.iv = iv
  26. self.counter = counter
  27. }
  28. public func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock) throws -> CipherModeWorker {
  29. if iv.count != blockSize {
  30. throw Error.invalidInitializationVector
  31. }
  32. return CTRModeWorker(blockSize: blockSize, iv: iv.slice, counter: counter, cipherOperation: cipherOperation)
  33. }
  34. }
  35. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  36. struct CTRModeWorker: StreamModeWorker, CounterModeWorker {
  37. typealias Counter = CTRCounter
  38. final class CTRCounter {
  39. private let constPrefix: Array<UInt8>
  40. private var value: UInt64
  41. //TODO: make it an updatable value, computing is too slow
  42. var bytes: Array<UInt8> {
  43. return constPrefix + value.bytes()
  44. }
  45. init(_ initialValue: Array<UInt8>) {
  46. let halfIndex = initialValue.startIndex.advanced(by: initialValue.count / 2)
  47. constPrefix = Array(initialValue[initialValue.startIndex..<halfIndex])
  48. let suffixBytes = Array(initialValue[halfIndex...])
  49. value = UInt64(bytes: suffixBytes)
  50. }
  51. convenience init(nonce: Array<UInt8>, startAt index: Int) {
  52. self.init(buildCounterValue(nonce, counter: UInt64(index)))
  53. }
  54. static func +=(lhs: CTRCounter, rhs: Int) {
  55. lhs.value += UInt64(rhs)
  56. }
  57. }
  58. let cipherOperation: CipherOperationOnBlock
  59. let additionalBufferSize: Int = 0
  60. let iv: Array<UInt8>
  61. var counter: CTRCounter
  62. private let blockSize: Int
  63. // The same keystream is used for the block length plaintext
  64. // As new data is added, keystream suffix is used to xor operation.
  65. private var keystream: Array<UInt8>
  66. private var keystreamPosIdx = 0
  67. init(blockSize: Int, iv: ArraySlice<UInt8>, counter: Int, cipherOperation: @escaping CipherOperationOnBlock) {
  68. self.cipherOperation = cipherOperation
  69. self.blockSize = blockSize
  70. self.iv = Array(iv)
  71. // the first keystream is calculated from the nonce = initial value of counter
  72. self.counter = CTRCounter(nonce: Array(iv), startAt: counter)
  73. self.keystream = Array(cipherOperation(self.counter.bytes.slice)!)
  74. }
  75. mutating func seek(to position: Int) throws {
  76. let offset = position % blockSize
  77. counter = CTRCounter(nonce: iv, startAt: position / blockSize)
  78. keystream = Array(cipherOperation(counter.bytes.slice)!)
  79. keystreamPosIdx = offset
  80. }
  81. // plaintext is at most blockSize long
  82. mutating func encrypt(block plaintext: ArraySlice<UInt8>) -> Array<UInt8> {
  83. var result = Array<UInt8>(reserveCapacity: plaintext.count)
  84. var processed = 0
  85. while processed < plaintext.count {
  86. // Update keystream
  87. if keystreamPosIdx == blockSize {
  88. counter += 1
  89. keystream = Array(cipherOperation(counter.bytes.slice)!)
  90. keystreamPosIdx = 0
  91. }
  92. let xored: Array<UInt8> = xor(plaintext[plaintext.startIndex.advanced(by: processed)...], keystream[keystreamPosIdx...])
  93. keystreamPosIdx += xored.count
  94. processed += xored.count
  95. result += xored
  96. }
  97. return result
  98. }
  99. mutating func decrypt(block ciphertext: ArraySlice<UInt8>) -> Array<UInt8> {
  100. return encrypt(block: ciphertext)
  101. }
  102. }
  103. private func buildCounterValue(_ iv: Array<UInt8>, counter: UInt64) -> Array<UInt8> {
  104. let noncePartLen = iv.count / 2
  105. let noncePrefix = iv[iv.startIndex..<iv.startIndex.advanced(by: noncePartLen)]
  106. let nonceSuffix = iv[iv.startIndex.advanced(by: noncePartLen)..<iv.startIndex.advanced(by: iv.count)]
  107. let c = UInt64(bytes: nonceSuffix) + counter
  108. return noncePrefix + c.bytes()
  109. }