summaryrefslogtreecommitdiffstats
path: root/openpgp/src/tsk.rs
blob: 120fc88b993eb05e4e5f4f844aab3c14aa07de9f (plain)
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
use std::borrow::Cow;
use std::io;
use std::ops::{Deref, DerefMut};
use std::path::Path;

use {
    Result,
    TPK,
    Error,
};

use packet::{
    signature::{Signature, KeyPair},
    Tag,
    UserID,
    Key,
};
use serialize::{
    Serialize,
    SerializeKey,
};
use parse::{Parse, PacketParserResult};

/// A transferable secret key (TSK).
///
/// A TSK (see [RFC 4880, section 11.2]) can be used to create
/// signatures and decrypt data.
///
/// [RFC 4880, section 11.2]: https://tools.ietf.org/html/rfc4880#section-11.2
#[derive(Debug, PartialEq)]
pub struct TSK {
    key: TPK,
}

impl Deref for TSK {
    type Target = TPK;

    fn deref(&self) -> &Self::Target {
        &self.key
    }
}

impl DerefMut for TSK {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.key
    }
}

impl<'a> Parse<'a, TSK> for TSK {
    /// Initializes a `TSK` from a `Read`er.
    fn from_reader<R: 'a + io::Read>(reader: R) -> Result<Self> {
        TPK::from_reader(reader).map(|tpk| Self::from_tpk(tpk))
    }

    /// Initializes a `TSK` from a `File`.
    fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
        TPK::from_file(path).map(|tpk| Self::from_tpk(tpk))
    }

    /// Initializes a `TSK` from a byte string.
    fn from_bytes(data: &'a [u8]) -> Result<Self> {
        TPK::from_bytes(data).map(|tpk| Self::from_tpk(tpk))
    }
}

impl TSK {
    /// Initializes a `TSK` from a `PacketParser`.
    pub fn from_packet_parser<'a>(ppr: PacketParserResult<'a>) -> Result<Self> {
        TPK::from_packet_parser(ppr).map(|tpk| Self::from_tpk(tpk))
    }

    pub(crate) fn from_tpk(tpk: TPK) -> TSK {
        TSK{ key: tpk }
    }

    /// Generates a new key OpenPGP key. The key will be capable of encryption
    /// and signing. If no user id is given the primary self signature will be
    /// a direct key signature.
    pub fn new<'a, O: Into<Option<Cow<'a,str>>>>(primary_uid: O)
                                                 -> Result<(TSK, Signature)> {
        use tpk::TPKBuilder;

        let mut key = TPKBuilder::autocrypt(None);

        match primary_uid.into() {
            Some(uid) => { key = key.add_userid(&uid); }
            None => {}
        }

        let (tpk, revocation) = key.generate()?;
        Ok((TSK::from_tpk(tpk), revocation))
    }

    /// Returns a reference to the corresponding TPK.
    pub fn tpk<'a>(&'a self) -> &'a TPK {
        &self.key
    }

    /// Converts to a TPK.
    pub fn into_tpk(self) -> TPK {
        self.key
    }

    /// Signs `key` and `userid` with a 3rd party certification.
    pub fn certify_userid(&self, key: &Key, userid: &UserID) -> Result<Signature> {
        use packet::{KeyFlags, signature, key::SecretKey};
        use constants::{HashAlgorithm, SignatureType};

        let caps = KeyFlags::default().set_certify(true);
        let keys = self.key.select_keys(caps, None);

        match keys.first() {
            Some(ref my_key) => {
                match my_key.secret() {
                    Some(&SecretKey::Unencrypted{ ref mpis }) => {
                        signature::Builder::new(SignatureType::GenericCertificate)
                            .sign_userid_binding(
                                &mut KeyPair::new(my_key, mpis)?,
                                key, userid, HashAlgorithm::SHA512)
                    }
                    _ => Err(Error::InvalidOperation(
                            "secret key missing or encrypted".into()).into()),
                }
            }
            None => Err(Error::InvalidOperation(
                        "this key cannot certify keys".into()).into()),
        }
    }

    /// Signs the primary key's self signatures of `key`.
    pub fn certify_key(&self, key: &TPK) -> Result<Signature> {
        match key.primary_key_signature_full() {
            None | Some((None, _)) =>
                Err(Error::InvalidOperation(
                    "this key has nothing to certify".into()).into()),
            Some((Some(uid), _)) =>
                self.certify_userid(key.primary(), uid.userid()),
        }
    }
 }

impl Serialize for TSK {
    /// Serializes the TSK.
    fn serialize<W: io::Write>(&self, o: &mut W) -> Result<()> {
        self.key.primary.serialize(o, Tag::SecretKey)?;

        for s in self.key.primary_selfsigs.iter() {
            s.serialize(o)?;
        }
        for s in self.key.primary_self_revocations.iter() {
            s.serialize(o)?;
        }
        for s in self.key.primary_certifications.iter() {
            s.serialize(o)?;
        }
        for s in self.key.primary_other_revocations.iter() {
            s.serialize(o)?;
        }

        for u in self.key.userids() {
            u.userid().serialize(o)?;
            for s in u.self_revocations() {
                s.serialize(o)?;
            }
            for s in u.selfsigs() {
                s.serialize(o)?;
            }
            for s in u.other_revocations() {
                s.serialize(o)?;
            }
            for s in u.certifications() {
                s.serialize(o)?;
            }
        }

        for u in self.key.user_attributes() {
            u.user_attribute().serialize(o)?;
            for s in u.self_revocations() {
                s.serialize(o)?;
            }
            for s in u.selfsigs() {
                s.serialize(o)?;
            }
            for s in u.other_revocations() {
                s.serialize(o)?;
            }
            for s in u.certifications() {
                s.serialize(o)?;
            }
        }

        for k in self.key.subkeys() {
            k.subkey().serialize(o, Tag::SecretSubkey)?;
            for s in k.self_revocations</