summaryrefslogtreecommitdiffstats
path: root/autocrypt/src/cert.rs
blob: b1bef1610bba9e6b4a6d6b6f74add9f5c329fd13 (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
use sequoia_openpgp as openpgp;
use openpgp::packet;
use openpgp::cert::{
    CertBuilder,
    CipherSuite,
};
use openpgp::types::{
    KeyFlags,
};

use super::{
    Autocrypt,
};

/// Generates a key compliant to
/// [Autocrypt](https://autocrypt.org/).
///
/// If no version is given the latest one is used.
///
/// The autocrypt specification requires a UserID.  However,
/// because it can be useful to add the UserID later, it is
/// permitted to be none.
pub fn cert_builder<'a, V, U>(version: V, userid: Option<U>)
                              -> CertBuilder
    where V: Into<Option<Autocrypt>>,
          U: Into<packet::UserID>
{
    let builder = CertBuilder::new()
        .set_cipher_suite(match version.into().unwrap_or_default() {
            Autocrypt::V1 => CipherSuite::RSA3k,
            Autocrypt::V1_1 => CipherSuite::Cv25519,
        })
        .set_primary_key_flags(
            KeyFlags::default()
                .set_certification(true)
                .set_signing(true))
        .add_subkey(
            KeyFlags::default()
                .set_transport_encryption(true)
                .set_storage_encryption(true),
            None,
            None);

    if let Some(userid) = userid {
        builder.add_userid(userid.into())
    } else {
        builder
    }
}


#[cfg(test)]
mod tests {
    use super::*;
    use openpgp::types::PublicKeyAlgorithm;

    #[test]
    fn autocrypt_v1() {
        let (cert1, _) = cert_builder(Autocrypt::V1, Some("Foo"))
            .generate().unwrap();
        assert_eq!(cert1.primary_key().pk_algo(),
                   PublicKeyAlgorithm::RSAEncryptSign);
        assert_eq!(cert1.keys().subkeys().next().unwrap().key().pk_algo(),
                   PublicKeyAlgorithm::RSAEncryptSign);
        assert_eq!(cert1.userids().count(), 1);
    }

    #[test]
    fn autocrypt_v1_1() {
        let (cert1, _) = cert_builder(Autocrypt::V1_1, Some("Foo"))
            .generate().unwrap();
        assert_eq!(cert1.primary_key().pk_algo(),
                   PublicKeyAlgorithm::EdDSA);
        assert_eq!(cert1.keys().subkeys().next().unwrap().key().pk_algo(),
                   PublicKeyAlgorithm::ECDH);
        match cert1.keys().subkeys().next().unwrap().key().mpis() {
            openpgp::crypto::mpis::PublicKey::ECDH {
                curve: openpgp::types::Curve::Cv25519, ..
            } => (),
            m => panic!("unexpected mpi: {:?}", m),
        }
        assert_eq!(cert1.userids().count(), 1);
    }
}