2024-12-10 15:47:37 +01:00
|
|
|
import pkg/nimcrypto/sha2
|
|
|
|
|
import pkg/nimcrypto/hash
|
2024-12-18 10:28:10 +01:00
|
|
|
import ./basics
|
2024-12-10 15:47:37 +01:00
|
|
|
|
2024-12-18 10:19:09 +01:00
|
|
|
export hash.`$`
|
|
|
|
|
|
2024-12-10 15:47:37 +01:00
|
|
|
type Hash* = MDigest[256]
|
|
|
|
|
|
|
|
|
|
func hash*(_: type Hash, bytes: openArray[byte]): Hash =
|
|
|
|
|
var context: sha256
|
|
|
|
|
context.init()
|
|
|
|
|
context.update(bytes)
|
|
|
|
|
result = context.finish()
|
|
|
|
|
context.clear()
|
|
|
|
|
|
2024-12-18 10:28:10 +01:00
|
|
|
func toBytes*(hash: Hash): seq[byte] =
|
|
|
|
|
@(hash.data)
|
|
|
|
|
|
|
|
|
|
func fromBytes*(_: type Hash, bytes: openArray[byte]): ?!Hash =
|
|
|
|
|
if bytes.len != 32:
|
|
|
|
|
return failure "expected hash of 32 bytes, but got: " & $bytes.len
|
|
|
|
|
var data: array[32, byte]
|
|
|
|
|
data[0..<32] = bytes[0..<32]
|
|
|
|
|
success Hash(data: data)
|