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
use nettle_sys::{
    __gmpz_clear, __gmpz_init, __gmpz_init_set, mpz_t,
    nettle_dsa_generate_keypair,
};
use std::mem::zeroed;

use crate::helper::{convert_buffer_to_gmpz, convert_gmpz_to_buffer};
use crate::random::Random;

use super::Params;

/// Public DSA key.
pub struct PublicKey {
    pub(crate) public: mpz_t,
}

impl PublicKey {
    /// Creates a new public key.
    pub fn new(y: &[u8]) -> PublicKey {
        PublicKey { public: [convert_buffer_to_gmpz(y)] }
    }

    /// Returns the public key `y` as big endian number.
    pub fn as_bytes(&self) -> Box<[u8]> {
        convert_gmpz_to_buffer(self.public[0])
    }
}

impl Clone for PublicKey {
    fn clone(&self) -> Self {
        unsafe {
            let mut ret: mpz_t = zeroed();

            __gmpz_init_set(&mut ret[0], &self.public[0]);
            PublicKey { public: ret }
        }
    }
}

impl Drop for PublicKey {
    fn drop(&mut self) {
        unsafe {
            __gmpz_clear(&mut self.public[0] as *mut _);
        }
    }
}

/// Private DSA key.
pub struct PrivateKey {
    pub(crate) private: mpz_t,
}

impl PrivateKey {
    /// Creates a new private key sructure.
    ///
    /// The secret exponent `x` must be a big endian integer.
    pub fn new(x: &[u8]) -> PrivateKey {
        PrivateKey { private: [convert_buffer_to_gmpz(x)] }
    }

    /// Returns the secret exponent `x` as bit endian integer.
    pub fn as_bytes(&self) -> Box<[u8]> {
        convert_gmpz_to_buffer(self.private[0])
    }
}

impl Clone for PrivateKey {
    fn clone(&self) -> Self {
        unsafe {
            let mut ret: mpz_t = zeroed();

            __gmpz_init_set(&mut ret[0], &self.private[0]);
            PrivateKey { private: ret }
        }
    }
}

impl Drop for PrivateKey {
    fn drop(&mut self) {
        unsafe {
            __gmpz_clear(&mut self.private[0] as *mut _);
        }
    }
}

/// Generates a fresh DSA key pair.
///
/// Generator and primes must be supplied via `params`. Entrophy is
/// gathered using `random`.
pub fn generate_keypair<R: Random>(
    params: &Params,
    random: &mut R,
) -> (PublicKey, PrivateKey) {
    unsafe {
        let mut public: mpz_t = zeroed();
        let mut private: mpz_t = zeroed();

        __gmpz_init(&mut public[0] as *mut _);
        __gmpz_init(&mut private[0] as *mut _);

        nettle_dsa_generate_keypair(
            &params.params,
            &mut public[0],
            &mut private[0],
            random.context(),
            Some(R::random_impl),
        );

        let ret_pub = PublicKey { public: public };
        let ret_key = PrivateKey { private: private };

        (ret_pub, ret_key)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dsa::{sign, verify, Params};
    use crate::random::Yarrow;

    #[test]
    fn generate_key() {
        let mut rand = Yarrow::default();
        let params = Params::generate(&mut rand, 1024, 160).unwrap();

        for _ in 0..3 {
            let _ = generate_keypair(&params, &mut rand);
        }
    }

    #[test]
    fn new_public_key() {
        let y = &['y' as u8; 12];
        let public = PublicKey::new(y);
        assert_eq!(public.as_bytes().as_ref(), y);
    }

    #[test]
    fn new_private_key() {
        let x = &['x' as u8; 12];
        let private = PrivateKey::new(x);
        assert_eq!(private.as_bytes().as_ref(), x);
    }

    #[test]
    fn clone() {
        let mut rand = Yarrow::default();
        let params = Params::generate(&mut rand, 1024, 160).unwrap();
        let (public, private) = generate_keypair(&params, &mut rand);

        let public = public.clone();
        let private = private.clone();
        let params = params.clone();
        let mut msg = [0u8; 160];

        rand.random(&mut msg);
        let sig = sign(&params, &private, &msg, &mut rand).unwrap();
        let sig = sig.clone();

        assert!(verify(&params, &public, &msg, &sig));
    }
}