sha1

Note: Import std/sha1 to use this module.

SHA-1 (Secure Hash Algorithm 1) is a cryptographic hash function which takes an input and produces a 160-bit (20-byte) hash value known as a message digest.

Basic usage

Example:

let accessName = secureHash("John Doe")
assert $accessName == "AE6E4D1209F17B460503904FAD297B31E9CF6362"
let
  a = secureHashFile("myFile.nim")
  b = parseSecureHash("10DFAEBF6BFDBC7939957068E2EFACEC4972933C")

if a == b:
  echo "Files match"

See also

  • base64 module implements a Base64 encoder and decoder
  • hashes module for efficient computations of hash values for diverse Nim types
  • md5 module implements the MD5 checksum algorithm

Imports

strutils, endians

Types

Sha1Digest = array[0 .. 20 - 1, uint8]
Source Edit
SecureHash = distinct Sha1Digest
Source Edit
Sha1State = object
  count: int
  state: array[5, uint32]
  buf: array[64, byte]
Source Edit

Procs

proc newSha1State(): Sha1State {...}{.raises: [], tags: [].}

Creates a Sha1State.

If you use the secureHash proc, there's no need to call this function explicitly.

Source Edit
proc update(ctx: var Sha1State; data: openArray[char]) {...}{.raises: [], tags: [].}

Updates the Sha1State with data.

If you use the secureHash proc, there's no need to call this function explicitly.

Source Edit
proc finalize(ctx: var Sha1State): Sha1Digest {...}{.raises: [], tags: [].}

Finalizes the Sha1State and returns a Sha1Digest.

If you use the secureHash proc, there's no need to call this function explicitly.

Source Edit
proc secureHash(str: openArray[char]): SecureHash {...}{.raises: [], tags: [].}

Generates a SecureHash from str.

See also:

Example:

let hash = secureHash("Hello World")
assert hash == parseSecureHash("0A4D55A8D778E5022FAB701977C5D840BBC486D0")
Source Edit
proc secureHashFile(filename: string): SecureHash {...}{.raises: [IOError],
    tags: [ReadIOEffect].}

Generates a SecureHash from a file.

See also:

Source Edit
proc `$`(self: SecureHash): string {...}{.raises: [], tags: [].}

Returns the string representation of a SecureHash.

See also:

Example:

let hash = secureHash("Hello World")
assert $hash == "0A4D55A8D778E5022FAB701977C5D840BBC486D0"
Source Edit
proc parseSecureHash(hash: string): SecureHash {...}{.raises: [ValueError], tags: [].}

Converts a string hash to a SecureHash.

See also:

Example:

let
  hashStr = "0A4D55A8D778E5022FAB701977C5D840BBC486D0"
  secureHash = secureHash("Hello World")
assert secureHash == parseSecureHash(hashStr)
Source Edit
proc `==`(a, b: SecureHash): bool {...}{.raises: [], tags: [].}
Checks if two SecureHash values are identical.

Example:

let
  a = secureHash("Hello World")
  b = secureHash("Goodbye World")
  c = parseSecureHash("0A4D55A8D778E5022FAB701977C5D840BBC486D0")
assert a != b
assert a == c
Source Edit

© 2006–2021 Andreas Rumpf
Licensed under the MIT License.
https://nim-lang.org/docs/sha1.html