ssb_crypto/dalek/
sign.rs

1use crate::{Keypair, PublicKey, SecretKey, Signature};
2use dalek::{Signer, Verifier};
3use ed25519_dalek as dalek;
4use rand::{CryptoRng, RngCore};
5
6impl Into<dalek::Keypair> for &Keypair {
7    fn into(self) -> dalek::Keypair {
8        dalek::Keypair {
9            secret: dalek::SecretKey::from_bytes(&self.secret.0).unwrap(),
10            public: dalek::PublicKey::from_bytes(&self.public.0).unwrap(),
11        }
12    }
13}
14
15impl Into<Keypair> for dalek::Keypair {
16    fn into(self) -> Keypair {
17        Keypair {
18            secret: SecretKey(self.secret.to_bytes()),
19            public: PublicKey(self.public.to_bytes()),
20        }
21    }
22}
23
24#[cfg(feature = "getrandom")]
25pub fn generate_keypair() -> Keypair {
26    dalek::Keypair::generate(&mut rand::rngs::OsRng {}).into()
27}
28
29pub fn generate_keypair_with_rng<R>(r: &mut R) -> Keypair
30where
31    R: CryptoRng + RngCore,
32{
33    dalek::Keypair::generate(r).into()
34}
35
36pub fn keypair_from_seed(seed: &[u8]) -> Option<Keypair> {
37    let s = dalek::SecretKey::from_bytes(seed).ok()?;
38    let p = dalek::PublicKey::from(&s);
39
40    Some(Keypair {
41        public: PublicKey(p.to_bytes()),
42        secret: SecretKey(s.to_bytes()),
43    })
44}
45
46pub fn sign(k: &Keypair, b: &[u8]) -> Signature {
47    let kp: dalek::Keypair = k.into();
48    Signature(kp.sign(b).to_bytes())
49}
50
51pub fn verify(k: &PublicKey, s: &Signature, b: &[u8]) -> bool {
52    let sig = dalek::Signature::new(s.0);
53    let pk = dalek::PublicKey::from_bytes(&k.0).unwrap();
54    pk.verify(b, &sig).is_ok()
55}