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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
use ed25519_dalek::Signer;
use hmac::Hmac;
use sha2::{Digest, Sha256};

pub const VERSION: u64 = 0;

#[derive(Debug, Error)]
pub enum KeyError {
    #[error("Base 58 decoding error")]
    Encoding(#[from] bs58::decode::Error),
    #[error(transparent)]
    Dalek(#[from] ed25519_dalek::ed25519::Error),
    #[error("No password supplied")]
    NoPassword,
    #[error("The key expired")]
    Expired,
}

#[derive(Serialize, Deserialize)]
pub struct SecretKey {
    pub version: u64,
    pub algorithm: Algorithm,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires: Option<chrono::DateTime<chrono::Utc>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub encryption: Option<Encryption>,
    pub key: String,
}

pub enum SKey {
    Ed25519 {
        key: ed25519_dalek::Keypair,
        expires: Option<chrono::DateTime<chrono::Utc>>,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PublicKey {
    pub version: u64,
    pub algorithm: Algorithm,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires: Option<chrono::DateTime<chrono::Utc>>,
    pub signature: String,
    pub key: String,
}

#[derive(Debug)]
pub enum PKey {
    Ed25519 {
        expires: Option<chrono::DateTime<chrono::Utc>>,
        signature: String,
        key: ed25519_dalek::PublicKey,
    },
}

#[test]
fn sign_public_key() {
    use chrono::Datelike;
    let expires = chrono::Utc::now();
    let expires = expires.with_year(expires.year() + 1).unwrap();
    let sk = SKey::generate(Some(expires));
    let pk = sk.public_key();
    println!("{:?}", pk);
    let pk = pk.load().unwrap();
    println!("{:?}", pk);
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Signature {
    pub version: u64,
    pub key: PublicKey,
    pub signature: String,
    pub date: chrono::DateTime<chrono::Utc>,
}

impl SKey {
    pub fn sign(&self, h: &[u8]) -> Result<Signature, KeyError> {
        Ok(Signature {
            version: VERSION,
            signature: self.sign_raw(h)?,
            key: self.public_key(),
            date: chrono::Utc::now(),
        })
    }

    pub fn sign_raw(&self, h: &[u8]) -> Result<String, KeyError> {
        match self {
            SKey::Ed25519 { key, expires } => {
                if let Some(expires) = expires {
                    if expires <= &chrono::Utc::now() {
                        return Err(KeyError::Expired);
                    }
                }
                let sig = key.sign(&h);
                Ok(bs58::encode(&sig.to_bytes()).into_string())
            }
        }
    }

    pub fn generate(expires: Option<chrono::DateTime<chrono::Utc>>) -> Self {
        use rand::RngCore;
        let mut key = [0; 32];
        rand::thread_rng().fill_bytes(&mut key);
        let secret = ed25519_dalek::SecretKey::from_bytes(&key).unwrap();
        SKey::Ed25519 {
            key: ed25519_dalek::Keypair {
                public: (&secret).into(),
                secret,
            },
            expires,
        }
    }

    pub fn save(&self, password: Option<&str>) -> SecretKey {
        match self {
            SKey::Ed25519 { key, expires } => {
                let mut key = key.to_bytes();
                let encryption = if let Some(password) = password {
                    use rand::Rng;
                    let salt = rand::thread_rng()
                        .sample_iter(&rand::distributions::Alphanumeric)
                        .take(32)
                        .collect();
                    let enc = Encryption::Aes128(Kdf::Pbkdf2 { salt });
                    enc.encrypt(password.as_bytes(), &mut key);
                    Some(enc)
                } else {
                    None
                };
                SecretKey {
                    version: VERSION,
                    algorithm: Algorithm::Ed25519,
                    expires: expires.clone(),
                    encryption,
                    key: bs58::encode(&key).into_string(),
                }
            }
        }
    }

    pub fn public_key(&self) -> PublicKey {
        match self {
            SKey::Ed25519 { key, expires } => {
                let to_sign =
                    bincode::serialize(&(Algorithm::Ed25519, expires.clone(), key.public)).unwrap();
                debug!("to_sign {:?}", to_sign);
                let sig = key.sign(&to_sign);
                PublicKey {
                    version: VERSION,
                    algorithm: Algorithm::Ed25519,
                    expires: expires.clone(),
                    key: bs58::encode(&key.public.clone().to_bytes()).into_string(),
                    signature: bs58::encode(&sig.to_bytes()).into_string(),
                }
            }
        }
    }

    pub fn pkey(&self) -> PKey {
        match self {
            SKey::Ed25519 { key, expires } => {
                let to_sign =
                    bincode::serialize(&(Algorithm::Ed25519, expires.clone(), key.public)).unwrap();
                debug!("to_sign {:?}", to_sign);
                let sig = key.sign(&to_sign);
                PKey::Ed25519 {
                    expires: expires.clone(),
                    key: key.public.clone(),
                    signature: bs58::encode(&sig.to_bytes()).into_string(),
                }
            }
        }
    }
}

impl SecretKey {
    pub fn load(&self, pw: Option<&str>) -> Result<SKey, KeyError> {
        if let Some(expires) = self.expires {
            if expires <= chrono::Utc::now() {
                return Err(KeyError::Expired);
            }
        }
        match self.algorithm {
            Algorithm::Ed25519 => {
                let mut key_enc = [0; 64];
                bs58::decode(self.key.as_bytes()).into(&mut key_enc)?;
                if let Some(ref enc) = self.encryption {
                    let password = if let Some(ref pw) = pw {
                        pw
                    } else {
                        return Err(KeyError::NoPassword);
                    };
                    enc.decrypt(password.as_bytes(), &mut key_enc);
                }
                Ok(SKey::Ed25519 {
                    key: ed25519_dalek::Keypair::from_bytes(&key_enc)?,
                    expires: self.expires,
                })
            }
        }
    }
}

impl PublicKey {
    pub fn fingerprint(&self) -> String {
        match self.algorithm {
            Algorithm::Ed25519 => {
                let signed =
                    bincode::serialize(&(Algorithm::Ed25519, self.expires.clone(), &self.key))
                        .unwrap();
                let mut hash = ed25519_dalek::Sha512::new();
                hash.update(&signed);
                bs58::encode(&hash.finalize()).into_string()
            }
        }
    }

    pub fn load(&self) -> Result<PKey, KeyError> {
        match self.algorithm {
            Algorithm::Ed25519 => {
                let mut key = [0; 32];
                bs58::decode(self.key.as_bytes()).into(&mut key)?;
                let key = ed25519_dalek::PublicKey::from_bytes(&key)?;
                let mut signature = [0; 64];
                bs58::decode(self.signature.as_bytes()).into(&mut signature)?;
                let signature = ed25519_dalek::Signature::new(signature);

                let msg =
                    bincode::serialize(&(Algorithm::Ed25519, self.expires.clone(), &key)).unwrap();
                key.verify_strict(&msg, &signature)?;
                Ok(PKey::Ed25519 {
                    signature: self.signature.clone(),
                    expires: self.expires.clone(),
                    key,
                })
            }
        }
    }
}

impl PKey {
    pub fn save(&self) -> PublicKey {
        match self {
            PKey::Ed25519 {
                key,
                expires,
                signature,
            } => PublicKey {
                version: VERSION,
                algorithm: Algorithm::Ed25519,
                expires: expires.clone(),
                signature: signature.clone(),
                key: bs58::encode(key.as_bytes()).into_string(),
            },
        }
    }

    pub fn verify(
        &self,
        h: &[u8],
        signature: &str,
        date: &chrono::DateTime<chrono::Utc>,
    ) -> Result<(), KeyError> {
        match self {
            PKey::Ed25519 { key, expires, .. } => {
                if let Some(expires) = expires {
                    if expires <= date {
                        return Err(KeyError::Expired);
                    }
                }
                let mut sig = [0; 64];
                bs58::decode(signature.as_bytes()).into(&mut sig)?;
                let sig = ed25519_dalek::Signature::new(sig);
                key.verify_strict(&h, &sig)?;
                Ok(())
            }
        }
    }
}

#[test]
fn verify_test() {
    use chrono::Datelike;
    let expires = chrono::Utc::now();
    let expires = expires.with_year(expires.year() + 1).unwrap();
    let sk = SKey::generate(Some(expires));
    let m = b"blabla";
    let signature = sk.sign(m).unwrap();
    signature.verify(m).unwrap();
}

impl Signature {
    pub fn verify(&self, h: &[u8]) -> Result<(), KeyError> {
        self.key.load()?.verify(h, &self.signature, &self.date)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[repr(u8)]
pub enum Algorithm {
    Ed25519,
}

impl From<u8> for Algorithm {
    fn from(u: u8) -> Self {
        assert_eq!(u, 0);
        Algorithm::Ed25519
    }
}
impl From<Algorithm> for u8 {
    fn from(u: Algorithm) -> Self {
        match u {
            Algorithm::Ed25519 => 0,
        }
    }
}

#[derive(Serialize, Deserialize)]
pub enum Encryption {
    Aes128(Kdf),
}

#[derive(Serialize, Deserialize)]
pub enum Kdf {
    Pbkdf2 { salt: String },
}

impl Encryption {
    pub fn encrypt<'a>(&self, password: &[u8], bytes: &'a mut [u8]) {
        match self {
            Encryption::Aes128(Kdf::Pbkdf2 { ref salt }) => {
                let mut kdf = [0; 32];
                pbkdf2::pbkdf2::<Hmac<Sha256>>(password, salt.as_ref(), 10_000, &mut kdf);
                use aes::{
                    cipher::FromBlockCipher, cipher::StreamCipher, Aes128, Aes128Ctr,
                    NewBlockCipher,
                };
                let (a, b) = kdf.split_at(16);
                let cipher = Aes128::new(generic_array::GenericArray::from_slice(&a));
                let mut cipher = Aes128Ctr::from_block_cipher(
                    cipher,
                    generic_array::GenericArray::from_slice(b),
                );
                cipher.apply_keystream(bytes);
            }
        }
    }
    pub fn decrypt<'a>(&self, password: &[u8], bytes: &'a mut [u8]) {
        self.encrypt(password, bytes)
    }
}

#[test]
fn encrypt_decrypt() {
    let enc = Encryption::Aes128(Kdf::Pbkdf2 {
        salt: "blabla".to_string(),
    });
    let b0 = b"very confidential secret".to_vec();
    let mut b = b0.clone();
    enc.encrypt(b"password", &mut b[..]);
    println!("{:?}", b);
    enc.decrypt(b"password", &mut b[..]);
    println!("{:?}", b);
    assert_eq!(b, b0);
}

#[derive(Clone, Copy)]
pub struct SerializedKey {
    pub(crate) t: u8,
    k: K,
}

impl From<ed25519_dalek::PublicKey> for SerializedKey {
    fn from(k: ed25519_dalek::PublicKey) -> Self {
        SerializedKey {
            t: 0,
            k: K {
                ed25519: k.as_bytes().clone(),
            },
        }
    }
}

impl From<SerializedKey> for ed25519_dalek::PublicKey {
    fn from(k: SerializedKey) -> Self {
        assert_eq!(k.t, 0);
        unsafe { ed25519_dalek::PublicKey::from_bytes(&k.k.ed25519).unwrap() }
    }
}

#[derive(Clone, Copy)]
pub(crate) union K {
    ed25519: [u8; 32],
}