zkgroup/crypto/
profile_key_struct.rs

1//
2// Copyright 2020 Signal Messenger, LLC.
3// SPDX-License-Identifier: AGPL-3.0-only
4//
5
6#![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    #[allow(clippy::needless_range_loop)]
57    fn conditional_select(
58        a: &ProfileKeyStruct,
59        b: &ProfileKeyStruct,
60        choice: Choice,
61    ) -> ProfileKeyStruct {
62        let mut bytes: ProfileKeyBytes = [0u8; PROFILE_KEY_LEN];
63        for i in 0..PROFILE_KEY_LEN {
64            bytes[i] = u8::conditional_select(&a.bytes[i], &b.bytes[i], choice);
65        }
66
67        ProfileKeyStruct {
68            bytes,
69            M3: RistrettoPoint::conditional_select(&a.M3, &b.M3, choice),
70            M4: RistrettoPoint::conditional_select(&a.M4, &b.M4, choice),
71        }
72    }
73}
74
75impl zkcredential::attributes::Attribute for ProfileKeyStruct {
76    fn as_points(&self) -> [RistrettoPoint; 2] {
77        [self.M3, self.M4]
78    }
79}