std.crypto

Hashes and secure random bytes:

import std.crypto

print(crypto.sha256_hex("hello"))
let mac = crypto.hmac_sha256("secret".bytes(), "message".bytes())
let token = crypto.hex(crypto.random_bytes(16))

Bytes are List[u8]; text.bytes() gives a string's UTF-8 bytes. MD5 is only for systems that still ask for it.

Functions

fn sha256

pub fn sha256(data: List[u8]) -> List[u8]

The SHA-256 hash of bytes (32 bytes).

fn sha256_hex

pub fn sha256_hex(text: string) -> string

The SHA-256 hash of a string's UTF-8 bytes, as 64 hex digits.

fn hmac_sha256

pub fn hmac_sha256(key: List[u8], message: List[u8]) -> List[u8]

HMAC-SHA-256 of message with key (32 bytes).

fn pbkdf2_sha256

pub fn pbkdf2_sha256(password: List[u8], salt: List[u8], iterations: i64, length: i64) -> List[u8]

PBKDF2 with HMAC-SHA-256 (RFC 8018): a key of length bytes from a password and a salt, made slow by iterations rounds. Also a way to store passwords: keep the salt, the count and the result.

fn md5

pub fn md5(data: List[u8]) -> List[u8]

The MD5 hash of bytes (16 bytes). MD5 is broken: use it only where another system requires it.

fn random_bytes

pub fn random_bytes(n: i64) -> List[u8]

n bytes from the operating system's secure random source, for keys, tokens and nonces (unlike std.random).

fn hex

pub fn hex(data: List[u8]) -> string

Bytes as lower-case hex digits: [1, 171] is "01ab".

fn equal

pub fn equal(a: List[u8], b: List[u8]) -> bool

Whether two byte lists are equal, taking as long whatever the first difference, so comparing a secret does not tell where it differs.