Module std.crypto.hash
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.hash;
import std.encoding.hex;
fn main() {
let hash = hash.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
- fn sha256
- fn sha384
- fn sha512
- fn hmac_sha256
- fn random_bytes
- fn max_random_bytes_len
- fn constant_time_eq
- enum RandomError
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) -> bytes fails RandomError
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 fail rather
than return an empty buffer or terminate 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.
Types
Enum RandomError
A random-byte request that could not be served.
Variants
NegativeLength(i64)The requested length, which is negative.
TooLong { len: i64, max: i64 }The requested length, which exceeds
max_random_bytes_len().EntropyUnavailableThe system entropy source failed.
Failed(i64)The native draw failed with an unrecognized status.