SHA3.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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. // http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf
  16. // http://keccak.noekeon.org/specs_summary.html
  17. //
  18. #if canImport(Darwin)
  19. import Darwin
  20. #else
  21. import Glibc
  22. #endif
  23. public final class SHA3: DigestType {
  24. let round_constants: Array<UInt64> = [
  25. 0x0000000000000001, 0x0000000000008082, 0x800000000000808a, 0x8000000080008000,
  26. 0x000000000000808b, 0x0000000080000001, 0x8000000080008081, 0x8000000000008009,
  27. 0x000000000000008a, 0x0000000000000088, 0x0000000080008009, 0x000000008000000a,
  28. 0x000000008000808b, 0x800000000000008b, 0x8000000000008089, 0x8000000000008003,
  29. 0x8000000000008002, 0x8000000000000080, 0x000000000000800a, 0x800000008000000a,
  30. 0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008,
  31. ]
  32. public let blockSize: Int
  33. public let digestLength: Int
  34. public let markByte: UInt8
  35. fileprivate var accumulated = Array<UInt8>()
  36. fileprivate var accumulatedHash: Array<UInt64>
  37. public enum Variant {
  38. case sha224, sha256, sha384, sha512, keccak224, keccak256, keccak384, keccak512
  39. var digestLength: Int {
  40. return 100 - (blockSize / 2)
  41. }
  42. var blockSize: Int {
  43. return (1600 - outputLength * 2) / 8
  44. }
  45. var markByte: UInt8 {
  46. switch self {
  47. case .sha224, .sha256, .sha384, .sha512:
  48. return 0x06 // 0x1F for SHAKE
  49. case .keccak224, .keccak256, .keccak384, .keccak512:
  50. return 0x01
  51. }
  52. }
  53. public var outputLength: Int {
  54. switch self {
  55. case .sha224, .keccak224:
  56. return 224
  57. case .sha256, .keccak256:
  58. return 256
  59. case .sha384, .keccak384:
  60. return 384
  61. case .sha512, .keccak512:
  62. return 512
  63. }
  64. }
  65. }
  66. public init(variant: SHA3.Variant) {
  67. blockSize = variant.blockSize
  68. digestLength = variant.digestLength
  69. markByte = variant.markByte
  70. accumulatedHash = Array<UInt64>(repeating: 0, count: digestLength)
  71. }
  72. public func calculate(for bytes: Array<UInt8>) -> Array<UInt8> {
  73. do {
  74. return try update(withBytes: bytes.slice, isLast: true)
  75. } catch {
  76. return []
  77. }
  78. }
  79. /// 1. For all pairs (x,z) such that 0≤x<5 and 0≤z<w, let
  80. /// C[x,z]=A[x, 0,z] ⊕ A[x, 1,z] ⊕ A[x, 2,z] ⊕ A[x, 3,z] ⊕ A[x, 4,z].
  81. /// 2. For all pairs (x, z) such that 0≤x<5 and 0≤z<w let
  82. /// D[x,z]=C[(x1) mod 5, z] ⊕ C[(x+1) mod 5, (z –1) mod w].
  83. /// 3. For all triples (x, y, z) such that 0≤x<5, 0≤y<5, and 0≤z<w, let
  84. /// A′[x, y,z] = A[x, y,z] ⊕ D[x,z].
  85. private func θ(_ a: inout Array<UInt64>) {
  86. let c = UnsafeMutablePointer<UInt64>.allocate(capacity: 5)
  87. c.initialize(repeating: 0, count: 5)
  88. defer {
  89. c.deinitialize(count: 5)
  90. c.deallocate()
  91. }
  92. let d = UnsafeMutablePointer<UInt64>.allocate(capacity: 5)
  93. d.initialize(repeating: 0, count: 5)
  94. defer {
  95. d.deinitialize(count: 5)
  96. d.deallocate()
  97. }
  98. for i in 0..<5 {
  99. c[i] = a[i] ^ a[i &+ 5] ^ a[i &+ 10] ^ a[i &+ 15] ^ a[i &+ 20]
  100. }
  101. d[0] = rotateLeft(c[1], by: 1) ^ c[4]
  102. d[1] = rotateLeft(c[2], by: 1) ^ c[0]
  103. d[2] = rotateLeft(c[3], by: 1) ^ c[1]
  104. d[3] = rotateLeft(c[4], by: 1) ^ c[2]
  105. d[4] = rotateLeft(c[0], by: 1) ^ c[3]
  106. for i in 0..<5 {
  107. a[i] ^= d[i]
  108. a[i &+ 5] ^= d[i]
  109. a[i &+ 10] ^= d[i]
  110. a[i &+ 15] ^= d[i]
  111. a[i &+ 20] ^= d[i]
  112. }
  113. }
  114. /// A′[x, y, z]=A[(x &+ 3y) mod 5, x, z]
  115. private func π(_ a: inout Array<UInt64>) {
  116. let a1 = a[1]
  117. a[1] = a[6]
  118. a[6] = a[9]
  119. a[9] = a[22]
  120. a[22] = a[14]
  121. a[14] = a[20]
  122. a[20] = a[2]
  123. a[2] = a[12]
  124. a[12] = a[13]
  125. a[13] = a[19]
  126. a[19] = a[23]
  127. a[23] = a[15]
  128. a[15] = a[4]
  129. a[4] = a[24]
  130. a[24] = a[21]
  131. a[21] = a[8]
  132. a[8] = a[16]
  133. a[16] = a[5]
  134. a[5] = a[3]
  135. a[3] = a[18]
  136. a[18] = a[17]
  137. a[17] = a[11]
  138. a[11] = a[7]
  139. a[7] = a[10]
  140. a[10] = a1
  141. }
  142. /// For all triples (x, y, z) such that 0≤x<5, 0≤y<5, and 0≤z<w, let
  143. /// A′[x, y,z] = A[x, y,z] ⊕ ((A[(x+1) mod 5, y, z] ⊕ 1) ⋅ A[(x+2) mod 5, y, z])
  144. private func χ(_ a: inout Array<UInt64>) {
  145. for i in stride(from: 0, to: 25, by: 5) {
  146. let a0 = a[0 &+ i]
  147. let a1 = a[1 &+ i]
  148. a[0 &+ i] ^= ~a1 & a[2 &+ i]
  149. a[1 &+ i] ^= ~a[2 &+ i] & a[3 &+ i]
  150. a[2 &+ i] ^= ~a[3 &+ i] & a[4 &+ i]
  151. a[3 &+ i] ^= ~a[4 &+ i] & a0
  152. a[4 &+ i] ^= ~a0 & a1
  153. }
  154. }
  155. private func ι(_ a: inout Array<UInt64>, round: Int) {
  156. a[0] ^= round_constants[round]
  157. }
  158. fileprivate func process(block chunk: ArraySlice<UInt64>, currentHash hh: inout Array<UInt64>) {
  159. // expand
  160. hh[0] ^= chunk[0].littleEndian
  161. hh[1] ^= chunk[1].littleEndian
  162. hh[2] ^= chunk[2].littleEndian
  163. hh[3] ^= chunk[3].littleEndian
  164. hh[4] ^= chunk[4].littleEndian
  165. hh[5] ^= chunk[5].littleEndian
  166. hh[6] ^= chunk[6].littleEndian
  167. hh[7] ^= chunk[7].littleEndian
  168. hh[8] ^= chunk[8].littleEndian
  169. if blockSize > 72 { // 72 / 8, sha-512
  170. hh[9] ^= chunk[9].littleEndian
  171. hh[10] ^= chunk[10].littleEndian
  172. hh[11] ^= chunk[11].littleEndian
  173. hh[12] ^= chunk[12].littleEndian
  174. if blockSize > 104 { // 104 / 8, sha-384
  175. hh[13] ^= chunk[13].littleEndian
  176. hh[14] ^= chunk[14].littleEndian
  177. hh[15] ^= chunk[15].littleEndian
  178. hh[16] ^= chunk[16].littleEndian
  179. if blockSize > 136 { // 136 / 8, sha-256
  180. hh[17] ^= chunk[17].littleEndian
  181. // FULL_SHA3_FAMILY_SUPPORT
  182. if blockSize > 144 { // 144 / 8, sha-224
  183. hh[18] ^= chunk[18].littleEndian
  184. hh[19] ^= chunk[19].littleEndian
  185. hh[20] ^= chunk[20].littleEndian
  186. hh[21] ^= chunk[21].littleEndian
  187. hh[22] ^= chunk[22].littleEndian
  188. hh[23] ^= chunk[23].littleEndian
  189. hh[24] ^= chunk[24].littleEndian
  190. }
  191. }
  192. }
  193. }
  194. // Keccak-f
  195. for round in 0..<24 {
  196. θ(&hh)
  197. hh[1] = rotateLeft(hh[1], by: 1)
  198. hh[2] = rotateLeft(hh[2], by: 62)
  199. hh[3] = rotateLeft(hh[3], by: 28)
  200. hh[4] = rotateLeft(hh[4], by: 27)
  201. hh[5] = rotateLeft(hh[5], by: 36)
  202. hh[6] = rotateLeft(hh[6], by: 44)
  203. hh[7] = rotateLeft(hh[7], by: 6)
  204. hh[8] = rotateLeft(hh[8], by: 55)
  205. hh[9] = rotateLeft(hh[9], by: 20)
  206. hh[10] = rotateLeft(hh[10], by: 3)
  207. hh[11] = rotateLeft(hh[11], by: 10)
  208. hh[12] = rotateLeft(hh[12], by: 43)
  209. hh[13] = rotateLeft(hh[13], by: 25)
  210. hh[14] = rotateLeft(hh[14], by: 39)
  211. hh[15] = rotateLeft(hh[15], by: 41)
  212. hh[16] = rotateLeft(hh[16], by: 45)
  213. hh[17] = rotateLeft(hh[17], by: 15)
  214. hh[18] = rotateLeft(hh[18], by: 21)
  215. hh[19] = rotateLeft(hh[19], by: 8)
  216. hh[20] = rotateLeft(hh[20], by: 18)
  217. hh[21] = rotateLeft(hh[21], by: 2)
  218. hh[22] = rotateLeft(hh[22], by: 61)
  219. hh[23] = rotateLeft(hh[23], by: 56)
  220. hh[24] = rotateLeft(hh[24], by: 14)
  221. π(&hh)
  222. χ(&hh)
  223. ι(&hh, round: round)
  224. }
  225. }
  226. }
  227. extension SHA3: Updatable {
  228. public func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false) throws -> Array<UInt8> {
  229. accumulated += bytes
  230. if isLast {
  231. // Add padding
  232. let markByteIndex = accumulated.count
  233. // We need to always pad the input. Even if the input is a multiple of blockSize.
  234. let r = blockSize * 8
  235. let q = (r / 8) - (accumulated.count % (r / 8))
  236. accumulated += Array<UInt8>(repeating: 0, count: q)
  237. accumulated[markByteIndex] |= markByte
  238. accumulated[self.accumulated.count - 1] |= 0x80
  239. }
  240. var processedBytes = 0
  241. for chunk in accumulated.batched(by: blockSize) {
  242. if isLast || (accumulated.count - processedBytes) >= blockSize {
  243. process(block: chunk.toUInt64Array().slice, currentHash: &accumulatedHash)
  244. processedBytes += chunk.count
  245. }
  246. }
  247. accumulated.removeFirst(processedBytes)
  248. // TODO: verify performance, reduce vs for..in
  249. let result = accumulatedHash.reduce(Array<UInt8>()) { (result, value) -> Array<UInt8> in
  250. return result + value.bigEndian.bytes()
  251. }
  252. // reset hash value for instance
  253. if isLast {
  254. accumulatedHash = Array<UInt64>(repeating: 0, count: digestLength)
  255. }
  256. return Array(result[0..<self.digestLength])
  257. }
  258. }