summary refs log tree commit diff
path: root/src/lib.rs
blob: 5e2affed2dc3b812e6616a27db98fe26d530b584 (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
use aho_corasick::{AhoCorasick, MatchKind};
use crc::{CRC_4_G_704, Crc};
use ed25519_dalek::{
    SecretKey, Signature, SigningKey, VerifyingKey, ed25519::signature::SignerMut,
};
use include_lines::static_include_lines;
use rand_chacha::{
    ChaCha12Rng,
    rand_core::{RngCore, SeedableRng},
};
use serde::{Deserialize, Serialize};
use sha3::{Digest, Sha3_256};

const CHECKSUM: Crc<u8> = Crc::<u8>::new(&CRC_4_G_704);
static_include_lines!(DICTIONARY, "src/orchard-street-medium.txt");

/// A signature verifying an arbitrary message
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Certificate {
    pub key: VerifyingKey,
    pub sig: Signature,
}

impl Certificate {
    /// Verify a message against this certificate
    pub fn verify(&self, message: &[u8]) -> Result<(), ed25519_dalek::SignatureError> {
        self.key.verify_strict(message, &self.sig)
    }
}

/// Errors that may occur during sealed key decoding
#[derive(Clone, Debug)]
pub enum DecodeError {
    WrongLength,
    CrcMismatch,
}

/// A secret key, XOR'd with a hashed password as last-resort security
#[derive(Serialize, Deserialize)]
pub struct SealedKey([u8; 32]);

impl SealedKey {
    /// Seal a raw secret key with a given passphrase
    pub fn seal(mut key: SecretKey, passphrase: impl AsRef<str>) -> Self {
        // Initialize crypto
        let mut hasher = Sha3_256::new();

        // Hash passphrase
        hasher.update(passphrase.as_ref());
        let hash = hasher.finalize();

        // XOR with passphrase hash
        for (k, h) in key.iter_mut().zip(hash) {
            *k ^= h;
        }

        Self(key)
    }

    /// Unseal into a raw secret key with a given passphrase
    ///
    /// No checks are done on if the passphrase was valid or not.
    pub fn unseal(&self, passphrase: impl AsRef<str>) -> SecretKey {
        // Initialize crypto
        let mut hasher = Sha3_256::new();

        // Hash passphrase
        hasher.update(passphrase.as_ref());
        let hash = hasher.finalize();

        // XOR with passphrase hash
        let mut key = self.0.clone();
        for (k, h) in key.iter_mut().zip(hash) {
            *k ^= h;
        }

        key
    }

    /// Encode the key into a list of words suitable for writing down and storing securely
    fn encode(&self) -> [&'static str; 20] {
        // Compute CRC
        let checksum = CHECKSUM.checksum(&self.0);

        // Break into 13-bit indices
        let mut indices = [0usize; 20];
        for (i, byte) in self.0.iter().enumerate() {
            let bit = i * 8;
            let idx = bit / 13;
            let shift = (bit as isize) % 13 - 4;

            if shift <= 0 {
                indices[idx] |= (*byte as usize) << -shift;
            } else {
                indices[idx] |= (*byte as usize) >> shift;
                indices[idx + 1] |= ((*byte as usize) << (13 - shift)) & 0x1fff;
            }
        }
        indices[19] |= checksum as usize;

        indices.map(|i| DICTIONARY[i])
    }

    pub fn decode(input: impl AsRef<str>) -> Result<Self, DecodeError> {
        // Strip any non-alphabetic characters
        let alpha = input
            .as_ref()
            .chars()
            .filter(|c| c.is_alphabetic())
            .collect::<String>();

        // Construct Aho-Corasick automaton
        // TODO See if this can be done at compile time
        let ac = AhoCorasick::builder()
            .match_kind(MatchKind::LeftmostLongest)
            .ascii_case_insensitive(true)
            .build(DICTIONARY)
            .unwrap();

        // Stream decode the input
        let indices = ac
            .find_iter(&alpha)
            .map(|m| m.pattern().as_usize())
            .collect::<Vec<_>>();

        // Check length
        if indices.len() != 20 {
            return Err(DecodeError::WrongLength);
        }

        unimplemented!();
    }
}

/// A public/sealed-secret keypair capable of producing certificates
#[derive(Serialize, Deserialize)]
pub struct Keypair {
    public: VerifyingKey,
    secret: SealedKey,
}

impl Keypair {
    /// Create a new random keypair with a passphrase
    pub fn new(passphrase: impl AsRef<str>) -> Self {
        // Initalize crypto
        let mut rng = ChaCha12Rng::from_os_rng();

        // Generate secret key
        let mut unsealed = SecretKey::default();
        rng.fill_bytes(&mut unsealed);

        // Derive public key
        let public = SigningKey::from_bytes(&unsealed).verifying_key();

        // Seal secret key
        let secret = SealedKey::seal(unsealed, passphrase);

        Self { public, secret }
    }

    /// Sign a message with this keypair
    pub fn sign(&self, passphrase: impl AsRef<str>, message: &[u8]) -> Certificate {
        // Unseal secret key
        let unsealed = self.secret.unseal(passphrase);

        // Sign message
        let mut signer = SigningKey::from_bytes(&unsealed);
        let signature = signer.sign(message);

        Certificate {
            key: self.public.clone(),
            sig: signature,
        }
    }

    /// Sign this keypair's public key with itself
    pub fn self_sign(&self, passphrase: impl AsRef<str>) -> Certificate {
        self.sign(passphrase, self.public.as_bytes())
    }

    /// Encode the secret key into a list of words suitable for writing down and storing securely
    pub fn encode_secret(&self) -> [&'static str; 20] {
        self.secret.encode()
    }

    pub fn from_encoded(
        encoded: impl AsRef<str>,
        passphrase: impl AsRef<str>,
    ) -> Result<Self, DecodeError> {
        let sealed = SealedKey::decode(encoded)?;
        let unsealed = sealed.unseal(passphrase);

        Ok(Self {
            public: SigningKey::from_bytes(&unsealed).verifying_key(),
            secret: sealed,
        })
    }
}