2
0

CCM.swift 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. //// CryptoSwift
  2. //
  3. // Copyright (C) 2014-__YEAR__ 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. // CCM mode combines the well known CBC-MAC with the well known counter mode of encryption.
  15. // https://tools.ietf.org/html/rfc3610
  16. // https://csrc.nist.gov/publications/detail/sp/800-38c/final
  17. public struct CCM: StreamMode {
  18. public enum Error: Swift.Error {
  19. /// Invalid IV
  20. case invalidInitializationVector
  21. case invalidParameter
  22. }
  23. public let options: BlockModeOption = [.initializationVectorRequired]
  24. private let nonce: Array<UInt8>
  25. private let additionalAuthenticatedData: Array<UInt8>?
  26. private let tagLength: Int
  27. private let messageLength: Int // total message length. need to know in advance
  28. public init(nonce: Array<UInt8>, tagLength: Int, messageLength: Int, additionalAuthenticatedData: Array<UInt8>? = nil) {
  29. self.nonce = nonce
  30. self.tagLength = tagLength
  31. self.additionalAuthenticatedData = additionalAuthenticatedData
  32. self.messageLength = messageLength
  33. }
  34. public func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock) throws -> CipherModeWorker {
  35. if nonce.isEmpty {
  36. throw Error.invalidInitializationVector
  37. }
  38. return CCMModeWorker(blockSize: blockSize, nonce: nonce.slice, messageLength: messageLength, additionalAuthenticatedData: additionalAuthenticatedData, tagLength: tagLength, cipherOperation: cipherOperation)
  39. }
  40. }
  41. class CCMModeWorker: StreamModeWorker, SeekableModeWorker, CounterModeWorker, FinalizingModeWorker {
  42. typealias Counter = Int
  43. var counter = 0
  44. let cipherOperation: CipherOperationOnBlock
  45. let blockSize: Int
  46. private let tagLength: Int
  47. private let messageLength: Int // total message length. need to know in advance
  48. private let q: UInt8
  49. let additionalBufferSize: Int
  50. private var keystreamPosIdx = 0
  51. private let nonce: Array<UInt8>
  52. private var last_y: ArraySlice<UInt8> = []
  53. private var keystream: Array<UInt8> = []
  54. public enum Error: Swift.Error {
  55. case invalidParameter
  56. }
  57. init(blockSize: Int, nonce: ArraySlice<UInt8>, messageLength: Int, additionalAuthenticatedData: [UInt8]?, tagLength: Int, cipherOperation: @escaping CipherOperationOnBlock) {
  58. self.blockSize = blockSize
  59. self.tagLength = tagLength
  60. self.additionalBufferSize = tagLength
  61. self.messageLength = messageLength
  62. self.cipherOperation = cipherOperation
  63. self.nonce = Array(nonce)
  64. self.q = UInt8(15 - nonce.count) // n = 15-q
  65. let hasAssociatedData = additionalAuthenticatedData != nil && !additionalAuthenticatedData!.isEmpty
  66. processControlInformation(nonce: self.nonce, tagLength: tagLength, hasAssociatedData: hasAssociatedData)
  67. if let aad = additionalAuthenticatedData {
  68. process(aad: aad)
  69. }
  70. }
  71. // For the very first time setup new IV (aka y0) from the block0
  72. private func processControlInformation(nonce: [UInt8], tagLength: Int, hasAssociatedData: Bool) {
  73. let block0 = try! format(nonce: nonce, Q: UInt32(messageLength), q: q, t: UInt8(tagLength), hasAssociatedData: hasAssociatedData).slice
  74. let y0 = cipherOperation(block0)!.slice
  75. last_y = y0
  76. }
  77. private func process(aad: [UInt8]) {
  78. let encodedAAD = format(aad: aad)
  79. for block_i in encodedAAD.batched(by: 16) {
  80. let y_i = cipherOperation(xor(block_i, last_y))!.slice
  81. last_y = y_i
  82. }
  83. }
  84. private func S(i: Int) throws -> [UInt8] {
  85. let ctr = try format(counter: i, nonce: nonce, q: q)
  86. return cipherOperation(ctr.slice)!
  87. }
  88. func seek(to position: Int) throws {
  89. self.counter = position
  90. keystream = try S(i: position)
  91. let offset = position % blockSize
  92. keystreamPosIdx = offset
  93. }
  94. func encrypt(block plaintext: ArraySlice<UInt8>) -> Array<UInt8> {
  95. var result = Array<UInt8>(reserveCapacity: plaintext.count)
  96. var processed = 0
  97. while processed < plaintext.count {
  98. // Need a full block here to update keystream and do CBC
  99. if keystream.isEmpty || keystreamPosIdx == blockSize {
  100. // y[i], where i is the counter. Can encrypt 1 block at a time
  101. counter += 1
  102. guard let S = try? S(i: counter) else { return Array(plaintext) }
  103. let plaintextP = addPadding(Array(plaintext), blockSize: 16)
  104. guard let y = cipherOperation(xor(last_y, plaintextP)) else { return Array(plaintext) }
  105. last_y = y.slice
  106. keystream = S
  107. keystreamPosIdx = 0
  108. }
  109. let xored: Array<UInt8> = xor(plaintext[plaintext.startIndex.advanced(by: processed)...], keystream[keystreamPosIdx...])
  110. keystreamPosIdx += xored.count
  111. processed += xored.count
  112. result += xored
  113. }
  114. return result
  115. }
  116. // TODO
  117. func decrypt(block ciphertext: ArraySlice<UInt8>) -> Array<UInt8> {
  118. guard let plaintext = cipherOperation(ciphertext) else {
  119. return Array(ciphertext)
  120. }
  121. let result: Array<UInt8> = xor(last_y, plaintext)
  122. last_y = ciphertext
  123. return result
  124. }
  125. func finalize(encrypt ciphertext: ArraySlice<UInt8>) throws -> Array<UInt8> {
  126. // concatenate T at the end
  127. guard let S0 = try? S(i: 0) else { return Array(ciphertext) }
  128. let tag = last_y.prefix(tagLength)
  129. return Array(ciphertext) + (xor(tag, S0) as Array<UInt8>)
  130. }
  131. func willDecryptLast(block ciphertext: ArraySlice<UInt8>) throws -> ArraySlice<UInt8> {
  132. return ciphertext
  133. }
  134. func didDecryptLast(block plaintext: ArraySlice<UInt8>) throws -> Array<UInt8> {
  135. return Array(plaintext)
  136. }
  137. }
  138. // Q - octet length of P
  139. // q - octet length of Q. Maximum length (in octets) of payload. An element of {2,3,4,5,6,7,8}
  140. // t - octet length of T (MAC length). An element of {4,6,8,10,12,14,16}
  141. private func format(nonce N: [UInt8], Q: UInt32, q: UInt8, t: UInt8, hasAssociatedData: Bool) throws -> [UInt8] {
  142. var flags0: UInt8 = 0
  143. if hasAssociatedData {
  144. // 7 bit
  145. flags0 |= (1 << 6)
  146. }
  147. // 6,5,4 bit is t in 3 bits
  148. flags0 |= (((t-2)/2) & 0x07) << 3
  149. // 3,2,1 bit is q in 3 bits
  150. flags0 |= ((q-1) & 0x07) << 0
  151. var block0: [UInt8] = Array<UInt8>(repeating: 0, count: 16)
  152. block0[0] = flags0
  153. // N in 1...(15-q) octets, n = 15-q
  154. // n is an element of {7,8,9,10,11,12,13}
  155. let n = 15-Int(q)
  156. guard (n + Int(q)) == 15 else {
  157. // n+q == 15
  158. throw CCMModeWorker.Error.invalidParameter
  159. }
  160. block0[1...n] = N[0...(n-1)]
  161. // Q in (16-q)...15 octets
  162. block0[(16-Int(q))...15] = Q.bytes(totalBytes: Int(q)).slice
  163. return block0
  164. }
  165. /// Formatting of the Counter Blocks. Ctr[i]
  166. /// The counter generation function.
  167. /// Q - octet length of P
  168. /// q - octet length of Q. Maximum length (in octets) of payload. An element of {2,3,4,5,6,7,8}
  169. private func format(counter i: Int, nonce N: [UInt8], q: UInt8) throws -> [UInt8] {
  170. var flags0: UInt8 = 0
  171. // bit 8,7 is Reserved
  172. // bit 4,5,6 shall be set to 0
  173. // 3,2,1 bit is q in 3 bits
  174. flags0 |= ((q-1) & 0x07) << 0
  175. var block = Array<UInt8>(repeating: 0, count: 16) // block[0]
  176. block[0] = flags0
  177. // N in 1...(15-q) octets, n = 15-q
  178. // n is an element of {7,8,9,10,11,12,13}
  179. let n = 15-Int(q)
  180. guard (n + Int(q)) == 15 else {
  181. // n+q == 15
  182. throw CCMModeWorker.Error.invalidParameter
  183. }
  184. block[1...n] = N[0...(n-1)]
  185. // [i]8q in (16-q)...15 octets
  186. block[(16-Int(q))...15] = i.bytes(totalBytes: Int(q)).slice
  187. return block
  188. }
  189. /// Resulting can be partitioned into 16-octet blocks
  190. private func format(aad: [UInt8]) -> [UInt8] {
  191. let a = aad.count
  192. switch Double(a) {
  193. case 0..<65280: // 2^16-2^8
  194. // [a]16
  195. return addPadding(a.bytes(totalBytes: 2) + aad, blockSize: 16)
  196. case 65280..<4_294_967_296: // 2^32
  197. // [a]32
  198. return addPadding([0xFF, 0xFE] + a.bytes(totalBytes: 4) + aad, blockSize: 16)
  199. case 4_294_967_296..<pow(2,64): // 2^64
  200. // [a]64
  201. return addPadding([0xFF, 0xFF] + a.bytes(totalBytes: 8) + aad, blockSize: 16)
  202. default:
  203. // Reserved
  204. return addPadding(aad, blockSize: 16)
  205. }
  206. }
  207. // If data is not a multiple of block size bytes long then the remainder is zero padded
  208. // Note: It's similar to ZeroPadding, but it's not the same.
  209. private func addPadding(_ bytes: Array<UInt8>, blockSize: Int) -> Array<UInt8> {
  210. if bytes.isEmpty {
  211. return Array<UInt8>(repeating: 0, count: blockSize)
  212. }
  213. let remainder = bytes.count % blockSize
  214. if remainder == 0 {
  215. return bytes
  216. }
  217. let paddingCount = blockSize - remainder
  218. if paddingCount > 0 {
  219. return bytes + Array<UInt8>(repeating: 0, count: paddingCount)
  220. }
  221. return bytes
  222. }