ChaCha20.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. //
  2. // ChaCha20.swift
  3. // CryptoSwift
  4. //
  5. // Copyright (C) 2014-2017 Marcin Krzyżanowski <marcin@krzyzanowskim.com>
  6. // This software is provided 'as-is', without any express or implied warranty.
  7. //
  8. // In no event will the authors be held liable for any damages arising from the use of this software.
  9. //
  10. // 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:
  11. //
  12. // - 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.
  13. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  14. // - This notice may not be removed or altered from any source or binary distribution.
  15. //
  16. // https://tools.ietf.org/html/rfc7539
  17. //
  18. private typealias Key = SecureBytes
  19. public final class ChaCha20: BlockCipher {
  20. public enum Error: Swift.Error {
  21. case invalidKeyOrInitializationVector
  22. }
  23. public static let blockSize = 64 // 512 / 8
  24. fileprivate let key: Key
  25. fileprivate var counter: Array<UInt8>
  26. public init(key: Array<UInt8>, iv nonce: Array<UInt8>) throws {
  27. precondition(nonce.count == 12 || nonce.count == 8)
  28. if key.count != 32 {
  29. throw Error.invalidKeyOrInitializationVector
  30. }
  31. self.key = Key(bytes: key)
  32. if nonce.count == 8 {
  33. counter = [0, 0, 0, 0, 0, 0, 0, 0] + nonce
  34. } else {
  35. counter = [0, 0, 0, 0] + nonce
  36. }
  37. assert(counter.count == 16)
  38. }
  39. /// https://tools.ietf.org/html/rfc7539#section-2.3.
  40. fileprivate func core(block: inout Array<UInt8>, counter: Array<UInt8>, key: Array<UInt8>) {
  41. precondition(block.count == ChaCha20.blockSize)
  42. precondition(counter.count == 16)
  43. precondition(key.count == 32)
  44. let j0: UInt32 = 0x61707865
  45. let j1: UInt32 = 0x3320646e // 0x3620646e sigma/tau
  46. let j2: UInt32 = 0x79622d32
  47. let j3: UInt32 = 0x6b206574
  48. let j4: UInt32 = UInt32(bytes: key[0..<4]).bigEndian
  49. let j5: UInt32 = UInt32(bytes: key[4..<8]).bigEndian
  50. let j6: UInt32 = UInt32(bytes: key[8..<12]).bigEndian
  51. let j7: UInt32 = UInt32(bytes: key[12..<16]).bigEndian
  52. let j8: UInt32 = UInt32(bytes: key[16..<20]).bigEndian
  53. let j9: UInt32 = UInt32(bytes: key[20..<24]).bigEndian
  54. let j10: UInt32 = UInt32(bytes: key[24..<28]).bigEndian
  55. let j11: UInt32 = UInt32(bytes: key[28..<32]).bigEndian
  56. let j12: UInt32 = UInt32(bytes: counter[0..<4]).bigEndian
  57. let j13: UInt32 = UInt32(bytes: counter[4..<8]).bigEndian
  58. let j14: UInt32 = UInt32(bytes: counter[8..<12]).bigEndian
  59. let j15: UInt32 = UInt32(bytes: counter[12..<16]).bigEndian
  60. var (x0, x1, x2, x3, x4, x5, x6, x7) = (j0, j1, j2, j3, j4, j5, j6, j7)
  61. var (x8, x9, x10, x11, x12, x13, x14, x15) = (j8, j9, j10, j11, j12, j13, j14, j15)
  62. for _ in 0..<10 { // 20 rounds
  63. x0 = x0 &+ x4
  64. x12 ^= x0
  65. x12 = (x12 << 16) | (x12 >> 16)
  66. x8 = x8 &+ x12
  67. x4 ^= x8
  68. x4 = (x4 << 12) | (x4 >> 20)
  69. x0 = x0 &+ x4
  70. x12 ^= x0
  71. x12 = (x12 << 8) | (x12 >> 24)
  72. x8 = x8 &+ x12
  73. x4 ^= x8
  74. x4 = (x4 << 7) | (x4 >> 25)
  75. x1 = x1 &+ x5
  76. x13 ^= x1
  77. x13 = (x13 << 16) | (x13 >> 16)
  78. x9 = x9 &+ x13
  79. x5 ^= x9
  80. x5 = (x5 << 12) | (x5 >> 20)
  81. x1 = x1 &+ x5
  82. x13 ^= x1
  83. x13 = (x13 << 8) | (x13 >> 24)
  84. x9 = x9 &+ x13
  85. x5 ^= x9
  86. x5 = (x5 << 7) | (x5 >> 25)
  87. x2 = x2 &+ x6
  88. x14 ^= x2
  89. x14 = (x14 << 16) | (x14 >> 16)
  90. x10 = x10 &+ x14
  91. x6 ^= x10
  92. x6 = (x6 << 12) | (x6 >> 20)
  93. x2 = x2 &+ x6
  94. x14 ^= x2
  95. x14 = (x14 << 8) | (x14 >> 24)
  96. x10 = x10 &+ x14
  97. x6 ^= x10
  98. x6 = (x6 << 7) | (x6 >> 25)
  99. x3 = x3 &+ x7
  100. x15 ^= x3
  101. x15 = (x15 << 16) | (x15 >> 16)
  102. x11 = x11 &+ x15
  103. x7 ^= x11
  104. x7 = (x7 << 12) | (x7 >> 20)
  105. x3 = x3 &+ x7
  106. x15 ^= x3
  107. x15 = (x15 << 8) | (x15 >> 24)
  108. x11 = x11 &+ x15
  109. x7 ^= x11
  110. x7 = (x7 << 7) | (x7 >> 25)
  111. x0 = x0 &+ x5
  112. x15 ^= x0
  113. x15 = (x15 << 16) | (x15 >> 16)
  114. x10 = x10 &+ x15
  115. x5 ^= x10
  116. x5 = (x5 << 12) | (x5 >> 20)
  117. x0 = x0 &+ x5
  118. x15 ^= x0
  119. x15 = (x15 << 8) | (x15 >> 24)
  120. x10 = x10 &+ x15
  121. x5 ^= x10
  122. x5 = (x5 << 7) | (x5 >> 25)
  123. x1 = x1 &+ x6
  124. x12 ^= x1
  125. x12 = (x12 << 16) | (x12 >> 16)
  126. x11 = x11 &+ x12
  127. x6 ^= x11
  128. x6 = (x6 << 12) | (x6 >> 20)
  129. x1 = x1 &+ x6
  130. x12 ^= x1
  131. x12 = (x12 << 8) | (x12 >> 24)
  132. x11 = x11 &+ x12
  133. x6 ^= x11
  134. x6 = (x6 << 7) | (x6 >> 25)
  135. x2 = x2 &+ x7
  136. x13 ^= x2
  137. x13 = (x13 << 16) | (x13 >> 16)
  138. x8 = x8 &+ x13
  139. x7 ^= x8
  140. x7 = (x7 << 12) | (x7 >> 20)
  141. x2 = x2 &+ x7
  142. x13 ^= x2
  143. x13 = (x13 << 8) | (x13 >> 24)
  144. x8 = x8 &+ x13
  145. x7 ^= x8
  146. x7 = (x7 << 7) | (x7 >> 25)
  147. x3 = x3 &+ x4
  148. x14 ^= x3
  149. x14 = (x14 << 16) | (x14 >> 16)
  150. x9 = x9 &+ x14
  151. x4 ^= x9
  152. x4 = (x4 << 12) | (x4 >> 20)
  153. x3 = x3 &+ x4
  154. x14 ^= x3
  155. x14 = (x14 << 8) | (x14 >> 24)
  156. x9 = x9 &+ x14
  157. x4 ^= x9
  158. x4 = (x4 << 7) | (x4 >> 25)
  159. }
  160. x0 = x0 &+ j0
  161. x1 = x1 &+ j1
  162. x2 = x2 &+ j2
  163. x3 = x3 &+ j3
  164. x4 = x4 &+ j4
  165. x5 = x5 &+ j5
  166. x6 = x6 &+ j6
  167. x7 = x7 &+ j7
  168. x8 = x8 &+ j8
  169. x9 = x9 &+ j9
  170. x10 = x10 &+ j10
  171. x11 = x11 &+ j11
  172. x12 = x12 &+ j12
  173. x13 = x13 &+ j13
  174. x14 = x14 &+ j14
  175. x15 = x15 &+ j15
  176. block.replaceSubrange(0..<4, with: x0.bigEndian.bytes())
  177. block.replaceSubrange(4..<8, with: x1.bigEndian.bytes())
  178. block.replaceSubrange(8..<12, with: x2.bigEndian.bytes())
  179. block.replaceSubrange(12..<16, with: x3.bigEndian.bytes())
  180. block.replaceSubrange(16..<20, with: x4.bigEndian.bytes())
  181. block.replaceSubrange(20..<24, with: x5.bigEndian.bytes())
  182. block.replaceSubrange(24..<28, with: x6.bigEndian.bytes())
  183. block.replaceSubrange(28..<32, with: x7.bigEndian.bytes())
  184. block.replaceSubrange(32..<36, with: x8.bigEndian.bytes())
  185. block.replaceSubrange(36..<40, with: x9.bigEndian.bytes())
  186. block.replaceSubrange(40..<44, with: x10.bigEndian.bytes())
  187. block.replaceSubrange(44..<48, with: x11.bigEndian.bytes())
  188. block.replaceSubrange(48..<52, with: x12.bigEndian.bytes())
  189. block.replaceSubrange(52..<56, with: x13.bigEndian.bytes())
  190. block.replaceSubrange(56..<60, with: x14.bigEndian.bytes())
  191. block.replaceSubrange(60..<64, with: x15.bigEndian.bytes())
  192. }
  193. // XORKeyStream
  194. func process(bytes: Array<UInt8>, counter: inout Array<UInt8>, key: Array<UInt8>) -> Array<UInt8> {
  195. precondition(counter.count == 16)
  196. precondition(key.count == 32)
  197. var block = Array<UInt8>(repeating: 0, count: ChaCha20.blockSize)
  198. var bytes = bytes // TODO: check bytes[bytes.indices]
  199. var out = Array<UInt8>(reserveCapacity: bytes.count)
  200. while bytes.count >= ChaCha20.blockSize {
  201. core(block: &block, counter: counter, key: key)
  202. for (i, x) in block.enumerated() {
  203. out.append(bytes[i] ^ x)
  204. }
  205. var u: UInt32 = 1
  206. for i in 0..<4 {
  207. u += UInt32(counter[i])
  208. counter[i] = UInt8(u)
  209. u >>= 8
  210. }
  211. bytes = Array(bytes[ChaCha20.blockSize..<bytes.endIndex])
  212. }
  213. if bytes.count > 0 {
  214. core(block: &block, counter: counter, key: key)
  215. for (i, v) in bytes.enumerated() {
  216. out.append(v ^ block[i])
  217. }
  218. }
  219. return out
  220. }
  221. }
  222. // MARK: Cipher
  223. extension ChaCha20: Cipher {
  224. public func encrypt(_ bytes: ArraySlice<UInt8>) throws -> Array<UInt8> {
  225. return process(bytes: Array(bytes), counter: &counter, key: Array(key))
  226. }
  227. public func decrypt(_ bytes: ArraySlice<UInt8>) throws -> Array<UInt8> {
  228. return try encrypt(bytes)
  229. }
  230. }
  231. // MARK: Encryptor
  232. extension ChaCha20 {
  233. public struct Encryptor: Updatable {
  234. private var accumulated = Array<UInt8>()
  235. private let chacha: ChaCha20
  236. init(chacha: ChaCha20) {
  237. self.chacha = chacha
  238. }
  239. public mutating func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false) throws -> Array<UInt8> {
  240. accumulated += bytes
  241. var encrypted = Array<UInt8>()
  242. encrypted.reserveCapacity(accumulated.count)
  243. for chunk in accumulated.batched(by: ChaCha20.blockSize) {
  244. if isLast || accumulated.count >= ChaCha20.blockSize {
  245. encrypted += try chacha.encrypt(chunk)
  246. accumulated.removeFirst(chunk.count) // TODO: improve performance
  247. }
  248. }
  249. return encrypted
  250. }
  251. }
  252. }
  253. // MARK: Decryptor
  254. extension ChaCha20 {
  255. public struct Decryptor: Updatable {
  256. private var accumulated = Array<UInt8>()
  257. private var offset: Int = 0
  258. private var offsetToRemove: Int = 0
  259. private let chacha: ChaCha20
  260. init(chacha: ChaCha20) {
  261. self.chacha = chacha
  262. }
  263. public mutating func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = true) throws -> Array<UInt8> {
  264. // prepend "offset" number of bytes at the begining
  265. if offset > 0 {
  266. accumulated += Array<UInt8>(repeating: 0, count: offset) + bytes
  267. offsetToRemove = offset
  268. offset = 0
  269. } else {
  270. accumulated += bytes
  271. }
  272. var plaintext = Array<UInt8>()
  273. plaintext.reserveCapacity(accumulated.count)
  274. for chunk in accumulated.batched(by: ChaCha20.blockSize) {
  275. if isLast || accumulated.count >= ChaCha20.blockSize {
  276. plaintext += try chacha.decrypt(chunk)
  277. // remove "offset" from the beginning of first chunk
  278. if offsetToRemove > 0 {
  279. plaintext.removeFirst(offsetToRemove) // TODO: improve performance
  280. offsetToRemove = 0
  281. }
  282. accumulated.removeFirst(chunk.count)
  283. }
  284. }
  285. return plaintext
  286. }
  287. }
  288. }
  289. // MARK: Cryptors
  290. extension ChaCha20: Cryptors {
  291. public func makeEncryptor() -> ChaCha20.Encryptor {
  292. return Encryptor(chacha: self)
  293. }
  294. public func makeDecryptor() -> ChaCha20.Decryptor {
  295. return Decryptor(chacha: self)
  296. }
  297. }