cc984bd31a22c6c20a395b7bcf680ce1e912b4d5
[platform/upstream/nettle.git] / dsa-verify.c
1 /* dsa-verify.c
2
3    The DSA publickey algorithm.
4
5    Copyright (C) 2002, 2003 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 <stdlib.h>
39
40 #include "dsa.h"
41
42 #include "bignum.h"
43
44 int
45 dsa_verify(const struct dsa_params *params,
46            const mpz_t y,
47            size_t digest_size,
48            const uint8_t *digest,
49            const struct dsa_signature *signature)
50 {
51   mpz_t w;
52   mpz_t tmp;
53   mpz_t v;
54
55   int res;
56
57   /* Check that r and s are in the proper range */
58   if (mpz_sgn(signature->r) <= 0 || mpz_cmp(signature->r, params->q) >= 0)
59     return 0;
60
61   if (mpz_sgn(signature->s) <= 0 || mpz_cmp(signature->s, params->q) >= 0)
62     return 0;
63
64   mpz_init(w);
65
66   /* Compute w = s^-1 (mod q) */
67
68   /* NOTE: In gmp-2, mpz_invert sometimes generates negative inverses,
69    * so we need gmp-3 or better. */
70   if (!mpz_invert(w, signature->s, params->q))
71     {
72       mpz_clear(w);
73       return 0;
74     }
75
76   mpz_init(tmp);
77   mpz_init(v);
78
79   /* The message digest */
80   _dsa_hash (tmp, mpz_sizeinbase (params->q, 2), digest_size, digest);
81   
82   /* v = g^{w * h (mod q)} (mod p)  */
83   mpz_mul(tmp, tmp, w);
84   mpz_fdiv_r(tmp, tmp, params->q);
85
86   mpz_powm(v, params->g, tmp, params->p);
87
88   /* y^{w * r (mod q) } (mod p) */
89   mpz_mul(tmp, signature->r, w);
90   mpz_fdiv_r(tmp, tmp, params->q);
91
92   mpz_powm(tmp, y, tmp, params->p);
93
94   /* v = (g^{w * h} * y^{w * r} (mod p) ) (mod q) */
95   mpz_mul(v, v, tmp);
96   mpz_fdiv_r(v, v, params->p);
97
98   mpz_fdiv_r(v, v, params->q);
99
100   res = !mpz_cmp(v, signature->r);
101
102   mpz_clear(w);
103   mpz_clear(tmp);
104   mpz_clear(v);
105
106   return res;
107 }