libsignal_protocol/state/
prekey.rs

1//
2// Copyright 2020-2022 Signal Messenger, LLC.
3// SPDX-License-Identifier: AGPL-3.0-only
4//
5
6use std::fmt;
7
8use prost::Message;
9
10use crate::proto::storage::PreKeyRecordStructure;
11use crate::{KeyPair, PrivateKey, PublicKey, Result, SignalProtocolError};
12
13/// A unique identifier selecting among this client's known pre-keys.
14#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
15pub struct PreKeyId(u32);
16
17impl From<u32> for PreKeyId {
18    fn from(value: u32) -> Self {
19        Self(value)
20    }
21}
22
23impl From<PreKeyId> for u32 {
24    fn from(value: PreKeyId) -> Self {
25        value.0
26    }
27}
28
29impl fmt::Display for PreKeyId {
30    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
31        write!(f, "{}", self.0)
32    }
33}
34
35#[derive(Debug, Clone)]
36pub struct PreKeyRecord {
37    pre_key: PreKeyRecordStructure,
38}
39
40impl PreKeyRecord {
41    pub fn new(id: PreKeyId, key: &KeyPair) -> Self {
42        let public_key = key.public_key.serialize().to_vec();
43        let private_key = key.private_key.serialize().to_vec();
44        Self {
45            pre_key: PreKeyRecordStructure {
46                id: id.into(),
47                public_key,
48                private_key,
49            },
50        }
51    }
52
53    pub fn deserialize(data: &[u8]) -> Result<Self> {
54        Ok(Self {
55            pre_key: PreKeyRecordStructure::decode(data)
56                .map_err(|_| SignalProtocolError::InvalidProtobufEncoding)?,
57        })
58    }
59
60    pub fn id(&self) -> Result<PreKeyId> {
61        Ok(self.pre_key.id.into())
62    }
63
64    pub fn key_pair(&self) -> Result<KeyPair> {
65        KeyPair::from_public_and_private(&self.pre_key.public_key, &self.pre_key.private_key)
66    }
67
68    pub fn public_key(&self) -> Result<PublicKey> {
69        PublicKey::deserialize(&self.pre_key.public_key)
70    }
71
72    pub fn private_key(&self) -> Result<PrivateKey> {
73        PrivateKey::deserialize(&self.pre_key.private_key)
74    }
75
76    pub fn serialize(&self) -> Result<Vec<u8>> {
77        Ok(self.pre_key.encode_to_vec())
78    }
79}