Skip to content

Commit

Permalink
add SHA512, export hash_*
Browse files Browse the repository at this point in the history
  • Loading branch information
ba0f3 committed Jul 1, 2017
1 parent bdc34af commit c9a84ea
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 11 deletions.
22 changes: 13 additions & 9 deletions hmac.nim
Original file line number Diff line number Diff line change
Expand Up @@ -15,28 +15,29 @@ import securehash, md5, nimSHA2, strutils
type
Sha1Digest = array[20, uint8]

proc hash_sha1(s: string): SecureHash {.procvar.} =
proc hash_sha1*(s: string): SecureHash {.procvar.} =
secureHash(s)

proc hash_sha256(s: string): SHA256Digest {.procvar.} =
proc hash_sha256*(s: string): SHA256Digest {.procvar.} =
computeSHA256(s)

proc hash_md5(s: string): MD5Digest {.procvar.} =
toMD5(s)
proc hash_sha512*(s: string): SHA512Digest {.procvar.} =
computeSHA512(s)

proc hash_md5*(s: string): MD5Digest {.procvar.} =
toMD5(s)

iterator items(s: SecureHash): uint8 =
for n in Sha1Digest(s):
yield n

proc `%`*[T: SecureHash|SHA256Digest|MD5Digest](x: T): string =
proc `%`*[T](x: T): string =
when x is SecureHash:
toLower($x)
elif x is SHA256Digest:
toLower(nimSHA2.toHex(x))
elif x is MD5Digest:
$x
else:
discard
toLower(nimSHA2.toHex(x))

template hmac_x[T](key, data: string, hash: proc(s: string): T, digest_size: int, block_size = 64, opad = 0x5c, ipad = 0x36): stmt =
var keyA: seq[uint8] = @[]
Expand Down Expand Up @@ -66,7 +67,10 @@ proc hmac_sha1*(key, data: string, block_size = 64, opad = 0x5c, ipad = 0x36): S
hmac_x(key, data, hash_sha1, 20, block_size, opad, ipad)

proc hmac_sha256*(key, data: string, block_size = 64, opad = 0x5c, ipad = 0x36): SHA256Digest =
hmac_x(key, data, hash_sha256, 32, block_size, opad, ipad)
hmac_x(key, data, hash_sha256, 32, block_size, opad, ipad)

proc hmac_sha512*(key, data: string, block_size = 64, opad = 0x5c, ipad = 0x36): SHA512Digest =
hmac_x(key, data, hash_sha512, 32, block_size, opad, ipad)

proc hmac_md5*(key, data: string): MD5Digest =
hmac_x(key, data, hash_md5, 16)
Expand Down
4 changes: 2 additions & 2 deletions hmac.nimble
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
version = "0.1.2"
version = "0.1.3"
author = "Huy Doan"
description = "HMAC hashing in Nim"
license = "MIT"

requires "nim", "nimSHA2"
requires "nim", "nimSHA2"

0 comments on commit c9a84ea

Please sign in to comment.