Enum KeyPair

Source
pub enum KeyPair {
    Ed25519(KeyPair),
    P256(KeyPair),
}
Expand description

pair of cryptographic keys used to sign a token’s block

Variants§

§

Ed25519(KeyPair)

§

P256(KeyPair)

Implementations§

Source§

impl KeyPair

Source

pub fn new() -> KeyPair

Create a new ed25519 keypair with the default OS RNG

Examples found in repository?
examples/token_attenuation.rs (line 12)
6fn main() -> Result<(), TokenError> {
7    // Generate an example token
8    let (token_base64, root_keypair) = generate_example_token()?;
9    println!("Original token: {}\n", token_base64);
10
11    // Create a service node keypair
12    let service_keypair = KeyPair::new();
13
14    // 1. First, we need the binary token data
15    let token_bytes = decode_token(&token_base64)?;
16
17    // 2. Add service node attenuation
18    println!("Adding service node attenuation...");
19    let attenuated_token = add_service_node_attenuation(
20        token_bytes,
21        root_keypair.public(),
22        "my-service",
23        &service_keypair,
24    )?;
25
26    // 3. Encode back to base64
27    let attenuated_token_base64 = encode_token(&attenuated_token);
28    println!("Attenuated token: {}\n", attenuated_token_base64);
29
30    // 4. Verify the attenuated token still works
31    println!("Verifying attenuated token...");
32    verify_token(
33        &attenuated_token_base64,
34        root_keypair.public(),
35        "alice",
36        "resource1",
37    )?;
38    println!("✅ Verification successful for attenuated token");
39
40    // 5. Generate a chain of attenuations
41    println!("\nCreating a chain of attenuations...");
42    let token_with_chain = create_attenuation_chain(&token_base64, &root_keypair)?;
43    println!("Token with attenuation chain: {}", token_with_chain);
44
45    // 6. Verify the chain token
46    println!("\nVerifying token with attenuation chain...");
47    verify_token(
48        &token_with_chain,
49        root_keypair.public(),
50        "alice",
51        "resource1",
52    )?;
53    println!("✅ Verification successful for token with attenuation chain");
54
55    Ok(())
56}
57
58/// Generate an example token for testing, returning both token and keypair
59fn generate_example_token() -> Result<(String, KeyPair), TokenError> {
60    // Create a test keypair
61    let keypair = KeyPair::new();
62
63    // Create a simple test biscuit with authorization rules
64    let biscuit_builder = biscuit!(
65        r#"
66            // Grant rights to alice for resource1
67            right("alice", "resource1", "read");
68            right("alice", "resource1", "write");
69        "#
70    );
71
72    // Build and serialize the token
73    let biscuit = biscuit_builder
74        .build(&keypair)
75        .map_err(TokenError::biscuit_error)?;
76
77    let token_bytes = biscuit.to_vec().map_err(TokenError::biscuit_error)?;
78
79    // Encode to base64 for transmission
80    Ok((encode_token(&token_bytes), keypair))
81}
82
83/// Create a chain of service attestations
84fn create_attenuation_chain(
85    token_base64: &str,
86    root_keypair: &KeyPair,
87) -> Result<String, TokenError> {
88    // Decode the original token
89    let mut token_bytes = decode_token(token_base64)?;
90
91    // Create service keypairs
92    let service_names = ["service-1", "service-2", "service-3"];
93
94    // Add multiple service attestations
95    for service_name in service_names.iter() {
96        println!("  Adding attestation for {}", service_name);
97
98        // Create a new keypair for this service
99        let service_keypair = KeyPair::new();
100
101        // Add an attestation
102        token_bytes = add_service_node_attenuation(
103            token_bytes,
104            root_keypair.public(),
105            service_name,
106            &service_keypair,
107        )?;
108    }
109
110    // Encode the final token
111    Ok(encode_token(&token_bytes))
112}
More examples
Hide additional examples
examples/token_verification.rs (line 9)
7fn main() -> Result<(), TokenError> {
8    // Generate an example token
9    let root_keypair = Arc::new(KeyPair::new());
10    let token_base64 = generate_example_token(root_keypair.clone())?;
11    println!("Generated token: {}\n", token_base64);
12
13    // Example 1: Basic verification
14    println!("Example 1: Basic verification");
15    verify_token(&token_base64, root_keypair.public(), "alice", "resource1")?;
16    println!("✅ Basic verification successful\n");
17
18    // Example 2: Service chain verification
19    println!("Example 2: Service chain verification");
20
21    // Create service node keypairs
22    let service1_keypair = KeyPair::new();
23    let service1_pk_hex = hex::encode(service1_keypair.public().to_bytes());
24    let service1_public_key = format!("ed25519/{}", service1_pk_hex);
25
26    let service2_keypair = KeyPair::new();
27    let service2_pk_hex = hex::encode(service2_keypair.public().to_bytes());
28    let service2_public_key = format!("ed25519/{}", service2_pk_hex);
29
30    // Define service nodes
31    let service_nodes = vec![
32        ServiceNode {
33            component: "node1".to_string(),
34            public_key: service1_public_key.clone(),
35        },
36        ServiceNode {
37            component: "node2".to_string(),
38            public_key: service2_public_key.clone(),
39        },
40    ];
41
42    // Generate a token with service chain
43    let chain_token = generate_service_chain_token(
44        root_keypair.clone(),
45        service1_public_key,
46        service2_public_key,
47    )?;
48
49    // attenuate the token for node1
50    let attenuated_token = add_service_node_attenuation(
51        decode_token(&chain_token)?,
52        root_keypair.public(),
53        "resource1",
54        &service1_keypair,
55    )?;
56
57    // attenuate the token for node2
58    let attenuated_token2 = add_service_node_attenuation(
59        attenuated_token,
60        root_keypair.public(),
61        "resource1",
62        &service2_keypair,
63    )?;
64
65    // Verify with service chain
66    verify_service_chain_token(
67        &encode_token(&attenuated_token2),
68        root_keypair.public(),
69        "alice",
70        "resource1",
71        service_nodes,
72        None,
73    )?;
74    println!("✅ Service chain verification successful\n");
75
76    // Example 3: Verification with key from string
77    println!("Example 3: Verification with key from string");
78
79    // Convert public key to string format and back
80    let pk_hex = hex::encode(root_keypair.public().to_bytes());
81    let pk_str = format!("ed25519/{}", pk_hex);
82    let parsed_pk = biscuit_key_from_string(pk_str)?;
83
84    // Verify with parsed key
85    verify_token(&token_base64, parsed_pk, "alice", "resource1")?;
86    println!("✅ Verification with key from string successful");
87
88    Ok(())
89}
Source

