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"))ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015adSign 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")}64signature okThe raw digest, base64-encoded, as some protocols want it:
import hashimport encoding
let raw = try encoding.from_hex(&hash.sha256(&"abc"))print(raw.len())print(encoding.base64(&raw))32ungWv48Bz+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.
Reference
Section titled “Reference”import hashFunctions
Section titled “Functions”sha256
Section titled “sha256”pub fn sha256(data: &Str) -> StrThe SHA-256 digest of the bytes of data, as 64 lowercase hex digits.
hmac_sha256
Section titled “hmac_sha256”pub fn hmac_sha256(key: &Str, data: &Str) -> StrHMAC-SHA-256 of data under key, as 64 lowercase hex digits.
equal_secret
Section titled “equal_secret”pub fn equal_secret(a: &Str, b: &Str) -> boolCompares 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.