Module hash

This module provides helper procedures for calculating secure digests supported by nimcrypto library.

Types

MDigest[bits] = object
  data*: array[bits div 8, byte]
Message digest type
bchar = byte | char

Consts

MaxMDigestLength = 64
Maximum size of generated digests by nimcrypto library is 64 octets.

Procs

proc `$`(digest: MDigest): string
Return hexadecimal string representation of digest.

import nimcrypto

var digestHexString = $sha256.digest("Hello World!")
echo digestHexString

proc digest(HashType: typedesc; data: ptr byte; ulen: uint): MDigest[HashType.bits]
Calculate and return digest using algorithm HashType of data data with length ulen.

import nimcrypto

var stringToHash = "Hello World!"
let data = cast[ptr byte](addr stringToHash[0])
let datalen = uint(len(stringToHash))
echo sha256.digest(data, datalen)

proc digest[T](HashType: typedesc; data: openArray[T]; ostart: int = 0;
              ofinish: int = -1): MDigest[HashType.bits]
Calculate and return digest using algorithm HashType of data data in slice [ostart, ofinish], both ostart and ofinish are inclusive.

import nimcrypto

var stringToHash = "Hello World!"
## Calculate digest of whole string `Hello World!`.
echo sha256.digest(stringToHash)
## Calcualte digest of `Hello`.
echo sha256.digest(stringToHash, ofinish = 4)
## Calculate digest of `World!`.
echo sha256.digest(stringToHash, ostart = 6)
## Calculate digest of constant `Hello`.
echo sha256.digest("Hello")
## Calculate digest of constant `World!`.
echo sha256.digest("World!")

proc fromHex(T: typedesc[MDigest]; s: string): T:type
Create MDigest object from hexadecimal string representation.

import nimcrypto

var a = MDigest[256].fromHex("7F83B1657FF1FC53B92DC18148A1D65DFC2D4B1FA3D677284ADDD200126D9069")
echo $a
## Get number of bits used by ``a``.
echo a.bits

proc `==`[A, B](d1: MDigest[A]; d2: MDigest[B]): bool
Check for equality between two MDigest objects d1 and d2. If size in bits of d1 is not equal to size in bits of d2 then digests considered as not equal.

Templates

template toDigest(s: static string): auto
Convert hexadecimal string representation to MDigest object. This template can be used to create MDigest constants.

import nimcrypto

const SomeDigest = "7F83B1657FF1FC53B92DC18148A1D65DFC2D4B1FA3D677284ADDD200126D9069".toDigest
echo $SomeDigest
## Get number of bits used by ``SomeDigest``.
echo SomeDigest.bits