iwlink 0.1.1

IntelliWallet Link - encrypted phone to computer protocol for IntelliWallet for Browser
Documentation
//! Static X25519 keys.
//!
//! Each helper install has one static keypair. The phone has one per paired
//! computer, so unpairing a computer is deleting one key and two computers
//! never see the same phone key.
//!
//! Callers store both halves. The public half cannot be recomputed here
//! without adding a direct X25519 dependency next to the one inside `snow`, and
//! storing 32 more bytes is cheaper than that.

use zeroize::Zeroizing;

use crate::error::{LinkError, Result};
use crate::noise::RECONNECT_PATTERN;

/// Length of an X25519 key.
pub const KEY_LEN: usize = 32;

/// A static public key.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PublicKey(pub [u8; KEY_LEN]);

impl PublicKey {
    /// From a byte slice of exactly [`KEY_LEN`] bytes.
    pub fn from_slice(bytes: &[u8]) -> Result<PublicKey> {
        let array: [u8; KEY_LEN] = bytes
            .try_into()
            .map_err(|_| LinkError::InvalidKey("public key length"))?;
        Ok(PublicKey(array))
    }

    pub fn as_bytes(&self) -> &[u8; KEY_LEN] {
        &self.0
    }
}

/// A static keypair. The secret half is wiped when dropped.
pub struct StaticKeypair {
    secret: Zeroizing<[u8; KEY_LEN]>,
    public: PublicKey,
}

impl StaticKeypair {
    /// A fresh keypair from the operating system's generator.
    pub fn generate() -> Result<StaticKeypair> {
        let params = RECONNECT_PATTERN
            .parse()
            .map_err(|_| LinkError::InvalidKey("noise parameters"))?;
        let pair = snow::Builder::new(params).generate_keypair()?;
        let secret = Zeroizing::new(
            <[u8; KEY_LEN]>::try_from(pair.private.as_slice())
                .map_err(|_| LinkError::InvalidKey("secret key length"))?,
        );
        let public = PublicKey::from_slice(&pair.public)?;
        // `pair.private` is a plain Vec; wipe it rather than leave a copy of the
        // secret behind in freed memory.
        let mut private = pair.private;
        zeroize::Zeroize::zeroize(&mut private);
        Ok(StaticKeypair { secret, public })
    }

    /// Rebuild a stored keypair.
    pub fn from_parts(secret: &[u8], public: &[u8]) -> Result<StaticKeypair> {
        let secret = Zeroizing::new(
            <[u8; KEY_LEN]>::try_from(secret)
                .map_err(|_| LinkError::InvalidKey("secret key length"))?,
        );
        Ok(StaticKeypair {
            secret,
            public: PublicKey::from_slice(public)?,
        })
    }

    pub fn public(&self) -> PublicKey {
        self.public
    }

    /// The secret half, for the caller to store in the Keychain or Keystore.
    pub fn secret_bytes(&self) -> &[u8; KEY_LEN] {
        &self.secret
    }
}

impl std::fmt::Debug for StaticKeypair {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("StaticKeypair")
            .field("public", &self.public)
            .finish_non_exhaustive()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn generated_keys_differ() {
        let a = StaticKeypair::generate().unwrap();
        let b = StaticKeypair::generate().unwrap();
        assert_ne!(a.public(), b.public());
        assert_ne!(a.secret_bytes(), b.secret_bytes());
    }

    #[test]
    fn from_parts_round_trips() {
        let a = StaticKeypair::generate().unwrap();
        let b = StaticKeypair::from_parts(a.secret_bytes(), a.public().as_bytes()).unwrap();
        assert_eq!(a.public(), b.public());
        assert_eq!(a.secret_bytes(), b.secret_bytes());
    }

    #[test]
    fn wrong_lengths_are_rejected() {
        assert!(PublicKey::from_slice(&[0u8; 31]).is_err());
        assert!(StaticKeypair::from_parts(&[0u8; 33], &[0u8; 32]).is_err());
    }

    #[test]
    fn debug_does_not_print_the_secret() {
        let pair = StaticKeypair::from_parts(&[0xAB; 32], &[1; 32]).unwrap();
        let text = format!("{pair:?}");
        assert!(!text.contains("171"), "secret byte 0xAB leaked: {text}");
    }
}