mixnet/core/kx_pair.rs
1// Copyright 2022 Parity Technologies (UK) Ltd.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the "Software"),
5// to deal in the Software without restriction, including without limitation
6// the rights to use, copy, modify, merge, publish, distribute, sublicense,
7// and/or sell copies of the Software, and to permit persons to whom the
8// Software is furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19// DEALINGS IN THE SOFTWARE.
20
21//! Mixnet key-exchange key pair.
22
23use super::sphinx::{
24 derive_kx_public, derive_kx_shared_secret, gen_kx_secret, KxPublic, KxSecret, SharedSecret,
25};
26use rand::{CryptoRng, Rng};
27use zeroize::Zeroizing;
28
29pub struct KxPair {
30 /// Unclamped secret key. Boxed to avoid leaving copies around in memory if `KxPair` is moved.
31 secret: Box<Zeroizing<KxSecret>>,
32 public: KxPublic,
33}
34
35impl KxPair {
36 pub fn gen(rng: &mut (impl Rng + CryptoRng)) -> Self {
37 gen_kx_secret(rng).into()
38 }
39
40 pub fn public(&self) -> &KxPublic {
41 &self.public
42 }
43
44 pub fn exchange(&self, their_public: &KxPublic) -> SharedSecret {
45 derive_kx_shared_secret(their_public, self.secret.as_ref())
46 }
47}
48
49impl From<KxSecret> for KxPair {
50 fn from(secret: KxSecret) -> Self {
51 // We box the secret to avoid leaving copies of it in memory when the KxPair is moved. Note
52 // that we will likely leave some copies on the stack here; I'm not aware of any good way
53 // of avoiding this.
54 let secret = Box::new(Zeroizing::new(secret));
55 let public = derive_kx_public(secret.as_ref());
56 Self { secret, public }
57 }
58}