ChaCha20.swift 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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 {
  9. public enum Error: ErrorType {
  10. case MissingContext
  11. }
  12. static let blockSize = 64 // 512 / 8
  13. private let stateSize = 16
  14. private var context:Context?
  15. final private class Context {
  16. var input:[UInt32] = [UInt32](count: 16, repeatedValue: 0)
  17. deinit {
  18. for (var i = 0; i < input.count; i++) {
  19. input[i] = 0x00;
  20. }
  21. }
  22. }
  23. public init?(key:[UInt8], iv:[UInt8]) {
  24. if let c = contextSetup(iv: iv, key: key) {
  25. context = c
  26. } else {
  27. return nil
  28. }
  29. }
  30. public func encrypt(bytes:[UInt8]) throws -> [UInt8] {
  31. guard context != nil else {
  32. throw Error.MissingContext
  33. }
  34. return try encryptBytes(bytes)
  35. }
  36. public func decrypt(bytes:[UInt8]) throws -> [UInt8] {
  37. return try encrypt(bytes)
  38. }
  39. private final func wordToByte(input:[UInt32] /* 64 */) -> [UInt8]? /* 16 */ {
  40. if (input.count != stateSize) {
  41. return nil;
  42. }
  43. var x = input
  44. var i = 10
  45. while (i > 0) {
  46. quarterround(&x[0], &x[4], &x[8], &x[12])
  47. quarterround(&x[1], &x[5], &x[9], &x[13])
  48. quarterround(&x[2], &x[6], &x[10], &x[14])
  49. quarterround(&x[3], &x[7], &x[11], &x[15])
  50. quarterround(&x[0], &x[5], &x[10], &x[15])
  51. quarterround(&x[1], &x[6], &x[11], &x[12])
  52. quarterround(&x[2], &x[7], &x[8], &x[13])
  53. quarterround(&x[3], &x[4], &x[9], &x[14])
  54. i -= 2
  55. }
  56. var output = [UInt8]()
  57. output.reserveCapacity(16)
  58. for i in 0..<16 {
  59. x[i] = x[i] &+ input[i]
  60. output.appendContentsOf([UInt8((x[i] & 0xFFFFFFFF) >> 24),
  61. UInt8((x[i] & 0xFFFFFF) >> 16),
  62. UInt8((x[i] & 0xFFFF) >> 8),
  63. UInt8((x[i] & 0xFF) >> 0)])
  64. }
  65. return output;
  66. }
  67. private func contextSetup(iv iv:[UInt8], key:[UInt8]) -> Context? {
  68. let ctx = Context()
  69. let kbits = key.count * 8
  70. if (kbits != 128 && kbits != 256) {
  71. return nil
  72. }
  73. // 4 - 8
  74. for (var i = 0; i < 4; i++) {
  75. let start = i * 4
  76. ctx.input[i + 4] = wordNumber(key[start..<(start + 4)])
  77. }
  78. var addPos = 0;
  79. switch (kbits) {
  80. case 256:
  81. addPos += 16
  82. // sigma
  83. ctx.input[0] = 0x61707865 //apxe
  84. ctx.input[1] = 0x3320646e //3 dn
  85. ctx.input[2] = 0x79622d32 //yb-2
  86. ctx.input[3] = 0x6b206574 //k et
  87. default:
  88. // tau
  89. ctx.input[0] = 0x61707865 //apxe
  90. ctx.input[1] = 0x3620646e //6 dn
  91. ctx.input[2] = 0x79622d31 //yb-1
  92. ctx.input[3] = 0x6b206574 //k et
  93. break;
  94. }
  95. // 8 - 11
  96. for (var i = 0; i < 4; i++) {
  97. let start = addPos + (i*4)
  98. let bytes = key[start..<(start + 4)]
  99. ctx.input[i + 8] = wordNumber(bytes)
  100. }
  101. // iv
  102. ctx.input[12] = 0
  103. ctx.input[13] = 0
  104. ctx.input[14] = wordNumber(iv[0..<4])
  105. ctx.input[15] = wordNumber(iv[4..<8])
  106. return ctx
  107. }
  108. private final func encryptBytes(message:[UInt8]) throws -> [UInt8] {
  109. guard let ctx = context else {
  110. throw Error.MissingContext
  111. }
  112. var c:[UInt8] = [UInt8](count: message.count, repeatedValue: 0)
  113. var cPos:Int = 0
  114. var mPos:Int = 0
  115. var bytes = message.count
  116. while (true) {
  117. if let output = wordToByte(ctx.input) {
  118. ctx.input[12] = ctx.input[12] &+ 1
  119. if (ctx.input[12] == 0) {
  120. ctx.input[13] = ctx.input[13] &+ 1
  121. /* stopping at 2^70 bytes per nonce is user's responsibility */
  122. }
  123. if (bytes <= ChaCha20.blockSize) {
  124. for (var i = 0; i < bytes; i++) {
  125. c[i + cPos] = message[i + mPos] ^ output[i]
  126. }
  127. return c
  128. }
  129. for (var i = 0; i < ChaCha20.blockSize; i++) {
  130. c[i + cPos] = message[i + mPos] ^ output[i]
  131. }
  132. bytes -= ChaCha20.blockSize
  133. cPos += ChaCha20.blockSize
  134. mPos += ChaCha20.blockSize
  135. }
  136. }
  137. }
  138. private final func quarterround(inout a:UInt32, inout _ b:UInt32, inout _ c:UInt32, inout _ d:UInt32) {
  139. a = a &+ b
  140. d = rotateLeft((d ^ a), 16) //FIXME: WAT? n:
  141. c = c &+ d
  142. b = rotateLeft((b ^ c), 12);
  143. a = a &+ b
  144. d = rotateLeft((d ^ a), 8);
  145. c = c &+ d
  146. b = rotateLeft((b ^ c), 7);
  147. }
  148. }
  149. // MARK: - Cipher
  150. extension ChaCha20: Cipher {
  151. public func cipherEncrypt(bytes:[UInt8]) throws -> [UInt8] {
  152. return try self.encrypt(bytes)
  153. }
  154. public func cipherDecrypt(bytes: [UInt8]) throws -> [UInt8] {
  155. return try self.decrypt(bytes)
  156. }
  157. }
  158. // MARK: Helpers
  159. /// Change array to number. It's here because arrayOfBytes is too slow
  160. private func wordNumber(bytes:ArraySlice<UInt8>) -> UInt32 {
  161. var value:UInt32 = 0
  162. for (var i:UInt32 = 0, j = bytes.startIndex; i < 4; i++, j++) {
  163. value = value | UInt32(bytes[j]) << (8 * i)
  164. }
  165. return value
  166. }