Functions for creating and parsing signed & encrypted cookies.
The cookie crate is the de facto secure cookie library in Rust. It is Way Too Complicated (TM) for what I need. (And, in my opinion, for what most people need.) This is the 80% solution for 20% of the effort.
This library has only two goals:
- A simple, easily auditable implementation of signing, encrypting, decrypting & verifying cookies.
- Clear comments pointing out security issues and describing how to avoid them.
The goals of this library are not:
- Automatically detecting when a new Set-Cookie header is required.
- Tracking changes to cookies.
- Validating cookie name compliance with RFC6265. (Just don't use any weird cookie names.)
- Any kind of cookie "jar" functionality.
- Literally anything else.
Examples
Basic use:
use ;
let signing_key = generate_signing_key;
let encoded = encode_cookie;
let decoded = decode_cookie;
assert_eq!;
You probably want an actual Set-Cookie header. You can build one pretty easily:
use ;
let signing_key = generate_signing_key;
let encoded = encode_cookie;
let header = format!;
Then, to decrypt a header:
use ;
// You can create your own key or load it from somewhere.
// Don't use all zeros like this though. See the documentation for SigningKey for more info.
let signing_key = ;
// This is a standard HTTP Cookie header, pretty much exactly what the browser sends to your server.
let header = b"Cookie: session=gNm1wQ6lTTgAxLxfD2ntNS2nIBVcnjSmI+7FdFk; another-cookie=another-value";
// parse_cookie_header_value doesn't expect the header name.
// You don't normally need this step since HTTP libraries typically automatically parse
// the header name & value into separate parts of a tuple or struct or something.
let header = &header;
// parse_cookie_header_value returns an iterator, so you can use it in a for loop or something.
// I'll just find the cookie we're interested in here.
let = parse_cookie_header_value.find.unwrap;
let value = decode_cookie;
assert!