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(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 fn calc_M3(profile_key_bytes: ProfileKeyBytes, uid_bytes: UidBytes) -> RistrettoPoint {
40 let mut combined_array = [0u8; PROFILE_KEY_LEN + UUID_LEN];
41 combined_array[..PROFILE_KEY_LEN].copy_from_slice(&profile_key_bytes);
42 combined_array[PROFILE_KEY_LEN..].copy_from_slice(&uid_bytes);
43 Sho::new(
44 b"Signal_ZKGroup_20200424_ProfileKeyAndUid_ProfileKey_CalcM3",
45 &combined_array,
46 )
47 .get_point_single_elligator()
48 }
49
50 pub fn to_bytes(&self) -> ProfileKeyBytes {
51 self.bytes
52 }
53}
54
55impl ConditionallySelectable for ProfileKeyStruct {
56 #[expect(
57 clippy::needless_range_loop,
58 reason = "an explicit loop makes it more clear that this runs in constant time"
59 )]
60 fn conditional_select(
61 a: &ProfileKeyStruct,
62 b: &ProfileKeyStruct,
63 choice: Choice,
64 ) -> ProfileKeyStruct {
65 let mut bytes: ProfileKeyBytes = [0u8; PROFILE_KEY_LEN];
66 for i in 0..PROFILE_KEY_LEN {
67 bytes[i] = u8::conditional_select(&a.bytes[i], &b.bytes[i], choice);
68 }
69
70 ProfileKeyStruct {
71 bytes,
72 M3: RistrettoPoint::conditional_select(&a.M3, &b.M3, choice),
73 M4: RistrettoPoint::conditional_select(&a.M4, &b.M4, choice),
74 }
75 }
76}
77
78impl zkcredential::attributes::Attribute for ProfileKeyStruct {
79 fn as_points(&self) -> [RistrettoPoint; 2] {
80 [self.M3, self.M4]
81 }
82}