Skip to content

hash

SHA-256 digests and HMAC-SHA-256 signatures, returned as lowercase hex text.

Every function takes a &Str. A Str can hold any bytes, so the input may be text or binary data (for example the output of gzip.compress or random.secure_bytes). The result is always 64 hex digits. To get the 32 raw bytes instead, pass the hex to encoding.from_hex.

Hash some data:

import hash
print(hash.sha256(&"abc"))
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad

Sign a message with a shared key, and check a signature that came back. Compare signatures with equal_secret, not ==:

import hash
let key = "server secret"
let body = "user=ann&role=admin"
let signature = hash.hmac_sha256(&key, &body)
print(signature.len())
let received = signature.clone()
if hash.equal_secret(&hash.hmac_sha256(&key, &body), &received) {
print("signature ok")
}
64
signature ok

The raw digest, base64-encoded, as some protocols want it:

import hash
import encoding
let raw = try encoding.from_hex(&hash.sha256(&"abc"))
print(raw.len())
print(encoding.base64(&raw))
32
ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0=

SHA-256 is fast on purpose. Do not use it alone to store passwords; there is no password-hashing function (bcrypt, scrypt, argon2) in the standard library.

import hash
pub fn sha256(data: &Str) -> Str

The SHA-256 digest of the bytes of data, as 64 lowercase hex digits.

pub fn hmac_sha256(key: &Str, data: &Str) -> Str

HMAC-SHA-256 of data under key, as 64 lowercase hex digits.

pub fn equal_secret(a: &Str, b: &Str) -> bool

Compares secrets (like two HMACs) in a time that does not reveal where they differ.

== on strings stops at the first differing byte, so the time it takes leaks how much of a guess was right. equal_secret always looks at every byte. Use it for signatures, tokens and other secrets. Strings of different lengths compare unequal; the length itself is not treated as secret.