sha1.nim 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2015 Nim Contributors
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## [SHA-1 (Secure Hash Algorithm 1)](https://en.wikipedia.org/wiki/SHA-1)
  10. ## is a cryptographic hash function which takes an input and produces
  11. ## a 160-bit (20-byte) hash value known as a message digest.
  12. ##
  13. ## See also
  14. ## ========
  15. ## * `base64 module<base64.html>`_ implements a Base64 encoder and decoder
  16. ## * `hashes module<hashes.html>`_ for efficient computations of hash values for diverse Nim types
  17. ## * `md5 module<md5.html>`_ implements the MD5 checksum algorithm
  18. runnableExamples:
  19. let accessName = secureHash("John Doe")
  20. assert $accessName == "AE6E4D1209F17B460503904FAD297B31E9CF6362"
  21. runnableExamples("-r:off"):
  22. let
  23. a = secureHashFile("myFile.nim")
  24. b = parseSecureHash("10DFAEBF6BFDBC7939957068E2EFACEC4972933C")
  25. assert a == b, "files don't match"
  26. import std/strutils
  27. from std/endians import bigEndian32, bigEndian64
  28. const Sha1DigestSize = 20
  29. type
  30. Sha1Digest* = array[0 .. Sha1DigestSize - 1, uint8]
  31. SecureHash* = distinct Sha1Digest
  32. type
  33. Sha1State* = object
  34. count: int
  35. state: array[5, uint32]
  36. buf: array[64, byte]
  37. # This implementation of the SHA-1 algorithm was ported from the Chromium OS one
  38. # with minor modifications that should not affect its functionality.
  39. proc newSha1State*(): Sha1State =
  40. ## Creates a `Sha1State`.
  41. ##
  42. ## If you use the `secureHash proc <#secureHash,openArray[char]>`_,
  43. ## there's no need to call this function explicitly.
  44. result.count = 0
  45. result.state[0] = 0x67452301'u32
  46. result.state[1] = 0xEFCDAB89'u32
  47. result.state[2] = 0x98BADCFE'u32
  48. result.state[3] = 0x10325476'u32
  49. result.state[4] = 0xC3D2E1F0'u32
  50. template ror27(val: uint32): uint32 = (val shr 27) or (val shl 5)
  51. template ror2 (val: uint32): uint32 = (val shr 2) or (val shl 30)
  52. template ror31(val: uint32): uint32 = (val shr 31) or (val shl 1)
  53. proc transform(ctx: var Sha1State) =
  54. var w: array[80, uint32]
  55. var a, b, c, d, e: uint32
  56. var t = 0
  57. a = ctx.state[0]
  58. b = ctx.state[1]
  59. c = ctx.state[2]
  60. d = ctx.state[3]
  61. e = ctx.state[4]
  62. template shaF1(a, b, c, d, e, t: untyped) =
  63. bigEndian32(addr w[t], addr ctx.buf[t * 4])
  64. e += ror27(a) + w[t] + (d xor (b and (c xor d))) + 0x5A827999'u32
  65. b = ror2(b)
  66. while t < 15:
  67. shaF1(a, b, c, d, e, t + 0)
  68. shaF1(e, a, b, c, d, t + 1)
  69. shaF1(d, e, a, b, c, t + 2)
  70. shaF1(c, d, e, a, b, t + 3)
  71. shaF1(b, c, d, e, a, t + 4)
  72. t += 5
  73. shaF1(a, b, c, d, e, t + 0) # 16th one, t == 15
  74. template shaF11(a, b, c, d, e, t: untyped) =
  75. w[t] = ror31(w[t-3] xor w[t-8] xor w[t-14] xor w[t-16])
  76. e += ror27(a) + w[t] + (d xor (b and (c xor d))) + 0x5A827999'u32
  77. b = ror2(b)
  78. shaF11(e, a, b, c, d, t + 1)
  79. shaF11(d, e, a, b, c, t + 2)
  80. shaF11(c, d, e, a, b, t + 3)
  81. shaF11(b, c, d, e, a, t + 4)
  82. template shaF2(a, b, c, d, e, t: untyped) =
  83. w[t] = ror31(w[t-3] xor w[t-8] xor w[t-14] xor w[t-16])
  84. e += ror27(a) + w[t] + (b xor c xor d) + 0x6ED9EBA1'u32
  85. b = ror2(b)
  86. t = 20
  87. while t < 40:
  88. shaF2(a, b, c, d, e, t + 0)
  89. shaF2(e, a, b, c, d, t + 1)
  90. shaF2(d, e, a, b, c, t + 2)
  91. shaF2(c, d, e, a, b, t + 3)
  92. shaF2(b, c, d, e, a, t + 4)
  93. t += 5
  94. template shaF3(a, b, c, d, e, t: untyped) =
  95. w[t] = ror31(w[t-3] xor w[t-8] xor w[t-14] xor w[t-16])
  96. e += ror27(a) + w[t] + ((b and c) or (d and (b or c))) + 0x8F1BBCDC'u32
  97. b = ror2(b)
  98. while t < 60:
  99. shaF3(a, b, c, d, e, t + 0)
  100. shaF3(e, a, b, c, d, t + 1)
  101. shaF3(d, e, a, b, c, t + 2)
  102. shaF3(c, d, e, a, b, t + 3)
  103. shaF3(b, c, d, e, a, t + 4)
  104. t += 5
  105. template shaF4(a, b, c, d, e, t: untyped) =
  106. w[t] = ror31(w[t-3] xor w[t-8] xor w[t-14] xor w[t-16])
  107. e += ror27(a) + w[t] + (b xor c xor d) + 0xCA62C1D6'u32
  108. b = ror2(b)
  109. while t < 80:
  110. shaF4(a, b, c, d, e, t + 0)
  111. shaF4(e, a, b, c, d, t + 1)
  112. shaF4(d, e, a, b, c, t + 2)
  113. shaF4(c, d, e, a, b, t + 3)
  114. shaF4(b, c, d, e, a, t + 4)
  115. t += 5
  116. ctx.state[0] += a
  117. ctx.state[1] += b
  118. ctx.state[2] += c
  119. ctx.state[3] += d
  120. ctx.state[4] += e
  121. proc update*(ctx: var Sha1State, data: openArray[char]) =
  122. ## Updates the `Sha1State` with `data`.
  123. ##
  124. ## If you use the `secureHash proc <#secureHash,openArray[char]>`_,
  125. ## there's no need to call this function explicitly.
  126. var i = ctx.count mod 64
  127. var j = 0
  128. var len = data.len
  129. # Gather 64-bytes worth of data in order to perform a round with the leftover
  130. # data we had stored (but not processed yet)
  131. if len > 64 - i:
  132. copyMem(addr ctx.buf[i], unsafeAddr data[j], 64 - i)
  133. len -= 64 - i
  134. j += 64 - i
  135. transform(ctx)
  136. # Update the index since it's used in the while loop below _and_ we want to
  137. # keep its value if this code path isn't executed
  138. i = 0
  139. # Process the bulk of the payload
  140. while len >= 64:
  141. copyMem(addr ctx.buf[0], unsafeAddr data[j], 64)
  142. len -= 64
  143. j += 64
  144. transform(ctx)
  145. # Process the tail of the payload (len is < 64)
  146. while len > 0:
  147. dec len
  148. ctx.buf[i] = byte(data[j])
  149. inc i
  150. inc j
  151. if i == 64:
  152. transform(ctx)
  153. i = 0
  154. ctx.count += data.len
  155. proc finalize*(ctx: var Sha1State): Sha1Digest =
  156. ## Finalizes the `Sha1State` and returns a `Sha1Digest`.
  157. ##
  158. ## If you use the `secureHash proc <#secureHash,openArray[char]>`_,
  159. ## there's no need to call this function explicitly.
  160. var cnt = uint64(ctx.count * 8)
  161. # a 1 bit
  162. update(ctx, "\x80")
  163. # Add padding until we reach a complexive size of 64 - 8 bytes
  164. while (ctx.count mod 64) != (64 - 8):
  165. update(ctx, "\x00")
  166. # The message length as a 64bit BE number completes the block
  167. var tmp: array[8, char]
  168. bigEndian64(addr tmp[0], addr cnt)
  169. update(ctx, tmp)
  170. # Turn the result into a single 160-bit number
  171. for i in 0 ..< 5:
  172. bigEndian32(addr ctx.state[i], addr ctx.state[i])
  173. copyMem(addr result[0], addr ctx.state[0], Sha1DigestSize)
  174. # Public API
  175. proc secureHash*(str: openArray[char]): SecureHash =
  176. ## Generates a `SecureHash` from `str`.
  177. ##
  178. ## **See also:**
  179. ## * `secureHashFile proc <#secureHashFile,string>`_ for generating a `SecureHash` from a file
  180. ## * `parseSecureHash proc <#parseSecureHash,string>`_ for converting a string `hash` to `SecureHash`
  181. runnableExamples:
  182. let hash = secureHash("Hello World")
  183. assert hash == parseSecureHash("0A4D55A8D778E5022FAB701977C5D840BBC486D0")
  184. var state = newSha1State()
  185. state.update(str)
  186. SecureHash(state.finalize())
  187. proc secureHashFile*(filename: string): SecureHash =
  188. ## Generates a `SecureHash` from a file.
  189. ##
  190. ## **See also:**
  191. ## * `secureHash proc <#secureHash,openArray[char]>`_ for generating a `SecureHash` from a string
  192. ## * `parseSecureHash proc <#parseSecureHash,string>`_ for converting a string `hash` to `SecureHash`
  193. const BufferLength = 8192
  194. let f = open(filename)
  195. var state = newSha1State()
  196. var buffer = newString(BufferLength)
  197. while true:
  198. let length = readChars(f, buffer)
  199. if length == 0:
  200. break
  201. buffer.setLen(length)
  202. state.update(buffer)
  203. if length != BufferLength:
  204. break
  205. close(f)
  206. SecureHash(state.finalize())
  207. proc `$`*(self: SecureHash): string =
  208. ## Returns the string representation of a `SecureHash`.
  209. ##
  210. ## **See also:**
  211. ## * `secureHash proc <#secureHash,openArray[char]>`_ for generating a `SecureHash` from a string
  212. runnableExamples:
  213. let hash = secureHash("Hello World")
  214. assert $hash == "0A4D55A8D778E5022FAB701977C5D840BBC486D0"
  215. result = ""
  216. for v in Sha1Digest(self):
  217. result.add(toHex(int(v), 2))
  218. proc parseSecureHash*(hash: string): SecureHash =
  219. ## Converts a string `hash` to a `SecureHash`.
  220. ##
  221. ## **See also:**
  222. ## * `secureHash proc <#secureHash,openArray[char]>`_ for generating a `SecureHash` from a string
  223. ## * `secureHashFile proc <#secureHashFile,string>`_ for generating a `SecureHash` from a file
  224. runnableExamples:
  225. let
  226. hashStr = "0A4D55A8D778E5022FAB701977C5D840BBC486D0"
  227. secureHash = secureHash("Hello World")
  228. assert secureHash == parseSecureHash(hashStr)
  229. for i in 0 ..< Sha1DigestSize:
  230. Sha1Digest(result)[i] = uint8(parseHexInt(hash[i*2] & hash[i*2 + 1]))
  231. proc `==`*(a, b: SecureHash): bool =
  232. ## Checks if two `SecureHash` values are identical.
  233. runnableExamples:
  234. let
  235. a = secureHash("Hello World")
  236. b = secureHash("Goodbye World")
  237. c = parseSecureHash("0A4D55A8D778E5022FAB701977C5D840BBC486D0")
  238. assert a != b
  239. assert a == c
  240. # Not a constant-time comparison, but that's acceptable in this context
  241. Sha1Digest(a) == Sha1Digest(b)