libsignal_protocol/state/
signed_prekey.rs

1//
2// Copyright 2020-2022 Signal Messenger, LLC.
3// SPDX-License-Identifier: AGPL-3.0-only
4//
5
6use std::convert::AsRef;
7use std::fmt;
8
9use prost::Message;
10
11use crate::proto::storage::SignedPreKeyRecordStructure;
12use crate::{kem, KeyPair, PrivateKey, PublicKey, Result, SignalProtocolError, Timestamp};
13
14/// A unique identifier selecting among this client's known signed pre-keys.
15#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
16pub struct SignedPreKeyId(u32);
17
18impl From<u32> for SignedPreKeyId {
19    fn from(value: u32) -> Self {
20        Self(value)
21    }
22}
23
24impl From<SignedPreKeyId> for u32 {
25    fn from(value: SignedPreKeyId) -> Self {
26        value.0
27    }
28}
29
30impl fmt::Display for SignedPreKeyId {
31    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
32        write!(f, "{}", self.0)
33    }
34}
35
36#[derive(Debug, Clone)]
37pub struct SignedPreKeyRecord {
38    signed_pre_key: SignedPreKeyRecordStructure,
39}
40
41impl SignedPreKeyRecord {
42    pub fn private_key(&self) -> Result<PrivateKey> {
43        PrivateKey::deserialize(&self.get_storage().private_key)
44    }
45}
46
47impl GenericSignedPreKey for SignedPreKeyRecord {
48    type KeyPair = KeyPair;
49    type Id = SignedPreKeyId;
50
51    fn get_storage(&self) -> &SignedPreKeyRecordStructure {
52        &self.signed_pre_key
53    }
54
55    fn from_storage(storage: SignedPreKeyRecordStructure) -> Self {
56        Self {
57            signed_pre_key: storage,
58        }
59    }
60}
61
62pub trait GenericSignedPreKey {
63    type KeyPair: KeyPairSerde;
64    type Id: From<u32> + Into<u32>;
65
66    fn get_storage(&self) -> &SignedPreKeyRecordStructure;
67    fn from_storage(storage: SignedPreKeyRecordStructure) -> Self;
68
69    fn new(id: Self::Id, timestamp: Timestamp, key_pair: &Self::KeyPair, signature: &[u8]) -> Self
70    where
71        Self: Sized,
72    {
73        let timestamp = timestamp.epoch_millis();
74        let public_key = key_pair.get_public().serialize();
75        let private_key = key_pair.get_private().serialize();
76        let signature = signature.to_vec();
77        Self::from_storage(SignedPreKeyRecordStructure {
78            id: id.into(),
79            timestamp,
80            public_key,
81            private_key,
82            signature,
83        })
84    }
85
86    fn serialize(&self) -> Result<Vec<u8>> {
87        Ok(self.get_storage().encode_to_vec())
88    }
89
90    fn deserialize(data: &[u8]) -> Result<Self>
91    where
92        Self: Sized,
93    {
94        Ok(Self::from_storage(
95            SignedPreKeyRecordStructure::decode(data)
96                .map_err(|_| SignalProtocolError::InvalidProtobufEncoding)?,
97        ))
98    }
99
100    fn id(&self) -> Result<Self::Id> {
101        Ok(self.get_storage().id.into())
102    }
103
104    fn timestamp(&self) -> Result<Timestamp> {
105        Ok(Timestamp::from_epoch_millis(self.get_storage().timestamp))
106    }
107
108    fn signature(&self) -> Result<Vec<u8>> {
109        Ok(self.get_storage().signature.clone())
110    }
111
112    fn public_key(&self) -> Result<<Self::KeyPair as KeyPairSerde>::PublicKey> {
113        <Self::KeyPair as KeyPairSerde>::PublicKey::deserialize(&self.get_storage().public_key)
114    }
115
116    fn key_pair(&self) -> Result<Self::KeyPair> {
117        Self::KeyPair::from_public_and_private(
118            &self.get_storage().public_key,
119            &self.get_storage().private_key,
120        )
121    }
122}
123
124pub trait KeySerde {
125    fn serialize(&self) -> Vec<u8>;
126    fn deserialize<T: AsRef<[u8]>>(bytes: T) -> Result<Self>
127    where
128        Self: Sized;
129}
130
131pub trait KeyPairSerde {
132    type PublicKey: KeySerde;
133    type PrivateKey: KeySerde;
134    fn from_public_and_private(public_key: &[u8], private_key: &[u8]) -> Result<Self>
135    where
136        Self: Sized;
137    fn get_public(&self) -> &Self::PublicKey;
138    fn get_private(&self) -> &Self::PrivateKey;
139}
140
141impl KeySerde for PublicKey {
142    fn serialize(&self) -> Vec<u8> {
143        self.serialize().to_vec()
144    }
145
146    fn deserialize<T: AsRef<[u8]>>(bytes: T) -> Result<Self> {
147        Self::deserialize(bytes.as_ref())
148    }
149}
150
151impl KeySerde for PrivateKey {
152    fn serialize(&self) -> Vec<u8> {
153        self.serialize()
154    }
155
156    fn deserialize<T: AsRef<[u8]>>(bytes: T) -> Result<Self> {
157        Self::deserialize(bytes.as_ref())
158    }
159}
160
161impl KeySerde for kem::PublicKey {
162    fn serialize(&self) -> Vec<u8> {
163        self.serialize().to_vec()
164    }
165
166    fn deserialize<T: AsRef<[u8]>>(bytes: T) -> Result<Self>
167    where
168        Self: Sized,
169    {
170        Self::deserialize(bytes.as_ref())
171    }
172}
173
174impl KeySerde for kem::SecretKey {
175    fn serialize(&self) -> Vec<u8> {
176        self.serialize().to_vec()
177    }
178    fn deserialize<T: AsRef<[u8]>>(bytes: T) -> Result<Self>
179    where
180        Self: Sized,
181    {
182        Self::deserialize(bytes.as_ref())
183    }
184}
185
186impl KeyPairSerde for KeyPair {
187    type PublicKey = PublicKey;
188    type PrivateKey = PrivateKey;
189
190    fn from_public_and_private(public_key: &[u8], private_key: &[u8]) -> Result<Self> {
191        KeyPair::from_public_and_private(public_key, private_key)
192    }
193
194    fn get_public(&self) -> &PublicKey {
195        &self.public_key
196    }
197
198    fn get_private(&self) -> &PrivateKey {
199        &self.private_key
200    }
201}
202
203impl KeyPairSerde for kem::KeyPair {
204    type PublicKey = kem::PublicKey;
205    type PrivateKey = kem::SecretKey;
206
207    fn from_public_and_private(public_key: &[u8], private_key: &[u8]) -> Result<Self> {
208        kem::KeyPair::from_public_and_private(public_key, private_key)
209    }
210
211    fn get_public(&self) -> &kem::PublicKey {
212        &self.public_key
213    }
214
215    fn get_private(&self) -> &kem::SecretKey {
216        &self.secret_key
217    }
218}