Module std::crypto::crypto

Cryptographic hashing and utilities.

Provides SHA-2 hash functions (SHA-256, SHA-384, SHA-512), HMAC-SHA-256 message authentication, secure random byte generation, and constant-time comparison.

Examples

import std.crypto.crypto;
import std.encoding.hex;

fn main() {
    let hash = crypto.sha256("A".to_bytes());
    println(hex.encode(hash));
}

"...".to_bytes() is the canonical string-to-bytes conversion โ€” use it to build the bytes payload any hashing/HMAC/network function here expects from a string you already have, instead of hand-rolling a bytes buffer byte-by-byte with bytes.new() + .push().

Contents

Functions

Function sha256

pub fn sha256(data: bytes) -> bytes

Compute the SHA-256 hash of data, returning a 32-byte digest.

Function sha384

pub fn sha384(data: bytes) -> bytes

Compute the SHA-384 hash of data, returning a 48-byte digest.

Function sha512

pub fn sha512(data: bytes) -> bytes

Compute the SHA-512 hash of data, returning a 64-byte digest.

Function hmac_sha256

pub fn hmac_sha256(key: bytes, data: bytes) -> bytes

Compute HMAC-SHA-256 with the given key and data.

Returns a 32-byte tag.

Function random_bytes

pub fn random_bytes(len: i64) -> Result<bytes, string>

Generate len cryptographically random bytes, reporting a request that could not be served.

An empty result is only ever a len == 0 draw. A negative length, a length above max_random_bytes_len(), and an entropy-source failure are reported as Err rather than returned as an empty buffer or answered by terminating the process.

Function max_random_bytes_len

pub fn max_random_bytes_len() -> i64

Largest random-byte request accepted by random_bytes (16 MiB).

Function constant_time_eq

pub fn constant_time_eq(a: bytes, b: bytes) -> bool

Compare two bytes values in constant time.

Returns true if they are equal (same length and same content). Always runs in time proportional to the length to avoid timing leaks.