Skip to main content

rialo_types/
crypto.rs

1// Copyright (c) Subzero Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Cryptographic primitives and key types used throughout the system
5
6use borsh::{BorshDeserialize, BorshSerialize};
7use serde::{Deserialize, Serialize};
8
9/// Size of X25519 private/public keys in bytes.
10pub const X25519_KEY_SIZE: usize = 32;
11
12/// Size of TEE user data in bytes.
13pub const TEE_USER_DATA_SIZE: usize = 32;
14
15/// Type alias for TEE user data
16pub type TeeUserData = [u8; TEE_USER_DATA_SIZE];
17
18/// Strongly typed X25519 public key wrapper used throughout the TEE crates.
19///
20/// This type provides a type-safe wrapper around X25519 public keys, ensuring
21/// proper serialization and preventing misuse of raw byte arrays.
22#[derive(
23    Clone,
24    Copy,
25    Debug,
26    PartialEq,
27    Eq,
28    Hash,
29    Serialize,
30    Deserialize,
31    BorshSerialize,
32    BorshDeserialize,
33)]
34pub struct PublicKey([u8; X25519_KEY_SIZE]);
35
36impl PublicKey {
37    /// Create a PublicKey from raw bytes
38    pub fn from_bytes(bytes: [u8; X25519_KEY_SIZE]) -> Self {
39        Self(bytes)
40    }
41
42    /// Convert PublicKey to raw bytes
43    pub fn to_bytes(self) -> [u8; X25519_KEY_SIZE] {
44        self.0
45    }
46
47    /// Get a reference to the raw bytes
48    pub fn as_bytes(&self) -> &[u8; X25519_KEY_SIZE] {
49        &self.0
50    }
51}
52
53impl From<x25519_dalek::PublicKey> for PublicKey {
54    fn from(key: x25519_dalek::PublicKey) -> Self {
55        Self(key.to_bytes())
56    }
57}
58
59impl From<PublicKey> for x25519_dalek::PublicKey {
60    fn from(pk: PublicKey) -> Self {
61        x25519_dalek::PublicKey::from(pk.0)
62    }
63}
64
65impl From<&x25519_dalek::StaticSecret> for PublicKey {
66    fn from(private_key: &x25519_dalek::StaticSecret) -> Self {
67        Self(x25519_dalek::PublicKey::from(private_key).to_bytes())
68    }
69}
70
71impl AsRef<[u8]> for PublicKey {
72    fn as_ref(&self) -> &[u8] {
73        &self.0
74    }
75}
76
77impl AsRef<[u8; X25519_KEY_SIZE]> for PublicKey {
78    fn as_ref(&self) -> &[u8; X25519_KEY_SIZE] {
79        &self.0
80    }
81}
82
83impl Default for PublicKey {
84    fn default() -> Self {
85        Self([0u8; X25519_KEY_SIZE])
86    }
87}