### PasetoNonce Struct and Usage Example Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/core/struct.PasetoNonce.html Demonstrates the definition of the PasetoNonce struct and provides an example of its usage in creating a PASETO token with a symmetric key and a randomly generated nonce. ```APIDOC ## Struct PasetoNonce ### Description A nonce key for use in PASETO algorithms. Key sizes for nonces are either 32 or 24 bytes in size. Nonces can be specified directly for testing or randomly in production. ### Example Usage ```rust use serde_json::json; use rusty_paseto::core::*; let key = PasetoSymmetricKey::::from(Key::<32>::try_from("707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f")?); // generate a random nonce with let nonce = Key::<32>::try_new_random()?; let nonce = PasetoNonce::::from(&nonce); let payload = json!({"data": "this is a secret message", "exp":"2022-01-01T00:00:00+00:00"}).to_string(); let payload = payload.as_str(); let payload = Payload::from(payload); //create a public v4 token let token = Paseto::::builder() .set_payload(payload) .try_encrypt(&key, &nonce)?; ``` ``` -------------------------------- ### starts_with Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/core/struct.PasetoNonce.html Checks if the slice starts with a specific prefix. ```APIDOC ## starts_with ### Description Returns true if the provided needle is a prefix of the slice or equal to the slice. ### Parameters - **needle** (&[T]) - Required - The prefix to check. ### Response - **bool** - True if it starts with the needle. ``` -------------------------------- ### Error Example: Using Reserved Key in Custom Claim Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/index.html This example demonstrates an error scenario where a reserved PASETO claim key ('exp') is used with `CustomClaim`. The correct approach is to use the specific claim type, like `ExpirationClaim`. ```rust # #[cfg(feature = "v4_local")] # { # use rusty_paseto::prelude::*; # // must include # use std::convert::TryFrom; # let key = PasetoSymmetricKey::::from(Key::from(b"wubbalubbadubdubwubbalubbadubdub")); // "exp" is a reserved PASETO claim key, you should use the ExpirationClaim type let token = PasetoBuilder::::default() .set_claim(CustomClaim::try_from(("exp", "Some expiration value"))?) .build(&key)?; # } # Ok::<(),anyhow::Error>(()) ``` -------------------------------- ### Get Slice Length Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/core/struct.PasetoNonce.html Provides an example of how to get the number of elements in a slice. ```rust let a = [1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### Add a claim to PasetoBuilder Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/prelude/struct.PasetoBuilder.html Example of adding a claim to the builder before encryption. ```rust use rusty_paseto::prelude::*; let key = PasetoSymmetricKey::::from(Key::<32>::from(*b"wubbalubbadubdubwubbalubbadubdub")); //create a builder, add some claims and then build the token with the key let token = PasetoBuilder::::default() .set_claim(AudienceClaim::from("customers")) .try_encrypt(&key)?; ``` -------------------------------- ### GET /get Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/generic/type.ValidatorMap.html Retrieves a reference to the value corresponding to the provided key. ```APIDOC ## GET /get ### Description Returns a reference to the value corresponding to the key. The key may be any borrowed form of the map’s key type. ### Parameters #### Query Parameters - **k** (Q) - Required - The key to look up in the map. ``` -------------------------------- ### Configure valid feature combinations Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/index.html Examples of valid Cargo.toml configurations for single or multiple PASETO versions and purposes. ```toml # Single version + purpose ✅ rusty_paseto = { version = "latest", features = ["v4_local"] } rusty_paseto = { version = "latest", features = ["v4_public"] } # Same version, both purposes ✅ rusty_paseto = { version = "latest", features = ["v4_local", "v4_public"] } # Default (recommended) ✅ # Enables: batteries_included + v4_local + v4_public rusty_paseto = "latest" ``` -------------------------------- ### Example: Secure Usage Pattern for PasetoAsymmetricPrivateKey Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/core/struct.PasetoAsymmetricPrivateKey.html Demonstrates a secure usage pattern for PasetoAsymmetricPrivateKey by using a Key<64> which zeroizes on drop, ensuring memory safety. This pattern minimizes the lifetime of the borrowed key material. ```rust // Good: Key<64> zeroizes on drop let key_bytes = Key::<64>::try_new_random()?; let private_key = PasetoAsymmetricPrivateKey::::from(&key_bytes); // ... use private_key ... // key_bytes will be zeroized when dropped ``` -------------------------------- ### Set a footer on a token Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/prelude/struct.PasetoBuilder.html Example of adding an optional footer to the PASETO token. ```rust use rusty_paseto::prelude::*; let key = PasetoSymmetricKey::::from(Key::<32>::from(*b"wubbalubbadubdubwubbalubbadubdub")); let token = PasetoBuilder::::default() .set_footer(Footer::from("Some footer")) .build(&key)?; ``` -------------------------------- ### Paseto Token Encryption and Decryption (V4 Local) Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/core/struct.Paseto.html Demonstrates how to create and encrypt a PASETO token using a symmetric key and a nonce, and subsequently decrypt it. This example uses V4 and Local purpose. ```APIDOC ## Example Usage: V4 Local PASETO Token ### Description This example shows the complete lifecycle of creating, encrypting, and then decrypting a PASETO token using V4 and Local purpose with a symmetric key. ### Method `try_encrypt` and `try_decrypt` ### Endpoint N/A (Library functions) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body N/A (Methods operate on struct instances and provided arguments) ### Request Example (Encryption) ```rust use rusty_paseto::core::*; use serde_json::json; let key = PasetoSymmetricKey::::from(Key::<32>::try_from("707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f")?); let nonce = Key::<32>::try_from("0000000000000000000000000000000000000000000000000000000000000000")?; let nonce = PasetoNonce::::from(&nonce); let payload_str = json!({"data": "this is a secret message", "exp":"2022-01-01T00:00:00+00:00"}).to_string(); let payload = Payload::from(payload_str.as_str()); //create a public v4 token let token = Paseto::::builder() .set_payload(payload) .try_encrypt(&key, &nonce)?; //validate the test vector assert_eq!(token.to_string(), "v4.local.AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAr68PS4AXe7If_ZgesdkUMvSwscFlAl1pk5HC0e8kApeaqMfGo_7OpBnwJOAbY9V7WU6abu74MmcUE8YWAiaArVI8XJ5hOb_4v9RmDkneN0S92dx0OW4pgy7omxgf3S8c3LlQg"); ``` ### Response Example (Decryption) ```rust //now let's try to decrypt it let json = Paseto::::try_decrypt(&token, &key, None, None)?; assert_eq!(payload_str, json); ``` ### Success Response (200) - **String** - The decrypted payload as a JSON string. ``` -------------------------------- ### Create PASETO Token Builder Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/core/struct.Paseto.html Initiates the builder pattern for creating a PASETO token. Use this to start the process of setting payload, footer, and implicit assertions before encryption or signing. ```rust //create a public v4 token let token = Paseto::::builder() .set_payload(payload) .try_encrypt(&key, &nonce)?; ``` -------------------------------- ### Build and Parse Token with Custom Claim Validation Source: https://docs.rs/rusty_paseto Builds a PASETO token with custom claims and then parses it, applying a custom validation rule to ensure the 'Universe' claim is a prime number. This example demonstrates successful validation. ```rust use rusty_paseto::prelude::*; use std::convert::TryFrom; // use a default token builder with the same PASETO version and purpose let token = PasetoBuilder::::default() .set_claim(SubjectClaim::from("Get schwifty")) .set_claim(CustomClaim::try_from(("Contestant", "Earth"))?) .set_claim(CustomClaim::try_from(("Universe", 137))?) .build(&key)?; PasetoParser::::default() .check_claim(SubjectClaim::from("Get schwifty")) .check_claim(CustomClaim::try_from(("Contestant", "Earth"))?) .validate_claim(CustomClaim::try_from("Universe")?, &|key, value| { //let's get the value let universe = value .as_u64() .ok_or(PasetoClaimError::Unexpected(key.to_string()))?; // we only accept prime universes in this app if primes::is_prime(universe) { Ok(()) } else { Err(PasetoClaimError::CustomValidation(key.to_string())) } }) .parse(&token, &key)?; ``` -------------------------------- ### Create and Use PasetoParser with Claims Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/prelude/struct.PasetoParser.html Demonstrates creating a PASETO token with various claims and then parsing and verifying it using PasetoParser. Includes setting standard and custom claims, a footer, and encrypting with a symmetric key. ```rust use rusty_paseto::prelude::*; let key = PasetoSymmetricKey::::from(Key::<32>::from(*b"wubbalubbadubdubwubbalubbadubdub")); let footer = Footer::from("some footer"); //create a builder, add some claims and then build the token with the key let token = PasetoBuilder::::default() .set_claim(AudienceClaim::from("customers")) .set_claim(SubjectClaim::from("loyal subjects")) .set_claim(IssuerClaim::from("me")) .set_claim(TokenIdentifierClaim::from("me")) .set_claim(IssuedAtClaim::try_from("2019-01-01T00:00:00+00:00")?) .set_claim(NotBeforeClaim::try_from("2019-01-01T00:00:00+00:00")?) .set_claim(ExpirationClaim::try_from("2019-01-01T00:00:00+00:00")?) .set_claim(CustomClaim::try_from(("data", "this is a secret message"))?) .set_claim(CustomClaim::try_from(("seats", 4))?) .set_claim(CustomClaim::try_from(("pi to 6 digits", 3.141526))?) .set_footer(footer) .try_encrypt(&key)?; //now let's decrypt the token and verify the values let json = PasetoParser::::default() .set_footer(footer) .parse(&token, &key)?; assert_eq!(json["aud"], "customers"); assert_eq!(json["jti"], "me"); assert_eq!(json["iss"], "me"); assert_eq!(json["data"], "this is a secret message"); assert_eq!(json["exp"], "2019-01-01T00:00:00+00:00"); assert_eq!(json["iat"], "2019-01-01T00:00:00+00:00"); assert_eq!(json["nbf"], "2019-01-01T00:00:00+00:00"); assert_eq!(json["sub"], "loyal subjects"); assert_eq!(json["pi to 6 digits"], 3.141526); assert_eq!(json["seats"], 4); ``` -------------------------------- ### PasetoParser Usage Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/prelude/struct.PasetoParser.html Demonstrates how to create a PasetoParser, set claims, build a token, and then parse and verify it. ```APIDOC ## Usage Example This example shows the typical workflow of creating a PASETO token with custom claims and then parsing it using `PasetoParser`. ### Steps: 1. **Key and Footer Setup**: Initialize a symmetric key and a footer. 2. **Token Creation**: Use `PasetoBuilder` to set various claims (audience, subject, issuer, expiration, custom claims) and build the token. 3. **Token Parsing**: Use `PasetoParser` to parse the generated token, verifying claims and the footer. ```rust use rusty_paseto::prelude::*; let key = PasetoSymmetricKey::::from(Key::<32>::from(*b"wubbalubbadubdubwubbalubbadubdub")); let footer = Footer::from("some footer"); // Create a builder, add some claims and then build the token with the key let token = PasetoBuilder::::default() .set_claim(AudienceClaim::from("customers")) .set_claim(SubjectClaim::from("loyal subjects")) .set_claim(IssuerClaim::from("me")) .set_claim(TokenIdentifierClaim::from("me")) .set_claim(IssuedAtClaim::try_from("2019-01-01T00:00:00+00:00")?) .set_claim(NotBeforeClaim::try_from("2019-01-01T00:00:00+00:00")?) .set_claim(ExpirationClaim::try_from("2019-01-01T00:00:00+00:00")?) .set_claim(CustomClaim::try_from(("data", "this is a secret message"))?) .set_claim(CustomClaim::try_from(("seats", 4))?) .set_claim(CustomClaim::try_from(("pi to 6 digits", 3.141526))?) .set_footer(footer) .try_encrypt(&key)?; // Now let's decrypt the token and verify the values let json = PasetoParser::::default() .set_footer(footer) .parse(&token, &key)?; assert_eq!(json["aud"], "customers"); assert_eq!(json["jti"], "me"); assert_eq!(json["iss"], "me"); assert_eq!(json["data"], "this is a secret message"); assert_eq!(json["exp"], "2019-01-01T00:00:00+00:00"); assert_eq!(json["iat"], "2019-01-01T00:00:00+00:00"); assert_eq!(json["nbf"], "2019-01-01T00:00:00+00:00"); assert_eq!(json["sub"], "loyal subjects"); assert_eq!(json["pi to 6 digits"], 3.141526); assert_eq!(json["seats"], 4); ``` ``` -------------------------------- ### Get Last Element of Slice Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/core/struct.PasetoNonce.html Provides an example of safely retrieving the last element of a slice, returning `None` if the slice is empty. ```rust let v = [10, 40, 30]; assert_eq!(Some(&30), v.last()); let w: &[i32] = &[]; assert_eq!(None, w.last()); ``` -------------------------------- ### Slice Get Unchecked Element or Subslice Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/core/struct.PasetoNonce.html Unsafely gets a reference to an element or subslice without bounds checking. Use with extreme caution. ```APIDOC ## pub unsafe fn get_unchecked( &self, index: I, ) -> &>::Output ### Description Returns a reference to an element or subslice, without doing bounds checking. For a safe alternative see `get`. ### Method GET (conceptual) ### Endpoint N/A (method on slice) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust let x = &[1, 2, 4]; unsafe { assert_eq!(x.get_unchecked(1), &2); } ``` ### Safety Calling this method with an out-of-bounds index is _undefined behavior_ even if the resulting reference is not used. ### Response #### Success Response (200) - **&>::Output**: A reference to the element or subslice. Behavior is undefined if the index is out of bounds. ``` -------------------------------- ### Import rusty_paseto prelude Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/index.html Import the prelude module for standard functionality. ```rust // at the top of your source file use rusty_paseto::prelude::*; ``` -------------------------------- ### Construct and parse a PASETO token Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/prelude/struct.PasetoBuilder.html Demonstrates creating a builder, adding various claims, setting a footer, encrypting the token, and subsequently parsing and verifying it. ```rust use rusty_paseto::prelude::*; let key = PasetoSymmetricKey::::from(Key::<32>::from(*b"wubbalubbadubdubwubbalubbadubdub")); let footer = Footer::from("some footer"); //create a builder, add some claims and then build the token with the key let token = PasetoBuilder::::default() .set_claim(AudienceClaim::from("customers")) .set_claim(SubjectClaim::from("loyal subjects")) .set_claim(IssuerClaim::from("me")) .set_claim(TokenIdentifierClaim::from("me")) .set_claim(IssuedAtClaim::try_from("2019-01-01T00:00:00+00:00")?) .set_claim(NotBeforeClaim::try_from("2019-01-01T00:00:00+00:00")?) .set_claim(ExpirationClaim::try_from("2019-01-01T00:00:00+00:00")?) .set_claim(CustomClaim::try_from(("data", "this is a secret message"))?) .set_claim(CustomClaim::try_from(("seats", 4))?) .set_claim(CustomClaim::try_from(("pi to 6 digits", 3.141526))?) .set_footer(footer) .try_encrypt(&key)?; //now let's decrypt the token and verify the values let json = PasetoParser::::default() .set_footer(footer) .parse(&token, &key)?; assert_eq!(json["aud"], "customers"); assert_eq!(json["jti"], "me"); assert_eq!(json["iss"], "me"); assert_eq!(json["data"], "this is a secret message"); assert_eq!(json["exp"], "2019-01-01T00:00:00+00:00"); assert_eq!(json["iat"], "2019-01-01T00:00:00+00:00"); assert_eq!(json["nbf"], "2019-01-01T00:00:00+00:00"); assert_eq!(json["sub"], "loyal subjects"); assert_eq!(json["pi to 6 digits"], 3.141526); assert_eq!(json["seats"], 4); ``` -------------------------------- ### Get Slice as Array Reference Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/core/struct.Payload.html The `as_array` method attempts to get a reference to the underlying array. It returns `Some` only if the slice length exactly matches `N`. ```rust let slice = &[1, 2, 3]; let array_ref: Option<&[i32; 3]> = slice.as_array(); assert!(array_ref.is_some()); let short_slice = &[1, 2]; let array_ref_short: Option<&[i32; 3]> = short_slice.as_array(); assert!(array_ref_short.is_none()); ``` -------------------------------- ### Slice Get Element or Subslice Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/core/struct.PasetoNonce.html Safely gets a reference to an element or subslice using various index types. Returns None if the index is out of bounds. ```APIDOC ## pub fn get(&self, index: I) -> Option<&>::Output> ### Description Returns a reference to an element or subslice depending on the type of index. If given a position, returns a reference to the element at that position or `None` if out of bounds. If given a range, returns the subslice corresponding to that range, or `None` if out of bounds. ### Method GET (conceptual) ### Endpoint N/A (method on slice) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust let v = [10, 40, 30]; assert_eq!(Some(&40), v.get(1)); assert_eq!(Some(&[10, 40][..]), v.get(0..2)); assert_eq!(None, v.get(3)); assert_eq!(None, v.get(0..4)); ``` ### Response #### Success Response (200) - **Option<&>::Output>**: A reference to the element or subslice if the index is valid, otherwise None. ``` -------------------------------- ### Example of Failed Custom Validation Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/generic/struct.CustomClaim.html This example demonstrates a token that will fail custom validation because the 'Universe' claim (136) is not a prime number, as required by the validation logic. ```rust let token = PasetoBuilder::::default() .set_claim(CustomClaim::try_from(("Universe", 136))?) .build(&key)?; ``` -------------------------------- ### Implementation: From<&Key<64>> for PasetoAsymmetricPrivateKey Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/core/struct.PasetoAsymmetricPrivateKey.html Allows creating a PasetoAsymmetricPrivateKey from a reference to a Key<64>. This is the recommended way to create the key for automatic memory zeroization. ```rust fn from(key: &'a Key<64>) -> Self ``` -------------------------------- ### Decrypt and Parse PASETO Token with Claims (V4, Local) Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/prelude/struct.PasetoParser.html Decrypt a PASETO token and validate its claims using PasetoParser. This example demonstrates parsing a token previously built with PasetoBuilder. ```rust //now let's decrypt the token and verify the values let json = PasetoParser::::default() .set_footer(footer) .set_implicit_assertion(implicit_assertion) .parse(&token, &key)?; assert_eq!(json["aud"], "customers"); assert_eq!(json["jti"], "me"); assert_eq!(json["iss"], "me"); assert_eq!(json["data"], "this is a secret message"); assert_eq!(json["exp"], "2019-01-01T00:00:00+00:00"); assert_eq!(json["iat"], "2019-01-01T00:00:00+00:00"); assert_eq!(json["nbf"], "2019-01-01T00:00:00+00:00"); assert_eq!(json["sub"], "loyal subjects"); assert_eq!(json["pi to 6 digits"], 3.141526); assert_eq!(json["seats"], 4); ``` -------------------------------- ### Usage of GenericBuilder for Token Creation and Parsing Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/generic/struct.GenericBuilder.html Demonstrates creating a token with various claims and a footer, then parsing it back to verify the values. ```rust use rusty_paseto::generic::*; let key = PasetoSymmetricKey::::from(Key::<32>::from(*b"wubbalubbadubdubwubbalubbadubdub")); let footer = Footer::from("some footer"); //create a builder, add some claims and then build the token with the key let token = GenericBuilder::::default() .set_claim(AudienceClaim::from("customers")) .set_claim(SubjectClaim::from("loyal subjects")) .set_claim(IssuerClaim::from("me")) .set_claim(TokenIdentifierClaim::from("me")) .set_claim(IssuedAtClaim::try_from("2019-01-01T00:00:00+00:00")?) .set_claim(NotBeforeClaim::try_from("2019-01-01T00:00:00+00:00")?) .set_claim(ExpirationClaim::try_from("2019-01-01T00:00:00+00:00")?) .set_claim(CustomClaim::try_from(("data", "this is a secret message"))?) .set_claim(CustomClaim::try_from(("seats", 4))?) .set_claim(CustomClaim::try_from(("pi to 6 digits", 3.141526))?) .set_footer(footer) .try_encrypt(&key)?; //now let's decrypt the token and verify the values let json = GenericParser::::default() .set_footer(footer) .parse(&token, &key)?; assert_eq!(json["aud"], "customers"); assert_eq!(json["jti"], "me"); assert_eq!(json["iss"], "me"); assert_eq!(json["data"], "this is a secret message"); assert_eq!(json["exp"], "2019-01-01T00:00:00+00:00"); assert_eq!(json["iat"], "2019-01-01T00:00:00+00:00"); assert_eq!(json["nbf"], "2019-01-01T00:00:00+00:00"); assert_eq!(json["sub"], "loyal subjects"); assert_eq!(json["pi to 6 digits"], 3.141526); assert_eq!(json["seats"], 4); ``` -------------------------------- ### trim_prefix Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/core/struct.ImplicitAssertion.html This is a nightly-only experimental API. It returns a subslice with the optional prefix removed. If the slice starts with `prefix`, it returns the subslice after the prefix. If `prefix` is empty or the slice does not start with `prefix`, it returns the original slice. ```APIDOC ## trim_prefix ### Description Returns a subslice with the optional prefix removed. If the slice starts with `prefix`, the prefix is removed. Otherwise, the original slice is returned. ### Method N/A (This is a method on slices) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) `&[T]` - The subslice with the prefix removed, or the original slice if the prefix was not found. #### Response Example ```rust let v = &[10, 40, 30]; assert_eq!(v.trim_prefix(&[10]), &[40, 30][..]); assert_eq!(v.trim_prefix(&[50]), &[10, 40, 30][..]); ``` ``` -------------------------------- ### PasetoBuilder Usage and Methods Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/prelude/struct.PasetoBuilder.html Demonstrates how to use the PasetoBuilder to create and configure PASETO tokens, including setting claims, footers, and handling encryption. It also details the available methods for modifying the builder's state. ```APIDOC ## PasetoBuilder ### Description The `PasetoBuilder` is used to construct PASETO tokens. It allows specifying PASETO version and purpose, setting standard JWT-style claims (like `aud`, `sub`, `iss`, `iat`, `nbf`, `exp`), custom claims, and an optional footer. It wraps a `GenericBuilder` and enforces PASETO standard business rules. ### Usage Example ```rust use rusty_paseto::prelude::*; let key = PasetoSymmetricKey::::from(Key::<32>::from(*b"wubbalubbadubdubwubbalubbadubdub")); let footer = Footer::from("some footer"); let token = PasetoBuilder::::default() .set_claim(AudienceClaim::from("customers")) .set_claim(SubjectClaim::from("loyal subjects")) .set_claim(IssuerClaim::from("me")) .set_claim(TokenIdentifierClaim::from("me")) .set_claim(IssuedAtClaim::try_from("2019-01-01T00:00:00+00:00")?) .set_claim(NotBeforeClaim::try_from("2019-01-01T00:00:00+00:00")?) .set_claim(ExpirationClaim::try_from("2019-01-01T00:00:00+00:00")?) .set_claim(CustomClaim::try_from(("data", "this is a secret message"))?) .set_claim(CustomClaim::try_from(("seats", 4))?) .set_claim(CustomClaim::try_from(("pi to 6 digits", 3.141526))?) .set_footer(footer) .try_encrypt(&key)?; // To verify and parse the token: let json = PasetoParser::::default() .set_footer(footer) .parse(&token, &key)?; assert_eq!(json["aud"], "customers"); // ... other assertions ``` ### Methods #### `set_claim( &mut self, value: T, ) -> &mut Self` ##### Description Adds a `PasetoClaim` to the builder for inclusion in the token's payload. Overwrites the default ‘nbf’ (not before) claim if provided. Prevents duplicate claims from being added. ##### Returns A mutable reference to the builder on success. ##### Example ```rust use rusty_paseto::prelude::*; let key = PasetoSymmetricKey::::from(Key::<32>::from(*b"wubbalubbadubdubwubbalubbadubdub")); let token = PasetoBuilder::::default() .set_claim(AudienceClaim::from("customers")) .try_encrypt(&key)?; ``` #### `set_no_expiration_danger_acknowledged(&mut self) -> &mut Self` ##### Description Sets the token to have no expiration date. By default, a 1-hour `ExpirationClaim` is set. This method explicitly removes that default, acknowledging the security implications. ##### Returns A mutable reference to the builder on success. ##### Example ```rust use rusty_paseto::prelude::*; let key = PasetoSymmetricKey::::from(Key::<32>::from(*b"wubbalubbadubdubwubbalubbadubdub")); let token = PasetoBuilder::::default() .set_claim(ExpirationClaim::try_from(in_5_minutes)?) .set_no_expiration_danger_acknowledged() .build(&key)?; ``` #### `set_footer(&mut self, footer: Footer<'a>) -> &mut Self` ##### Description Sets an optional Footer on the token. ##### Returns A mutable reference to the builder on success. ##### Example ```rust use rusty_paseto::prelude::*; let key = PasetoSymmetricKey::::from(Key::<32>::from(*b"wubbalubbadubdubwubbalubbadubdub")); let token = PasetoBuilder::::default() .set_footer(Footer::from("Some footer")) .build(&key)?; ``` ``` -------------------------------- ### Create a Public V4 PASETO Token Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/core/struct.PasetoNonce.html Demonstrates how to create a symmetric key, generate a random nonce, and encrypt a payload using PasetoNonce and PasetoSymmetricKey for V4 Local tokens. Ensure you have the necessary dependencies like serde_json. ```rust use serde_json::json; use rusty_paseto::core::*; let key = PasetoSymmetricKey::::from(Key::<32>::try_from("707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f")?); // generate a random nonce with let nonce = Key::<32>::try_new_random()?; let nonce = PasetoNonce::::from(&nonce); let payload = json!({"data": "this is a secret message", "exp":"2022-01-01T00:00:00+00:00"}).to_string(); let payload = payload.as_str(); let payload = Payload::from(payload); //create a public v4 token let token = Paseto::::builder() .set_payload(payload) .try_encrypt(&key, &nonce)? ``` -------------------------------- ### as_array Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/core/struct.Footer.html Gets a reference to the underlying array. ```APIDOC ## as_array ### Description Attempts to return a reference to the underlying array of size N. Returns None if the slice length does not match N. ### Parameters #### Generic Parameters - **N** (usize) - The required length of the array. ### Response - **Return** (Option<&[T; N]>) - The array reference or None. ``` -------------------------------- ### Create and Parse a PASETO Token Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/generic/struct.GenericBuilder.html Demonstrates building a V4 Local PASETO token with claims, footer, and implicit assertion, followed by decryption and verification. ```rust use rusty_paseto::generic::*; let key = PasetoSymmetricKey::::from(Key::<32>::from(*b"wubbalubbadubdubwubbalubbadubdub")); let footer = Footer::from("some footer"); let implicit_assertion = ImplicitAssertion::from("some assertion"); //create a builder, add some claims and then build the token with the key let token = GenericBuilder::::default() .set_claim(AudienceClaim::from("customers")) .set_claim(SubjectClaim::from("loyal subjects")) .set_claim(IssuerClaim::from("me")) .set_claim(TokenIdentifierClaim::from("me")) .set_claim(IssuedAtClaim::try_from("2019-01-01T00:00:00+00:00")?) .set_claim(NotBeforeClaim::try_from("2019-01-01T00:00:00+00:00")?) .set_claim(ExpirationClaim::try_from("2019-01-01T00:00:00+00:00")?) .set_claim(CustomClaim::try_from(("data", "this is a secret message"))?) .set_claim(CustomClaim::try_from(("seats", 4))?) .set_claim(CustomClaim::try_from(("pi to 6 digits", 3.141526))?) .set_footer(footer) .set_implicit_assertion(implicit_assertion) .try_encrypt(&key)?; //now let's decrypt the token and verify the values let json = GenericParser::::default() .set_footer(footer) .set_implicit_assertion(implicit_assertion) .parse(&token, &key)?; assert_eq!(json["aud"], "customers"); assert_eq!(json["jti"], "me"); assert_eq!(json["iss"], "me"); assert_eq!(json["data"], "this is a secret message"); assert_eq!(json["exp"], "2019-01-01T00:00:00+00:00"); assert_eq!(json["iat"], "2019-01-01T00:00:00+00:00"); assert_eq!(json["nbf"], "2019-01-01T00:00:00+00:00"); assert_eq!(json["sub"], "loyal subjects"); assert_eq!(json["pi to 6 digits"], 3.141526); assert_eq!(json["seats"], 4); ``` -------------------------------- ### Initialize HashMap with capacity and hasher Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/generic/type.ValidatorMap.html Creates an empty HashMap with pre-allocated capacity and a custom hash builder. ```rust use std::collections::HashMap; use std::hash::RandomState; let s = RandomState::new(); let mut map = HashMap::with_capacity_and_hasher(10, s); map.insert(1, 2); ``` -------------------------------- ### Configure core dependency Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/index.html Add the core feature for lightweight, basic PASETO operations without claims. ```toml ## Includes only v4 modern sodium cipher crypto core and local (symmetric) ## key types with NO claims, defaults or validation, just basic PASETO ## encrypt/signing and decrypt/verification. rusty_paseto = {version = "latest", features = ["core", "v4_local"] } ``` -------------------------------- ### rchunks Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/core/struct.PasetoNonce.html Returns an iterator over chunks of the slice starting from the end. ```APIDOC ## pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T> ### Description Returns an iterator over chunk_size elements of the slice at a time, starting at the end of the slice. ### Parameters #### Query Parameters - **chunk_size** (usize) - Required - The size of each chunk. ### Response - **iterator** (RChunks) - An iterator over the chunks. ``` -------------------------------- ### get Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/core/struct.Payload.html Returns a reference to an element or subslice depending on the type of index. ```APIDOC ## get ### Description Returns a reference to an element or subslice depending on the type of index. If given a position, returns a reference to the element at that position or None if out of bounds. If given a range, returns the subslice corresponding to that range, or None if out of bounds. ### Parameters #### Path Parameters - **index** (I) - Required - The index or range to retrieve. ### Response #### Success Response (200) - **Option<&>::Output>** - The element or subslice at the specified index. ``` -------------------------------- ### Import rusty_paseto core module Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/index.html Import the core module for basic crypto functions. ```rust // at the top of your source file use rusty_paseto::core::*; ``` -------------------------------- ### GET /get_key_value Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/generic/type.ValidatorMap.html Retrieves the key-value pair corresponding to the supplied key. ```APIDOC ## GET /get_key_value ### Description Returns the key-value pair corresponding to the supplied key. Useful for retrieving the stored key reference or handling cases where non-identical keys are considered equal. ### Parameters #### Query Parameters - **k** (Q) - Required - The key to look up. ``` -------------------------------- ### Build a default token Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/index.html Create a basic PASETO token using the batteries_included builder. ```rust use rusty_paseto::prelude::*; // create a key specifying the PASETO version and purpose let key = PasetoSymmetricKey::::from(Key::from(b"wubbalubbadubdubwubbalubbadubdub")); // use a default token builder with the same PASETO version and purpose let token = PasetoBuilder::::default().build(&key)?; // token is a String in the form: "v4.local.encoded-payload" ``` -------------------------------- ### GET footer_str Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/core/struct.UntrustedToken.html Decodes and returns the token footer as a UTF-8 string. ```APIDOC ## GET footer_str ### Description Decodes and returns the footer as a UTF-8 string if present. Returns None if the token does not contain a footer. Note: This value is UNTRUSTED and has not been cryptographically verified. ### Errors - PasetoError::PayloadBase64Decode: Returned if the footer contains invalid base64url encoding. - PasetoError::Utf8Error: Returned if the decoded footer is not valid UTF-8. ### Request Example ```rust let token = "v4.local.payload.eyJraWQiOiJrZXktMSJ9"; let untrusted = UntrustedToken::try_parse(token)?; let footer_str = untrusted.footer_str()?; ``` ``` -------------------------------- ### GET footer_decoded Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/core/struct.UntrustedToken.html Decodes and returns the token footer as raw bytes. ```APIDOC ## GET footer_decoded ### Description Decodes and returns the footer as raw bytes if present. Returns None if the token does not contain a footer. Note: This value is UNTRUSTED and has not been cryptographically verified. ### Errors - PasetoError::PayloadBase64Decode: Returned if the footer is present but contains invalid base64url encoding. ### Request Example ```rust let token = "v4.local.payload.Zm9vdGVy"; let untrusted = UntrustedToken::try_parse(token)?; let footer_bytes = untrusted.footer_decoded()?; ``` ``` -------------------------------- ### Key Implementations Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/core/struct.Key.html Provides methods for creating and managing cryptographic keys. ```APIDOC ## Implementations ### impl Key #### pub fn try_new_random() -> Result Uses the system’s RNG to create a random slice of bytes of a specific size. ##### Errors Returns `PasetoError::Cipher` if the system’s random number generator fails to fill the buffer. ``` -------------------------------- ### Create and parse a token with a footer Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/index.html Demonstrates adding an optional footer to a PASETO token during construction and providing it during parsing. ```rust use rusty_paseto::prelude::*; let key = PasetoSymmetricKey::::from(Key::from(b"wubbalubbadubdubwubbalubbadubdub")); let token = PasetoBuilder::::default() // note how we set the footer here .set_footer(Footer::from("Sometimes science is more art than science")) .build(&key)?; // token is now a String in the form: "v4.local.encoded-payload.footer" ``` ```rust // now we can parse and validate the token with a parser that returns a serde_json::Value let json_value = PasetoParser::::default() .set_footer(Footer::from("Sometimes science is more art than science")) .parse(&token, &key)?; //the ExpirationClaim assert!(json_value["exp"].is_string()); //the IssuedAtClaim assert!(json_value["iat"].is_string()); ``` -------------------------------- ### iter Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/core/struct.PasetoNonce.html Returns an iterator over the slice, yielding all items from start to end. ```APIDOC ## pub fn iter(&self) -> Iter<'_, T> ### Description Returns an iterator over the slice. The iterator yields all items from start to end. ### Method `pub fn` ### Endpoint N/A (Method on slice) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust let x = &[1, 2, 4]; let mut iterator = x.iter(); assert_eq!(iterator.next(), Some(&1)); assert_eq!(iterator.next(), Some(&2)); assert_eq!(iterator.next(), Some(&4)); assert_eq!(iterator.next(), None); ``` ### Response #### Success Response (Iter<'_, T>) - An iterator that yields references to the elements of the slice. #### Response Example None ``` -------------------------------- ### Build and Encrypt PASETO Token (V4, Local) Source: https://docs.rs/rusty_paseto/0.9.0/rusty_paseto/prelude/struct.PasetoParser.html Construct a PASETO token with various claims, footer, and implicit assertion using PasetoBuilder, then encrypt it with a symmetric key. ```rust use rusty_paseto::prelude::*; let key = PasetoSymmetricKey::::from(Key::<32>::from(*b"wubbalubbadubdubwubbalubbadubdub")); let footer = Footer::from("some footer"); let implicit_assertion = ImplicitAssertion::from("some assertion"); //create a builder, add some claims and then build the token with the key let token = PasetoBuilder::::default() .set_claim(AudienceClaim::from("customers")) .set_claim(SubjectClaim::from("loyal subjects")) .set_claim(IssuerClaim::from("me")) .set_claim(TokenIdentifierClaim::from("me")) .set_claim(IssuedAtClaim::try_from("2019-01-01T00:00:00+00:00")?) .set_claim(NotBeforeClaim::try_from("2019-01-01T00:00:00+00:00")?) .set_claim(ExpirationClaim::try_from("2019-01-01T00:00:00+00:00")?) .set_claim(CustomClaim::try_from(("data", "this is a secret message"))?) .set_claim(CustomClaim::try_from(("seats", 4))?) .set_claim(CustomClaim::try_from(("pi to 6 digits", 3.141526))?) .set_footer(footer) .set_implicit_assertion(implicit_assertion) .try_encrypt(&key)?; ```