bc_components/
private_keys.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
use anyhow::{ bail, Error, Result };
use bc_ur::prelude::*;
use crate::{
    tags,
    Decrypter,
    Digest,
    EncapsulationPrivateKey,
    Reference,
    ReferenceProvider,
    Signature,
    Signer,
    SigningPrivateKey,
};

/// Holds information used to communicate cryptographically with a remote
/// entity.
///
/// Includes the entity's private signing key for making signatures, and the
/// entity's private encapsulation key used to decrypt messages.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PrivateKeys {
    signing_private_key: SigningPrivateKey,
    encapsulation_private_key: EncapsulationPrivateKey,
}

impl PrivateKeys {
    /// Restores a `PrivateKeys` from a `SigningPrivateKey` and an `EncapsulationPrivateKey`.
    pub fn with_keys(
        signing_private_key: SigningPrivateKey,
        encapsulation_private_key: EncapsulationPrivateKey
    ) -> Self {
        Self {
            signing_private_key,
            encapsulation_private_key,
        }
    }

    /// Returns the `SigningPrivateKey` of this `PrivateKeys`.
    pub fn signing_private_key(&self) -> &SigningPrivateKey {
        &self.signing_private_key
    }

    /// Returns the `EncapsulationPrivateKey` of this `PrivateKeys`.
    pub fn enapsulation_private_key(&self) -> &EncapsulationPrivateKey {
        &self.encapsulation_private_key
    }
}

pub trait PrivateKeysProvider {
    fn private_keys(&self) -> PrivateKeys;
}

impl PrivateKeysProvider for PrivateKeys {
    fn private_keys(&self) -> PrivateKeys {
        self.clone()
    }
}

impl ReferenceProvider for PrivateKeys {
    fn reference(&self) -> Reference {
        Reference::from_digest(Digest::from_image(self.tagged_cbor().to_cbor_data()))
    }
}

impl AsRef<PrivateKeys> for PrivateKeys {
    fn as_ref(&self) -> &PrivateKeys {
        self
    }
}

impl AsRef<SigningPrivateKey> for PrivateKeys {
    fn as_ref(&self) -> &SigningPrivateKey {
        &self.signing_private_key
    }
}

impl AsRef<EncapsulationPrivateKey> for PrivateKeys {
    fn as_ref(&self) -> &EncapsulationPrivateKey {
        &self.encapsulation_private_key
    }
}

impl CBORTagged for PrivateKeys {
    fn cbor_tags() -> Vec<Tag> {
        tags_for_values(&[tags::TAG_PRIVATE_KEYS])
    }
}

impl From<PrivateKeys> for CBOR {
    fn from(value: PrivateKeys) -> Self {
        value.tagged_cbor()
    }
}

impl CBORTaggedEncodable for PrivateKeys {
    fn untagged_cbor(&self) -> CBOR {
        let signing_key_cbor: CBOR = self.signing_private_key.clone().into();
        let encapsulation_key_cbor: CBOR = self.encapsulation_private_key.clone().into();
        vec![signing_key_cbor, encapsulation_key_cbor].into()
    }
}

impl TryFrom<CBOR> for PrivateKeys {
    type Error = Error;

    fn try_from(cbor: CBOR) -> Result<Self, Self::Error> {
        Self::from_tagged_cbor(cbor)
    }
}

impl CBORTaggedDecodable for PrivateKeys {
    fn from_untagged_cbor(untagged_cbor: CBOR) -> Result<Self> {
        match untagged_cbor.as_case() {
            CBORCase::Array(elements) => {
                if elements.len() != 2 {
                    bail!("PrivateKeys must have two elements");
                }

                let signing_private_key = SigningPrivateKey::try_from(elements[0].clone())?;
                let encapsulation_private_key = EncapsulationPrivateKey::try_from(
                    elements[1].clone()
                )?;
                Ok(Self::with_keys(signing_private_key, encapsulation_private_key))
            }
            _ => bail!("PrivateKeys must be an array"),
        }
    }
}

impl Signer for PrivateKeys {
    fn sign_with_options(
        &self,
        message: &dyn AsRef<[u8]>,
        options: Option<crate::SigningOptions>
    ) -> Result<Signature> {
        self.signing_private_key.sign_with_options(message, options)
    }
}

impl Decrypter for PrivateKeys {
    fn encapsulation_private_key(&self) -> EncapsulationPrivateKey {
        self.encapsulation_private_key.clone()
    }
}

impl std::fmt::Display for PrivateKeys {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "PrivateKeys({})", self.reference().ref_hex_short())
    }
}

#[cfg(test)]
mod tests {
    use bc_ur::{ UREncodable, URDecodable };
    use hex_literal::hex;
    use dcbor::prelude::*;

    use crate::{ PrivateKeyBase, PrivateKeys, PrivateKeysProvider, ReferenceProvider };

    const SEED: [u8; 16] = hex!("59f2293a5bce7d4de59e71b4207ac5d2");

    #[test]
    fn test_private_keys() {
        crate::register_tags();

        let private_key_base = PrivateKeyBase::from_data(SEED);
        let private_keys = private_key_base.private_keys();

        let cbor = CBOR::from(private_keys.clone());
        println!("{}", cbor.diagnostic_annotated());

        let private_keys_2 = PrivateKeys::try_from(cbor.clone()).unwrap();
        assert_eq!(private_keys, private_keys_2);

        let cbor_2 = CBOR::from(private_keys_2);
        assert_eq!(cbor, cbor_2);

        let ur = private_keys.ur_string();
        assert_eq!(
            ur,
            "ur:crypto-prvkeys/lftansgohdcxmdahoxgepeethhvaeotkbadnssnnihsflokkfwbwryzoyasgwtfpgdrhssmhhehttansgehdcxktzmlslflpnbfzfsencspklkdygactnlykgmclrnbdmwgwgdrsqdjswkfrldjylpmtdpskfx"
        );
        assert_eq!(PrivateKeys::from_ur_string(&ur).unwrap(), private_keys);

        assert_eq!(format!("{}", private_keys), "PrivateKeys(fa742ac8)");
        assert_eq!(format!("{}", private_keys.reference()), "Reference(fa742ac8)");
    }
}