sha1.nim 8.6 KB

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