1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
//
// Copyright 2023 Signal Messenger, LLC.
// SPDX-License-Identifier: AGPL-3.0-only
//

use std::fmt;

use crate::proto::storage::SignedPreKeyRecordStructure;
use crate::state::GenericSignedPreKey;
use crate::{kem, PrivateKey, Result, Timestamp};

/// A unique identifier selecting among this client's known signed pre-keys.
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct KyberPreKeyId(u32);

impl From<u32> for KyberPreKeyId {
    fn from(value: u32) -> Self {
        Self(value)
    }
}

impl From<KyberPreKeyId> for u32 {
    fn from(value: KyberPreKeyId) -> Self {
        value.0
    }
}

impl fmt::Display for KyberPreKeyId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

#[derive(Debug, Clone)]
pub struct KyberPreKeyRecord {
    signed_pre_key: SignedPreKeyRecordStructure,
}

impl GenericSignedPreKey for KyberPreKeyRecord {
    type KeyPair = kem::KeyPair;
    type Id = KyberPreKeyId;

    fn get_storage(&self) -> &SignedPreKeyRecordStructure {
        &self.signed_pre_key
    }

    fn from_storage(storage: SignedPreKeyRecordStructure) -> Self {
        Self {
            signed_pre_key: storage,
        }
    }
}

impl KyberPreKeyRecord {
    pub fn secret_key(&self) -> Result<kem::SecretKey> {
        kem::SecretKey::deserialize(&self.signed_pre_key.private_key)
    }
}

impl KyberPreKeyRecord {
    pub fn generate(
        kyber_key_type: kem::KeyType,
        id: KyberPreKeyId,
        signing_key: &PrivateKey,
    ) -> Result<KyberPreKeyRecord> {
        let key_pair = kem::KeyPair::generate(kyber_key_type);
        let mut rng = rand::rngs::OsRng;
        let signature = signing_key
            .calculate_signature(&key_pair.public_key.serialize(), &mut rng)?
            .into_vec();
        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::SystemTime::UNIX_EPOCH)
            .expect("Time should move forward")
            .as_millis();
        Ok(KyberPreKeyRecord::new(
            id,
            Timestamp::from_epoch_millis(timestamp.try_into().expect("Timestamp too large")),
            &key_pair,
            &signature,
        ))
    }
}