Revert "Merge branch 'upstream' into tizen"
[platform/upstream/nettle.git] / dsa-verify.c
1 /* dsa-verify.c
2  *
3  * The DSA publickey algorithm.
4  */
5
6 /* nettle, low-level cryptographics library
7  *
8  * Copyright (C) 2002, 2003 Niels Möller
9  *  
10  * The nettle library is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU Lesser General Public License as published by
12  * the Free Software Foundation; either version 2.1 of the License, or (at your
13  * option) any later version.
14  * 
15  * The nettle library is distributed in the hope that it will be useful, but
16  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
17  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
18  * License for more details.
19  * 
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with the nettle library; see the file COPYING.LIB.  If not, write to
22  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
23  * MA 02111-1301, USA.
24  */
25
26 #if HAVE_CONFIG_H
27 # include "config.h"
28 #endif
29
30 #include <stdlib.h>
31
32 #include "dsa.h"
33
34 #include "bignum.h"
35
36 int
37 _dsa_verify(const struct dsa_public_key *key,
38             unsigned digest_size,
39             const uint8_t *digest,
40             const struct dsa_signature *signature)
41 {
42   mpz_t w;
43   mpz_t tmp;
44   mpz_t v;
45
46   int res;
47
48   if (mpz_sizeinbase(key->q, 2) != 8 * digest_size)
49     return 0;
50
51   /* Check that r and s are in the proper range */
52   if (mpz_sgn(signature->r) <= 0 || mpz_cmp(signature->r, key->q) >= 0)
53     return 0;
54
55   if (mpz_sgn(signature->s) <= 0 || mpz_cmp(signature->s, key->q) >= 0)
56     return 0;
57
58   mpz_init(w);
59
60   /* Compute w = s^-1 (mod q) */
61
62   /* NOTE: In gmp-2, mpz_invert sometimes generates negative inverses,
63    * so we need gmp-3 or better. */
64   if (!mpz_invert(w, signature->s, key->q))
65     {
66       mpz_clear(w);
67       return 0;
68     }
69
70   mpz_init(tmp);
71   mpz_init(v);
72
73   /* The message digest */
74   nettle_mpz_set_str_256_u(tmp, digest_size, digest);
75   
76   /* v = g^{w * h (mod q)} (mod p)  */
77   mpz_mul(tmp, tmp, w);
78   mpz_fdiv_r(tmp, tmp, key->q);
79
80   mpz_powm(v, key->g, tmp, key->p);
81
82   /* y^{w * r (mod q) } (mod p) */
83   mpz_mul(tmp, signature->r, w);
84   mpz_fdiv_r(tmp, tmp, key->q);
85
86   mpz_powm(tmp, key->y, tmp, key->p);
87
88   /* v = (g^{w * h} * y^{w * r} (mod p) ) (mod q) */
89   mpz_mul(v, v, tmp);
90   mpz_fdiv_r(v, v, key->p);
91
92   mpz_fdiv_r(v, v, key->q);
93
94   res = !mpz_cmp(v, signature->r);
95
96   mpz_clear(w);
97   mpz_clear(tmp);
98   mpz_clear(v);
99
100   return res;
101 }