zkgroup/crypto/
profile_key_struct.rs1#![allow(non_snake_case)]
7
8use curve25519_dalek_signal::ristretto::RistrettoPoint;
9use partial_default::PartialDefault;
10use serde::{Deserialize, Serialize};
11use subtle::{Choice, ConditionallySelectable};
12
13use crate::common::constants::*;
14use crate::common::sho::*;
15use crate::common::simple_types::*;
16
17#[derive(Copy, Clone, PartialEq, Eq, Serialize, Deserialize, PartialDefault)]
18pub struct ProfileKeyStruct {
19 pub(crate) bytes: ProfileKeyBytes,
20 pub(crate) M3: RistrettoPoint,
21 pub(crate) M4: RistrettoPoint,
22}
23
24impl ProfileKeyStruct {
25 pub fn new(profile_key_bytes: ProfileKeyBytes, uid_bytes: UidBytes) -> Self {
26 let mut encoded_profile_key = profile_key_bytes;
27 encoded_profile_key[0] &= 254;
28 encoded_profile_key[31] &= 63;
29 let M3 = Self::calc_M3(Self::seed_M3(), profile_key_bytes, uid_bytes);
30 let M4 = RistrettoPoint::from_uniform_bytes_single_elligator(&encoded_profile_key);
31
32 ProfileKeyStruct {
33 bytes: profile_key_bytes,
34 M3,
35 M4,
36 }
37 }
38
39 pub(crate) fn seed_M3() -> Sho {
40 Sho::new_seed(b"Signal_ZKGroup_20200424_ProfileKeyAndUid_ProfileKey_CalcM3")
41 }
42
43 pub(crate) fn calc_M3(
44 mut seed: Sho,
45 profile_key_bytes: ProfileKeyBytes,
46 uid_bytes: UidBytes,
47 ) -> RistrettoPoint {
48 let mut combined_array = [0u8; PROFILE_KEY_LEN + UUID_LEN];
49 combined_array[..PROFILE_KEY_LEN].copy_from_slice(&profile_key_bytes);
50 combined_array[PROFILE_KEY_LEN..].copy_from_slice(&uid_bytes);
51 seed.absorb_and_ratchet(&combined_array);
52 seed.get_point_single_elligator()
53 }
54
55 pub fn to_bytes(&self) -> ProfileKeyBytes {
56 self.bytes
57 }
58}
59
60impl ConditionallySelectable for ProfileKeyStruct {
61 #[expect(
62 clippy::needless_range_loop,
63 reason = "an explicit loop makes it more clear that this runs in constant time"
64 )]
65 fn conditional_select(
66 a: &ProfileKeyStruct,
67 b: &ProfileKeyStruct,
68 choice: Choice,
69 ) -> ProfileKeyStruct {
70 let mut bytes: ProfileKeyBytes = [0u8; PROFILE_KEY_LEN];
71 for i in 0..PROFILE_KEY_LEN {
72 bytes[i] = u8::conditional_select(&a.bytes[i], &b.bytes[i], choice);
73 }
74
75 ProfileKeyStruct {
76 bytes,
77 M3: RistrettoPoint::conditional_select(&a.M3, &b.M3, choice),
78 M4: RistrettoPoint::conditional_select(&a.M4, &b.M4, choice),
79 }
80 }
81}
82
83impl zkcredential::attributes::Attribute for ProfileKeyStruct {
84 fn as_points(&self) -> [RistrettoPoint; 2] {
85 [self.M3, self.M4]
86 }
87}