pub fn new_with_algorithm(algorithm: Algorithm) -> KeyPair

Create a new keypair with a chosen algorithm and the default OS RNG

Source

pub fn new_with_rng<T>(algorithm: Algorithm, rng: &mut T) -> KeyPair
where T: RngCore + CryptoRng,

Source

pub fn from(key: &PrivateKey) -> KeyPair

Source

pub fn from_bytes(bytes: &[u8], algorithm: Algorithm) -> Result<KeyPair, Format>

deserializes from a byte array

Source

pub fn sign(&self, data: &[u8]) -> Result<Signature, Format>

Source

pub fn from_private_key_der_with_algorithm( bytes: &[u8], algorithm: Algorithm, ) -> Result<KeyPair, Format>

Source

pub fn from_private_key_der(bytes: &[u8]) -> Result<KeyPair, Format>

Source

pub fn from_private_key_pem_with_algorithm( str: &str, algorithm: Algorithm, ) -> Result<KeyPair, Format>

Source

pub fn from_private_key_pem(str: &str) -> Result<KeyPair, Format>

Source

pub fn to_private_key_der(&self) -> Result<Zeroizing<Vec<u8>>, Format>

Source

pub fn to_private_key_pem(&self) -> Result<Zeroizing<String>, Format>

Source

pub fn private(&self) -> PrivateKey

Source

pub fn public(&self) -> PublicKey

