/// Signed tokens: claims and their HMAC-SHA256, so a token handed out can /// be trusted when it comes back. The claims are readable by anyone who /// holds the token; only the key holder can make or change them. import std/base64 import std/bytes import std/crypto import std/int import std/list import std/string /// `"{claims}.{signature}"`, the signature in base64. The claims may /// themselves hold dots. pub fn sign :: key: Bytes claims: String -> String { "{claims}.{signature key claims}" } /// The claims of `token` when `key` signed them, compared in constant /// time; `None` for a forged, altered or malformed token. pub fn verified :: key: Bytes token: String -> Option { match list.reverse (string.split token ".") { [signed, first, ..rest] -> { let claims = string.join (list.reverse [first, ..rest]) "." if same_bytes (bytes.from_string signed) (bytes.from_string (signature key claims)) { Some(claims) } else { None } } , _ -> None } } fn signature :: key: Bytes claims: String -> String { base64.encode (crypto.hmac_sha256 key (bytes.from_string claims)) } /// Whether `a` and `b` are the same bytes, in time that depends on their /// lengths only: every byte is compared, so a forger learns nothing from /// how long a refusal took. pub fn same_bytes :: a: Bytes b: Bytes -> Bool { bytes.length a == bytes.length b && list.fold (list.zip (bytes.to_list a) (bytes.to_list b)) 0 fn acc pair { int.or acc (int.xor pair.0 pair.1) } == 0 }