rust_sike/isogeny/
secretkey.rs

1//! Secret key
2use bitvec::prelude::*;
3
4#[derive(Clone, PartialEq)]
5/// Secret key
6pub struct SecretKey {
7    bytes: Vec<u8>,
8}
9
10impl std::fmt::Debug for SecretKey {
11    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12        write!(f, "{:?}", self.bytes)
13    }
14}
15
16impl SecretKey {
17    /// Get a random secret key of given `size` in bytes
18    ///
19    /// # Examples
20    ///
21    /// ```rust
22    /// use rust_sike::pke::SecretKey;
23    /// let key = SecretKey::get_random_secret_key(64);
24    /// println!("{:?}", key);
25    /// ```
26    pub fn get_random_secret_key(size: usize) -> Result<Self, String> {
27        let mut bytes = vec![0; size];
28        if let Err(_e) = getrandom::getrandom(&mut bytes) {
29            return Err(String::from("RNG Error"));
30        };
31        Ok(Self::from_bytes(&bytes))
32    }
33
34    /// Converts the secret key into a sequence of bits
35    ///
36    /// Note: The format is big endian
37    pub fn to_bits(&self) -> BitVec<Msb0, u8> {
38        // We reverse the order of the bytes
39        // such that bits are properly ordered
40        //      Ex : [1, 0] -> [00000000, 00000001]
41        let bytes = self.bytes.iter().rev().copied().collect();
42        BitVec::<Msb0, u8>::from_vec(bytes)
43    }
44
45    /// Converts the secret key to bytes
46    pub fn to_bytes(&self) -> Vec<u8> {
47        self.bytes.clone()
48    }
49
50    /// Build a secret key from bytes
51    pub fn from_bytes(bytes: &[u8]) -> Self {
52        Self {
53            bytes: bytes.to_vec(),
54        }
55    }
56}