sha1.nim 8.7 KB

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