ChaCha20.swift 5.4 KB

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