Examples found in repository?
examples/token_attenuation.rs (line 21)
6fn main() -> Result<(), TokenError> {
7    // Generate an example token
8    let (token_base64, root_keypair) = generate_example_token()?;
9    println!("Original token: {}\n", token_base64);
10
11    // Create a service node keypair
12    let service_keypair = KeyPair::new();
13
14    // 1. First, we need the binary token data
15    let token_bytes = decode_token(&token_base64)?;
16
17    // 2. Add service node attenuation
18    println!("Adding service node attenuation...");
19    let attenuated_token = add_service_node_attenuation(
20        token_bytes,
21        root_keypair.public(),
22        "my-service",
23        &service_keypair,
24    )?;
25
26    // 3. Encode back to base64
27    let attenuated_token_base64 = encode_token(&attenuated_token);
28    println!("Attenuated token: {}\n", attenuated_token_base64);
29
30    // 4. Verify the attenuated token still works
31    println!("Verifying attenuated token...");
32    verify_token(
33        &attenuated_token_base64,
34        root_keypair.public(),
35        "alice",
36        "resource1",
37    )?;
38    println!("✅ Verification successful for attenuated token");
39
40    // 5. Generate a chain of attenuations
41    println!("\nCreating a chain of attenuations...");
42    let token_with_chain = create_attenuation_chain(&token_base64, &root_keypair)?;
43    println!("Token with attenuation chain: {}", token_with_chain);
44
45    // 6. Verify the chain token
46    println!("\nVerifying token with attenuation chain...");
47    verify_token(
48        &token_with_chain,
49        root_keypair.public(),
50        "alice",
51        "resource1",
52    )?;
53    println!("✅ Verification successful for token with attenuation chain");
54
55    Ok(())
56}
57
58/// Generate an example token for testing, returning both token and keypair
59fn generate_example_token() -> Result<(String, KeyPair), TokenError> {
60    // Create a test keypair
61    let keypair = KeyPair::new();
62
63    // Create a simple test biscuit with authorization rules
64    let biscuit_builder = biscuit!(
65        r#"
66            // Grant rights to alice for resource1
67            right("alice", "resource1", "read");
68            right("alice", "resource1", "write");
69        "#
70    );
71
72    // Build and serialize the token
73    let biscuit = biscuit_builder
74        .build(&keypair)
75        .map_err(TokenError::biscuit_error)?;
76
77    let token_bytes = biscuit.to_vec().map_err(TokenError::biscuit_error)?;
78
79    // Encode to base64 for transmission
80    Ok((encode_token(&token_bytes), keypair))
81}
82
83/// Create a chain of service attestations
84fn create_attenuation_chain(
85    token_base64: &str,
86    root_keypair: &KeyPair,
87) -> Result<String, TokenError> {
88    // Decode the original token
89    let mut token_bytes = decode_token(token_base64)?;
90
91    // Create service keypairs
92    let service_names = ["service-1", "service-2", "service-3"];
93
94    // Add multiple service attestations
95    for service_name in service_names.iter() {
96        println!("  Adding attestation for {}", service_name);
97
98        // Create a new keypair for this service
99        let service_keypair = KeyPair::new();
100
101        // Add an attestation
102        token_bytes = add_service_node_attenuation(
103            token_bytes,
104            root_keypair.public(),
105            service_name,
106            &service_keypair,
107        )?;
108    }
109
110    // Encode the final token
111    Ok(encode_token(&token_bytes))
112}
More examples
Hide additional examples
examples/token_verification.rs (line 15)
7fn main() -> Result<(), TokenError> {
8    // Generate an example token
9    let root_keypair = Arc::new(KeyPair::new());
10    let token_base64 = generate_example_token(root_keypair.clone())?;
11    println!("Generated token: {}\n", token_base64);
12
13    // Example 1: Basic verification
14    println!("Example 1: Basic verification");
15    verify_token(&token_base64, root_keypair.public(), "alice", "resource1")?;
16    println!("✅ Basic verification successful\n");
17
18    // Example 2: Service chain verification
19    println!("Example 2: Service chain verification");
20
21    // Create service node keypairs
22    let service1_keypair = KeyPair::new();
23    let service1_pk_hex = hex::encode(service1_keypair.public().to_bytes());
24    let service1_public_key = format!("ed25519/{}", service1_pk_hex);
25
26    let service2_keypair = KeyPair::new();
27    let service2_pk_hex = hex::encode(service2_keypair.public().to_bytes());
28    let service2_public_key = format!("ed25519/{}", service2_pk_hex);
29
30    // Define service nodes
31    let service_nodes = vec![
32        ServiceNode {
33            component: "node1".to_string(),
34            public_key: service1_public_key.clone(),
35        },
36        ServiceNode {
37            component: "node2".to_string(),
38            public_key: service2_public_key.clone(),
39        },
40    ];
41
42    // Generate a token with service chain
43    let chain_token = generate_service_chain_token(
44        root_keypair.clone(),
45        service1_public_key,
46        service2_public_key,
47    )?;
48
49    // attenuate the token for node1
50    let attenuated_token = add_service_node_attenuation(
51        decode_token(&chain_token)?,
52        root_keypair.public(),
53        "resource1",
54        &service1_keypair,
55    )?;
56
57    // attenuate the token for node2
58    let attenuated_token2 = add_service_node_attenuation(
59        attenuated_token,
60        root_keypair.public(),
61        "resource1",
62        &service2_keypair,
63    )?;
64
65    // Verify with service chain
66    verify_service_chain_token(
67        &encode_token(&attenuated_token2),
68        root_keypair.public(),
69        "alice",
70        "resource1",
71        service_nodes,
72        None,
73    )?;
74    println!("✅ Service chain verification successful\n");
75
76    // Example 3: Verification with key from string
77    println!("Example 3: Verification with key from string");
78
79    // Convert public key to string format and back
80    let pk_hex = hex::encode(root_keypair.public().to_bytes());
81    let pk_str = format!("ed25519/{}", pk_hex);
82    let parsed_pk = biscuit_key_from_string(pk_str)?;
83
84    // Verify with parsed key
85    verify_token(&token_base64, parsed_pk, "alice", "resource1")?;
86    println!("✅ Verification with key from string successful");
87
88    Ok(())
89}
Source

pub fn algorithm(&self) -> Algorithm

Trait Implementations§

Source§

impl Debug for KeyPair

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for KeyPair

Source§

fn default() -> KeyPair

Returns the “default value” for a type. Read more
Source§

impl PartialEq for KeyPair

Source§

fn eq(&self, other: &KeyPair) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl StructuralPartialEq for KeyPair

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V