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(
15    Copy, Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd, derive_more::From, derive_more::Into,
16)]
17pub struct PreKeyId(u32);
18
19impl fmt::Display for PreKeyId {
20    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
21        write!(f, "{}", self.0)
22    }
23}
24
25#[derive(Debug, Clone)]
26pub struct PreKeyRecord {
27    pre_key: PreKeyRecordStructure,
28}
29
30impl PreKeyRecord {
31    pub fn new(id: PreKeyId, key: &KeyPair) -> Self {
32        let public_key = key.public_key.serialize().to_vec();
33        let private_key = key.private_key.serialize().to_vec();
34        Self {
35            pre_key: PreKeyRecordStructure {
36                id: id.into(),
37                public_key,
38                private_key,
39            },
40        }
41    }
42
43    pub fn deserialize(data: &[u8]) -> Result<Self> {
44        Ok(Self {
45            pre_key: PreKeyRecordStructure::decode(data)
46                .map_err(|_| SignalProtocolError::InvalidProtobufEncoding)?,
47        })
48    }
49
50    pub fn id(&self) -> Result<PreKeyId> {
51        Ok(self.pre_key.id.into())
52    }
53
54    pub fn key_pair(&self) -> Result<KeyPair> {
55        Ok(KeyPair::from_public_and_private(
56            &self.pre_key.public_key,
57            &self.pre_key.private_key,
58        )?)
59    }
60
61    pub fn public_key(&self) -> Result<PublicKey> {
62        Ok(PublicKey::deserialize(&self.pre_key.public_key)?)
63    }
64
65    pub fn private_key(&self) -> Result<PrivateKey> {
66        Ok(PrivateKey::deserialize(&self.pre_key.private_key)?)
67    }
68
69    pub fn serialize(&self) -> Result<Vec<u8>> {
70        Ok(self.pre_key.encode_to_vec())
71    }
72}