SHA3.swift 10 KB

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