ChaCha20.swift 11 KB

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