updated makefiles
[gnutls.git] / lib / nettle / ecc_sign_hash.c
blobbd78da0441d45ecc19b72a2101e9f873a2e4486f
1 /*
2 * Copyright (C) 2011-2012 Free Software Foundation, Inc.
4 * This file is part of GNUTLS.
6 * The GNUTLS library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public License
8 * as published by the Free Software Foundation; either version 3 of
9 * the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>
21 /* Based on public domain code of LibTomCrypt by Tom St Denis.
22 * Adapted to gmp and nettle by Nikos Mavrogiannopoulos.
25 #include "ecc.h"
26 #include <nettle/dsa.h>
29 @file ecc_sign_hash.c
30 ECC Crypto, Tom St Denis
34 Sign a message digest
35 @param in The message digest to sign
36 @param inlen The length of the digest
37 @param sign The destination for the signature
38 @param prng An active PRNG state
39 @param wprng The index of the PRNG you wish to use
40 @param key A private ECC key
41 @return 0 if successful
43 int
44 ecc_sign_hash (const unsigned char *in, unsigned long inlen,
45 struct dsa_signature *sig,
46 void *random_ctx, nettle_random_func random, ecc_key * key)
48 ecc_key pubkey;
49 mpz_t e;
50 int err;
52 if (in == NULL || sig == NULL || key == NULL)
53 return -1;
55 /* is this a private key? */
56 if (key->type != PK_PRIVATE)
58 return -1;
61 /* get the hash and load it as a bignum into 'e' */
62 /* init the bignums */
63 if ((err = mp_init_multi (&e, NULL)) != 0)
65 return err;
68 nettle_mpz_set_str_256_u (e, inlen, in);
70 /* make up a key and export the public copy */
71 for (;;)
73 if ((err =
74 ecc_make_key_ex (random_ctx, random, &pubkey, key->prime,
75 key->order, key->A, key->B, key->Gx, key->Gy, 1)) != 0)
77 goto errnokey;
80 /* find r = x1 mod n */
81 mpz_mod (sig->r, pubkey.pubkey.x, pubkey.order);
83 if (mpz_cmp_ui (sig->r, 0) == 0)
85 ecc_free (&pubkey);
87 else
89 /* find s = (e + xr)/k */
90 mpz_invert (pubkey.k, pubkey.k, pubkey.order);
92 /* mulmod */
93 mpz_mul (sig->s, key->k, sig->r);
94 mpz_mod (sig->s, sig->s, pubkey.order);
95 mpz_add (sig->s, e, sig->s);
96 mpz_mod (sig->s, sig->s, pubkey.order);
98 mpz_mul (sig->s, sig->s, pubkey.k);
99 mpz_mod (sig->s, sig->s, pubkey.order);
100 ecc_free (&pubkey);
101 if (mpz_cmp_ui (sig->s, 0) != 0)
103 break;
108 errnokey:
109 mp_clear_multi (&e, NULL);
110 return err;
113 /* $Source: /cvs/libtom/libtomcrypt/src/pk/ecc/ecc_sign_hash.c,v $ */
114 /* $Revision: 1.11 $ */
115 /* $Date: 2007/05/12 14:32:35 $ */