packages
The Louise packages, each released on its own
Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.
Dernier runRéussi#28 · main · 3 min 34 s
0Étoiles
0Forks
3Issues
| 1 | /// Signed tokens: claims and their HMAC-SHA256, so a token handed out can |
| 2 | /// be trusted when it comes back. The claims are readable by anyone who |
| 3 | /// holds the token; only the key holder can make or change them. |
| 4 | |
| 5 | import std/base64 |
| 6 | import std/bytes |
| 7 | import std/crypto |
| 8 | import std/int |
| 9 | import std/list |
| 10 | import std/string |
| 11 | |
| 12 | /// `"{claims}.{signature}"`, the signature in base64. The claims may |
| 13 | /// themselves hold dots. |
| 14 | pub fn sign :: key: Bytes claims: String -> String |
| 15 | { |
| 16 | "{claims}.{signature key claims}" |
| 17 | } |
| 18 | |
| 19 | /// The claims of `token` when `key` signed them, compared in constant |
| 20 | /// time; `None` for a forged, altered or malformed token. |
| 21 | pub fn verified :: key: Bytes token: String -> Option<String> |
| 22 | { |
| 23 | match list.reverse (string.split token ".") |
| 24 | { [signed, first, ..rest] -> |
| 25 | { |
| 26 | let claims = string.join (list.reverse [first, ..rest]) "." |
| 27 | if same_bytes |
| 28 | (bytes.from_string signed) |
| 29 | (bytes.from_string (signature key claims)) |
| 30 | { |
| 31 | Some(claims) |
| 32 | } |
| 33 | else |
| 34 | { |
| 35 | None |
| 36 | } |
| 37 | } |
| 38 | , _ -> None |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | fn signature :: key: Bytes claims: String -> String |
| 43 | { |
| 44 | base64.encode (crypto.hmac_sha256 key (bytes.from_string claims)) |
| 45 | } |
| 46 | |
| 47 | /// Whether `a` and `b` are the same bytes, in time that depends on their |
| 48 | /// lengths only: every byte is compared, so a forger learns nothing from |
| 49 | /// how long a refusal took. |
| 50 | pub fn same_bytes :: a: Bytes b: Bytes -> Bool |
| 51 | { |
| 52 | bytes.length a == bytes.length b |
| 53 | && list.fold |
| 54 | (list.zip (bytes.to_list a) (bytes.to_list b)) |
| 55 | 0 |
| 56 | fn acc pair { int.or acc (int.xor pair.0 pair.1) } |
| 57 | == 0 |
| 58 | } |