Skip to content
CryoCryo home
Stdlibhash

sha256

import std::hash::sha256; · source

SHA-256, as FIPS 180-4 defines it, in pure Cryo.

Types

Sha256

type struct Sha256 {
    private state:          [u32; 8];
    private block:          [u8; 64];
    private buffered:       i64;
    private message_length: u64;
}

A computation in progress. update feeds the message in pieces, in order, and finish consumes the computation and gives the digest. Sha256::digest hashes one message held whole.

import std::hash::sha256::{ Sha256, Sha256Digest };
import std::fmt::{ println };

function main() -> int {
    const digest: Sha256Digest = Sha256::digest(Str::new("abc").as_bytes());
    println(f"{digest}");   // ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad

    mut hasher: Sha256 = Sha256::new();
    hasher.update(Str::new("a").as_bytes());
    hasher.update(Str::new("bc").as_bytes());
    const same: Sha256Digest = hasher.finish();   // equal to `digest`
    return if (same == digest) { 0 } else { 1 };
}

Constructors

static new() -> Sha256;

A computation over the empty message.

Static functions

static digest(data: &Slice<u8>) -> Sha256Digest;

The digest of data, held whole.

Methods

update(mut &this, data: &Slice<u8>) -> void;

Append data to the message.

finish(mut this) -> Sha256Digest;

Close the message and give its digest.

Sha256Digest

type struct Sha256Digest with [Eq] {
    private bytes: [u8; 32];
}

The hash's 32 bytes in the order the standard writes them, most significant byte of the first word first. It displays, and to_hex writes it, as 64 lowercase hexadecimal digits.

Methods

as_bytes(&this) -> &Slice<u8>;

The digest's bytes.

to_hex(&this) -> String;

The digest as 64 lowercase hexadecimal digits.

Trait implementations

implement trait Display for struct Sha256Digest

Constants

const DIGEST_LENGTH: i64 = 32;
const BLOCK_LENGTH:  i64 = 64;