atrium_crypto/
algorithm.rs

1use multibase::Base;
2
3/// Supported algorithms (elliptic curves) for atproto cryptography.
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub enum Algorithm {
6    /// [`p256`] elliptic curve: aka "NIST P-256", aka `secp256r1` (note the `r`), aka `prime256v1`.
7    P256,
8    /// [`k256`] elliptic curve: aka "NIST K-256", aka `secp256k1` (note the `k`).
9    Secp256k1,
10}
11
12impl Algorithm {
13    const MULTICODE_PREFIX_P256: [u8; 2] = [0x80, 0x24];
14    const MULTICODE_PREFIX_SECP256K1: [u8; 2] = [0xe7, 0x01];
15
16    pub(crate) fn prefix(&self) -> [u8; 2] {
17        match self {
18            Self::P256 => Self::MULTICODE_PREFIX_P256,
19            Self::Secp256k1 => Self::MULTICODE_PREFIX_SECP256K1,
20        }
21    }
22    pub(crate) fn from_prefix(prefix: [u8; 2]) -> Option<Self> {
23        match prefix {
24            Self::MULTICODE_PREFIX_P256 => Some(Self::P256),
25            Self::MULTICODE_PREFIX_SECP256K1 => Some(Self::Secp256k1),
26            _ => None,
27        }
28    }
29    pub(crate) fn format_mulikey_compressed(&self, key: &[u8]) -> String {
30        let mut v = Vec::with_capacity(2 + key.len());
31        v.extend_from_slice(&self.prefix());
32        v.extend_from_slice(key);
33        multibase::encode(Base::Base58Btc, v)
34    }
35}