ChaCha20.swift 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. //
  2. // ChaCha20.swift
  3. // CryptoSwift
  4. //
  5. // Created by Marcin Krzyzanowski on 25/08/14.
  6. // Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
  7. //
  8. final public class ChaCha20: BlockCipher {
  9. public enum Error: Swift.Error {
  10. case invalidKeyOrInitializationVector
  11. }
  12. public static let blockSize = 64 // 512 / 8
  13. private let context: Context
  14. private struct Context {
  15. var input = Array<UInt32>(repeating: 0, count: 16)
  16. init(key:Array<UInt8>, iv:Array<UInt8>) throws {
  17. precondition(iv.count >= 8)
  18. let kbits = key.count * 8
  19. if (kbits != 128 && kbits != 256) {
  20. throw Error.invalidKeyOrInitializationVector
  21. }
  22. // 4 - 8
  23. for i in 0..<4 {
  24. let start = i * 4
  25. input[i + 4] = wordNumber(key[start..<(start + 4)])
  26. }
  27. var addPos = 0;
  28. switch (kbits) {
  29. case 256:
  30. addPos += 16
  31. // sigma
  32. input[0] = 0x61707865 //apxe
  33. input[1] = 0x3320646e //3 dn
  34. input[2] = 0x79622d32 //yb-2
  35. input[3] = 0x6b206574 //k et
  36. default:
  37. // tau
  38. input[0] = 0x61707865 //apxe
  39. input[1] = 0x3620646e //6 dn
  40. input[2] = 0x79622d31 //yb-1
  41. input[3] = 0x6b206574 //k et
  42. }
  43. // 8 - 11
  44. for i in 0..<4 {
  45. let start = addPos + (i*4)
  46. let bytes = key[start..<(start + 4)]
  47. input[i + 8] = wordNumber(bytes)
  48. }
  49. // iv
  50. input[12] = 0
  51. input[13] = 0
  52. input[14] = wordNumber(iv[0..<4])
  53. input[15] = wordNumber(iv[4..<8])
  54. }
  55. }
  56. public init(key:Array<UInt8>, iv:Array<UInt8>) throws {
  57. self.context = try Context(key: key, iv: iv)
  58. }
  59. private final func wordToByte(_ input:Array<UInt32> /* 64 */) -> Array<UInt8>? /* 16 */ {
  60. precondition(input.count == 16)
  61. var x = input
  62. for _ in 0..<10 {
  63. quarterround(&x[0], &x[4], &x[8], &x[12])
  64. quarterround(&x[1], &x[5], &x[9], &x[13])
  65. quarterround(&x[2], &x[6], &x[10], &x[14])
  66. quarterround(&x[3], &x[7], &x[11], &x[15])
  67. quarterround(&x[0], &x[5], &x[10], &x[15])
  68. quarterround(&x[1], &x[6], &x[11], &x[12])
  69. quarterround(&x[2], &x[7], &x[8], &x[13])
  70. quarterround(&x[3], &x[4], &x[9], &x[14])
  71. }
  72. var output = Array<UInt8>()
  73. output.reserveCapacity(16)
  74. for i in 0..<16 {
  75. x[i] = x[i] &+ input[i]
  76. output.append(contentsOf: x[i].bytes().reversed())
  77. }
  78. return output;
  79. }
  80. fileprivate final func encryptBytes(_ message:Array<UInt8>) throws -> Array<UInt8> {
  81. var ctx = context
  82. var c = Array<UInt8>(repeating: 0, count: message.count)
  83. var cPos:Int = 0
  84. var mPos:Int = 0
  85. var bytes = message.count
  86. while (true) {
  87. if let output = wordToByte(ctx.input) {
  88. ctx.input[12] = ctx.input[12] &+ 1
  89. if (ctx.input[12] == 0) {
  90. ctx.input[13] = ctx.input[13] &+ 1
  91. /* stopping at 2^70 bytes per nonce is user's responsibility */
  92. }
  93. if (bytes <= ChaCha20.blockSize) {
  94. for i in 0..<bytes {
  95. c[i + cPos] = message[i + mPos] ^ output[i]
  96. }
  97. return c
  98. }
  99. for i in 0..<ChaCha20.blockSize {
  100. c[i + cPos] = message[i + mPos] ^ output[i]
  101. }
  102. bytes -= ChaCha20.blockSize
  103. cPos += ChaCha20.blockSize
  104. mPos += ChaCha20.blockSize
  105. }
  106. }
  107. }
  108. private final func quarterround(_ a:inout UInt32, _ b:inout UInt32, _ c:inout UInt32, _ d:inout UInt32) {
  109. a = a &+ b
  110. d = rotateLeft((d ^ a), by: 16) //FIXME: WAT? n:
  111. c = c &+ d
  112. b = rotateLeft((b ^ c), by: 12);
  113. a = a &+ b
  114. d = rotateLeft((d ^ a), by: 8);
  115. c = c &+ d
  116. b = rotateLeft((b ^ c), by: 7);
  117. }
  118. }
  119. // MARK: Encryptor
  120. extension ChaCha20 {
  121. public struct Encryptor: Updatable {
  122. private var accumulated = Array<UInt8>()
  123. private let chacha: ChaCha20
  124. init(chacha: ChaCha20) {
  125. self.chacha = chacha
  126. }
  127. mutating public func update<T: Sequence>(withBytes bytes:T, isLast: Bool = false) throws -> Array<UInt8> where T.Iterator.Element == UInt8 {
  128. self.accumulated += bytes
  129. var encrypted = Array<UInt8>()
  130. encrypted.reserveCapacity(self.accumulated.count)
  131. for chunk in self.accumulated.chunks(size: ChaCha20.blockSize) {
  132. if (isLast || self.accumulated.count >= ChaCha20.blockSize) {
  133. encrypted += try chacha.encrypt(chunk)
  134. self.accumulated.removeFirst(chunk.count)
  135. }
  136. }
  137. return encrypted
  138. }
  139. }
  140. }
  141. // MARK: Decryptor
  142. extension ChaCha20 {
  143. public struct Decryptor: Updatable {
  144. private var accumulated = Array<UInt8>()
  145. private var offset: Int = 0
  146. private var offsetToRemove: Int = 0
  147. private let chacha: ChaCha20
  148. init(chacha: ChaCha20) {
  149. self.chacha = chacha
  150. }
  151. mutating public func update<T: Sequence>(withBytes bytes:T, isLast: Bool = true) throws -> Array<UInt8> where T.Iterator.Element == UInt8 {
  152. // prepend "offset" number of bytes at the begining
  153. if self.offset > 0 {
  154. self.accumulated += Array<UInt8>(repeating: 0, count: offset) + bytes
  155. self.offsetToRemove = offset
  156. self.offset = 0
  157. } else {
  158. self.accumulated += bytes
  159. }
  160. var plaintext = Array<UInt8>()
  161. plaintext.reserveCapacity(self.accumulated.count)
  162. for chunk in self.accumulated.chunks(size: ChaCha20.blockSize) {
  163. if (isLast || self.accumulated.count >= ChaCha20.blockSize) {
  164. plaintext += try chacha.decrypt(chunk)
  165. // remove "offset" from the beginning of first chunk
  166. if self.offsetToRemove > 0 {
  167. plaintext.removeFirst(self.offsetToRemove);
  168. self.offsetToRemove = 0
  169. }
  170. self.accumulated.removeFirst(chunk.count)
  171. }
  172. }
  173. return plaintext
  174. }
  175. }
  176. }
  177. // MARK: Cryptors
  178. extension ChaCha20: Cryptors {
  179. public func makeEncryptor() -> ChaCha20.Encryptor {
  180. return Encryptor(chacha: self)
  181. }
  182. public func makeDecryptor() -> ChaCha20.Decryptor {
  183. return Decryptor(chacha: self)
  184. }
  185. }
  186. // MARK: Cipher
  187. extension ChaCha20: Cipher {
  188. public func encrypt(_ bytes:Array<UInt8>) throws -> Array<UInt8> {
  189. return try encryptBytes(bytes)
  190. }
  191. public func decrypt(_ bytes:Array<UInt8>) throws -> Array<UInt8> {
  192. return try encrypt(bytes)
  193. }
  194. }
  195. // MARK: Helpers
  196. /// Change array to number. It's here because arrayOfBytes is too slow
  197. private func wordNumber<T: Collection>(_ bytes: T) -> UInt32 where T.Iterator.Element == UInt8, T.IndexDistance == Int {
  198. var value:UInt32 = 0
  199. for i:UInt32 in 0..<4 {
  200. let j = bytes.index(bytes.startIndex, offsetBy: Int(i))
  201. value = value | UInt32(bytes[j]) << (8 * i)
  202. }
  203. return value
  204. }