libsignal_protocol/keys/
identity_key_pair.rs

1use crate::{
2    errors::FromInternalErrorCode,
3    keys::{PrivateKey, PublicKey},
4    raw_ptr::Raw,
5};
6use failure::Error;
7use std::{
8    fmt::{self, Debug, Formatter},
9    ptr,
10};
11
12/// A "ratcheting" key pair.
13#[derive(Clone)]
14pub struct IdentityKeyPair {
15    pub(crate) raw: Raw<sys::ratchet_identity_key_pair>,
16}
17
18impl IdentityKeyPair {
19    /// Create a new [`IdentityKeyPair`] out of its public and private keys.
20    pub fn new(
21        public_key: &PublicKey,
22        private_key: &PrivateKey,
23    ) -> Result<IdentityKeyPair, Error> {
24        unsafe {
25            let mut raw = ptr::null_mut();
26            sys::ratchet_identity_key_pair_create(
27                &mut raw,
28                public_key.raw.as_ptr(),
29                private_key.raw.as_ptr(),
30            )
31            .into_result()?;
32
33            Ok(IdentityKeyPair {
34                raw: Raw::from_ptr(raw),
35            })
36        }
37    }
38
39    /// Get the public part of this key pair.
40    pub fn public(&self) -> PublicKey {
41        unsafe {
42            let raw = sys::ratchet_identity_key_pair_get_public(
43                self.raw.as_const_ptr(),
44            );
45            assert!(!raw.is_null());
46            PublicKey {
47                raw: Raw::copied_from(raw),
48            }
49        }
50    }
51
52    /// Get the public part of this key pair.
53    pub fn private(&self) -> PrivateKey {
54        unsafe {
55            let raw = sys::ratchet_identity_key_pair_get_private(
56                self.raw.as_const_ptr(),
57            );
58            assert!(!raw.is_null());
59            PrivateKey {
60                raw: Raw::copied_from(raw),
61            }
62        }
63    }
64}
65
66impl Debug for IdentityKeyPair {
67    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
68        f.debug_struct("IdentityKeyPair")
69            .field("public", &self.public())
70            .field("private", &self.private())
71            .finish()
72    }
73}
74
75impl_serializable!(IdentityKeyPair, ratchet_identity_key_pair_serialize, foo);