3 * The DSA publickey algorithm.
6 /* nettle, low-level cryptographics library
8 * Copyright (C) 2002, 2010 Niels Möller
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.
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.
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,
39 _dsa_sign(const struct dsa_public_key *pub,
40 const struct dsa_private_key *key,
41 void *random_ctx, nettle_random_func *random,
43 const uint8_t *digest,
44 struct dsa_signature *signature)
50 /* Require precise match of bitsize of q and hash size. The general
51 description of DSA in FIPS186-3 allows both larger and smaller q;
52 in the the latter case, the hash must be truncated to the right
54 if (mpz_sizeinbase(pub->q, 2) != 8 * digest_size)
57 /* Select k, 0<k<q, randomly */
58 mpz_init_set(tmp, pub->q);
59 mpz_sub_ui(tmp, tmp, 1);
62 nettle_mpz_random(k, random_ctx, random, tmp);
65 /* Compute r = (g^k (mod p)) (mod q) */
66 mpz_powm(tmp, pub->g, k, pub->p);
67 mpz_fdiv_r(signature->r, tmp, pub->q);
71 nettle_mpz_set_str_256_u(h, digest_size, digest);
73 /* Compute k^-1 (mod q) */
74 if (!mpz_invert(k, k, pub->q))
75 /* What do we do now? The key is invalid. */
78 /* Compute signature s = k^-1 (h + xr) (mod q) */
79 mpz_mul(tmp, signature->r, key->x);
80 mpz_fdiv_r(tmp, tmp, pub->q);
83 mpz_fdiv_r(signature->s, tmp, pub->q);