rsa-compute-root-test: Fix qsize. Try more keys.
[gd/nettle] / dsa-sign.c
1 /* dsa-sign.c
2
3    The DSA publickey algorithm.
4
5    Copyright (C) 2002, 2010 Niels Möller
6
7    This file is part of GNU Nettle.
8
9    GNU Nettle is free software: you can redistribute it and/or
10    modify it under the terms of either:
11
12      * the GNU Lesser General Public License as published by the Free
13        Software Foundation; either version 3 of the License, or (at your
14        option) any later version.
15
16    or
17
18      * the GNU General Public License as published by the Free
19        Software Foundation; either version 2 of the License, or (at your
20        option) any later version.
21
22    or both in parallel, as here.
23
24    GNU Nettle is distributed in the hope that it will be useful,
25    but WITHOUT ANY WARRANTY; without even the implied warranty of
26    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
27    General Public License for more details.
28
29    You should have received copies of the GNU General Public License and
30    the GNU Lesser General Public License along with this program.  If
31    not, see http://www.gnu.org/licenses/.
32 */
33
34 #if HAVE_CONFIG_H
35 # include "config.h"
36 #endif
37
38 #include <assert.h>
39 #include <stdlib.h>
40
41 #include "dsa.h"
42
43 #include "bignum.h"
44
45
46 int
47 dsa_sign(const struct dsa_params *params,
48          const mpz_t x,
49          void *random_ctx, nettle_random_func *random,
50          size_t digest_size,
51          const uint8_t *digest,
52          struct dsa_signature *signature)
53 {
54   mpz_t k;
55   mpz_t h;
56   mpz_t tmp;
57   int res;
58   
59   /* Check that p is odd, so that invalid keys don't result in a crash
60      inside mpz_powm_sec. */
61   if (mpz_even_p (params->p))
62     return 0;
63
64   /* Select k, 0<k<q, randomly */
65   mpz_init_set(tmp, params->q);
66   mpz_sub_ui(tmp, tmp, 1);
67
68   mpz_init(k);
69   nettle_mpz_random(k, random_ctx, random, tmp);
70   mpz_add_ui(k, k, 1);
71
72   /* Compute r = (g^k (mod p)) (mod q) */
73   mpz_powm_sec(tmp, params->g, k, params->p);
74   mpz_fdiv_r(signature->r, tmp, params->q);
75
76   /* Compute hash */
77   mpz_init(h);
78   _dsa_hash (h, mpz_sizeinbase(params->q, 2), digest_size, digest);
79
80   /* Compute k^-1 (mod q) */
81   if (mpz_invert(k, k, params->q))
82     {
83       /* Compute signature s = k^-1 (h + xr) (mod q) */
84       mpz_mul(tmp, signature->r, x);
85       mpz_fdiv_r(tmp, tmp, params->q);
86       mpz_add(tmp, tmp, h);
87       mpz_mul(tmp, tmp, k);
88       mpz_fdiv_r(signature->s, tmp, params->q);
89       res = 1;
90     }
91   else
92     /* What do we do now? The key is invalid. */
93     res = 0;
94
95   mpz_clear(k);
96   mpz_clear(h);
97   mpz_clear(tmp);
98
99   return res;
100 }