ecdsa.c 11.9 KB
Newer Older
1 2 3
/*
 *  Elliptic curve DSA
 *
Manuel Pégourié-Gonnard's avatar
Manuel Pégourié-Gonnard committed
4
 *  Copyright (C) 2006-2014, ARM Limited, All Rights Reserved
5
 *
6
 *  This file is part of mbed TLS (https://tls.mbed.org)
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

/*
 * References:
 *
 * SEC1 http://www.secg.org/index.php?action=secg,docs_secg
 */

29
#if !defined(POLARSSL_CONFIG_FILE)
30
#include "mbedtls/config.h"
31 32 33
#else
#include POLARSSL_CONFIG_FILE
#endif
34 35 36

#if defined(POLARSSL_ECDSA_C)

37 38
#include "mbedtls/ecdsa.h"
#include "mbedtls/asn1write.h"
39

40 41
#include <string.h>

42
#if defined(POLARSSL_ECDSA_DETERMINISTIC)
43
#include "mbedtls/hmac_drbg.h"
44
#endif
45

46 47 48 49 50 51 52
/*
 * Derive a suitable integer for group grp from a buffer of length len
 * SEC1 4.1.3 step 5 aka SEC1 4.1.4 step 3
 */
static int derive_mpi( const ecp_group *grp, mpi *x,
                       const unsigned char *buf, size_t blen )
{
53
    int ret;
54
    size_t n_size = ( grp->nbits + 7 ) / 8;
55 56 57 58 59 60
    size_t use_size = blen > n_size ? n_size : blen;

    MPI_CHK( mpi_read_binary( x, buf, use_size ) );
    if( use_size * 8 > grp->nbits )
        MPI_CHK( mpi_shift_r( x, use_size * 8 - grp->nbits ) );

61 62 63 64
    /* While at it, reduce modulo N */
    if( mpi_cmp_mpi( x, &grp->N ) >= 0 )
        MPI_CHK( mpi_sub_mpi( x, x, &grp->N ) );

65 66
cleanup:
    return( ret );
67 68
}

69 70 71 72
/*
 * Compute ECDSA signature of a hashed message (SEC1 4.1.3)
 * Obviously, compared to SEC1 4.1.3, we skip step 4 (hash message)
 */
73
int ecdsa_sign( ecp_group *grp, mpi *r, mpi *s,
74 75 76
                const mpi *d, const unsigned char *buf, size_t blen,
                int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
{
77
    int ret, key_tries, sign_tries, blind_tries;
78
    ecp_point R;
79
    mpi k, e, t;
80

81 82 83 84
    /* Fail cleanly on curves such as Curve25519 that can't be used for ECDSA */
    if( grp->N.p == NULL )
        return( POLARSSL_ERR_ECP_BAD_INPUT_DATA );

85
    ecp_point_init( &R );
86
    mpi_init( &k ); mpi_init( &e ); mpi_init( &t );
87 88 89 90 91 92

    sign_tries = 0;
    do
    {
        /*
         * Steps 1-3: generate a suitable ephemeral keypair
93
         * and set r = xR mod n
94 95 96 97 98
         */
        key_tries = 0;
        do
        {
            MPI_CHK( ecp_gen_keypair( grp, &k, &R, f_rng, p_rng ) );
99
            MPI_CHK( mpi_mod_mpi( r, &R.X, &grp->N ) );
100 101

            if( key_tries++ > 10 )
102
            {
103
                ret = POLARSSL_ERR_ECP_RANDOM_FAILED;
104 105
                goto cleanup;
            }
106 107 108 109 110 111
        }
        while( mpi_cmp_int( r, 0 ) == 0 );

        /*
         * Step 5: derive MPI from hashed message
         */
112
        MPI_CHK( derive_mpi( grp, &e, buf, blen ) );
113 114

        /*
115 116 117 118 119 120
         * Generate a random value to blind inv_mod in next step,
         * avoiding a potential timing leak.
         */
        blind_tries = 0;
        do
        {
121
            size_t n_size = ( grp->nbits + 7 ) / 8;
122 123 124 125 126 127 128 129 130 131 132 133
            MPI_CHK( mpi_fill_random( &t, n_size, f_rng, p_rng ) );
            MPI_CHK( mpi_shift_r( &t, 8 * n_size - grp->nbits ) );

            /* See ecp_gen_keypair() */
            if( ++blind_tries > 30 )
                return( POLARSSL_ERR_ECP_RANDOM_FAILED );
        }
        while( mpi_cmp_int( &t, 1 ) < 0 ||
               mpi_cmp_mpi( &t, &grp->N ) >= 0 );

        /*
         * Step 6: compute s = (e + r * d) / k = t (e + rd) / (kt) mod n
134 135 136
         */
        MPI_CHK( mpi_mul_mpi( s, r, d ) );
        MPI_CHK( mpi_add_mpi( &e, &e, s ) );
137 138
        MPI_CHK( mpi_mul_mpi( &e, &e, &t ) );
        MPI_CHK( mpi_mul_mpi( &k, &k, &t ) );
139 140 141 142 143
        MPI_CHK( mpi_inv_mod( s, &k, &grp->N ) );
        MPI_CHK( mpi_mul_mpi( s, s, &e ) );
        MPI_CHK( mpi_mod_mpi( s, s, &grp->N ) );

        if( sign_tries++ > 10 )
144
        {
145
            ret = POLARSSL_ERR_ECP_RANDOM_FAILED;
146 147
            goto cleanup;
        }
148 149 150 151 152
    }
    while( mpi_cmp_int( s, 0 ) == 0 );

cleanup:
    ecp_point_free( &R );
153
    mpi_free( &k ); mpi_free( &e ); mpi_free( &t );
154 155 156

    return( ret );
}
157

158 159 160 161 162 163 164 165 166 167
#if defined(POLARSSL_ECDSA_DETERMINISTIC)
/*
 * Deterministic signature wrapper
 */
int ecdsa_sign_det( ecp_group *grp, mpi *r, mpi *s,
                    const mpi *d, const unsigned char *buf, size_t blen,
                    md_type_t md_alg )
{
    int ret;
    hmac_drbg_context rng_ctx;
168
    unsigned char data[2 * POLARSSL_ECP_MAX_BYTES];
169 170 171 172
    size_t grp_len = ( grp->nbits + 7 ) / 8;
    const md_info_t *md_info;
    mpi h;

173
    if( ( md_info = md_info_from_type( md_alg ) ) == NULL )
174 175 176 177 178
        return( POLARSSL_ERR_ECP_BAD_INPUT_DATA );

    mpi_init( &h );
    memset( &rng_ctx, 0, sizeof( hmac_drbg_context ) );

179 180
    /* Use private key and message hash (reduced) to initialize HMAC_DRBG */
    MPI_CHK( mpi_write_binary( d, data, grp_len ) );
181
    MPI_CHK( derive_mpi( grp, &h, buf, blen ) );
182
    MPI_CHK( mpi_write_binary( &h, data + grp_len, grp_len ) );
183
    hmac_drbg_init_buf( &rng_ctx, md_info, data, 2 * grp_len );
184 185 186 187 188 189 190 191 192 193

    ret = ecdsa_sign( grp, r, s, d, buf, blen,
                      hmac_drbg_random, &rng_ctx );

cleanup:
    hmac_drbg_free( &rng_ctx );
    mpi_free( &h );

    return( ret );
}
194 195
#endif /* POLARSSL_ECDSA_DETERMINISTIC */

196 197 198 199
/*
 * Verify ECDSA signature of hashed message (SEC1 4.1.4)
 * Obviously, compared to SEC1 4.1.3, we skip step 2 (hash message)
 */
200
int ecdsa_verify( ecp_group *grp,
201 202 203 204 205 206 207 208 209 210
                  const unsigned char *buf, size_t blen,
                  const ecp_point *Q, const mpi *r, const mpi *s)
{
    int ret;
    mpi e, s_inv, u1, u2;
    ecp_point R, P;

    ecp_point_init( &R ); ecp_point_init( &P );
    mpi_init( &e ); mpi_init( &s_inv ); mpi_init( &u1 ); mpi_init( &u2 );

211 212 213 214
    /* Fail cleanly on curves such as Curve25519 that can't be used for ECDSA */
    if( grp->N.p == NULL )
        return( POLARSSL_ERR_ECP_BAD_INPUT_DATA );

215 216 217 218 219 220
    /*
     * Step 1: make sure r and s are in range 1..n-1
     */
    if( mpi_cmp_int( r, 1 ) < 0 || mpi_cmp_mpi( r, &grp->N ) >= 0 ||
        mpi_cmp_int( s, 1 ) < 0 || mpi_cmp_mpi( s, &grp->N ) >= 0 )
    {
221
        ret = POLARSSL_ERR_ECP_VERIFY_FAILED;
222
        goto cleanup;
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
    }

    /*
     * Additional precaution: make sure Q is valid
     */
    MPI_CHK( ecp_check_pubkey( grp, Q ) );

    /*
     * Step 3: derive MPI from hashed message
     */
    MPI_CHK( derive_mpi( grp, &e, buf, blen ) );

    /*
     * Step 4: u1 = e / s mod n, u2 = r / s mod n
     */
    MPI_CHK( mpi_inv_mod( &s_inv, s, &grp->N ) );

    MPI_CHK( mpi_mul_mpi( &u1, &e, &s_inv ) );
    MPI_CHK( mpi_mod_mpi( &u1, &u1, &grp->N ) );

    MPI_CHK( mpi_mul_mpi( &u2, r, &s_inv ) );
    MPI_CHK( mpi_mod_mpi( &u2, &u2, &grp->N ) );

    /*
     * Step 5: R = u1 G + u2 Q
248 249 250
     *
     * Since we're not using any secret data, no need to pass a RNG to
     * ecp_mul() for countermesures.
251
     */
252 253
    MPI_CHK( ecp_mul( grp, &R, &u1, &grp->G, NULL, NULL ) );
    MPI_CHK( ecp_mul( grp, &P, &u2, Q, NULL, NULL ) );
254 255 256
    MPI_CHK( ecp_add( grp, &R, &R, &P ) );

    if( ecp_is_zero( &R ) )
257
    {
258
        ret = POLARSSL_ERR_ECP_VERIFY_FAILED;
259 260
        goto cleanup;
    }
261 262

    /*
263 264 265 266 267 268 269
     * Step 6: convert xR to an integer (no-op)
     * Step 7: reduce xR mod n (gives v)
     */
    MPI_CHK( mpi_mod_mpi( &R.X, &R.X, &grp->N ) );

    /*
     * Step 8: check if v (that is, R.X) is equal to r
270 271
     */
    if( mpi_cmp_mpi( &R.X, r ) != 0 )
272
    {
273
        ret = POLARSSL_ERR_ECP_VERIFY_FAILED;
274 275
        goto cleanup;
    }
276 277 278 279 280 281 282 283

cleanup:
    ecp_point_free( &R ); ecp_point_free( &P );
    mpi_free( &e ); mpi_free( &s_inv ); mpi_free( &u1 ); mpi_free( &u2 );

    return( ret );
}

284 285 286
/*
 * Convert a signature (given by context) to ASN.1
 */
287
static int ecdsa_signature_to_asn1( const mpi *r, const mpi *s,
288 289 290
                                    unsigned char *sig, size_t *slen )
{
    int ret;
291
    unsigned char buf[POLARSSL_ECDSA_MAX_LEN];
292 293 294
    unsigned char *p = buf + sizeof( buf );
    size_t len = 0;

295 296
    ASN1_CHK_ADD( len, asn1_write_mpi( &p, buf, s ) );
    ASN1_CHK_ADD( len, asn1_write_mpi( &p, buf, r ) );
297 298 299 300 301 302 303 304 305 306 307

    ASN1_CHK_ADD( len, asn1_write_len( &p, buf, len ) );
    ASN1_CHK_ADD( len, asn1_write_tag( &p, buf,
                                       ASN1_CONSTRUCTED | ASN1_SEQUENCE ) );

    memcpy( sig, p, len );
    *slen = len;

    return( 0 );
}

308 309 310
/*
 * Compute and write signature
 */
311
int ecdsa_write_signature( ecdsa_context *ctx, md_type_t md_alg,
312 313 314 315 316 317
                           const unsigned char *hash, size_t hlen,
                           unsigned char *sig, size_t *slen,
                           int (*f_rng)(void *, unsigned char *, size_t),
                           void *p_rng )
{
    int ret;
318 319 320 321
    mpi r, s;

    mpi_init( &r );
    mpi_init( &s );
322

323 324 325 326
#if defined(POLARSSL_ECDSA_DETERMINISTIC)
    (void) f_rng;
    (void) p_rng;

327 328
    MPI_CHK( ecdsa_sign_det( &ctx->grp, &r, &s, &ctx->d,
                             hash, hlen, md_alg ) );
329 330 331
#else
    (void) md_alg;

332 333
    MPI_CHK( ecdsa_sign( &ctx->grp, &r, &s, &ctx->d,
                         hash, hlen, f_rng, p_rng ) );
334
#endif
335

336 337 338 339 340 341 342
    MPI_CHK( ecdsa_signature_to_asn1( &r, &s, sig, slen ) );

cleanup:
    mpi_free( &r );
    mpi_free( &s );

    return( ret );
343
}
344

345 346
#if ! defined(POLARSSL_DEPRECATED_REMOVED) && \
    defined(POLARSSL_ECDSA_DETERMINISTIC)
347 348 349 350 351
int ecdsa_write_signature_det( ecdsa_context *ctx,
                               const unsigned char *hash, size_t hlen,
                               unsigned char *sig, size_t *slen,
                               md_type_t md_alg )
{
352
    return( ecdsa_write_signature( ctx, md_alg, hash, hlen, sig, slen,
353
                                   NULL, NULL ) );
354
}
355
#endif
356 357 358 359 360 361 362 363 364 365 366 367

/*
 * Read and check signature
 */
int ecdsa_read_signature( ecdsa_context *ctx,
                          const unsigned char *hash, size_t hlen,
                          const unsigned char *sig, size_t slen )
{
    int ret;
    unsigned char *p = (unsigned char *) sig;
    const unsigned char *end = sig + slen;
    size_t len;
368 369 370 371
    mpi r, s;

    mpi_init( &r );
    mpi_init( &s );
372 373 374 375

    if( ( ret = asn1_get_tag( &p, end, &len,
                    ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
    {
376 377
        ret += POLARSSL_ERR_ECP_BAD_INPUT_DATA;
        goto cleanup;
378 379 380
    }

    if( p + len != end )
381 382 383 384 385
    {
        ret = POLARSSL_ERR_ECP_BAD_INPUT_DATA +
              POLARSSL_ERR_ASN1_LENGTH_MISMATCH;
        goto cleanup;
    }
386

387 388 389 390 391 392
    if( ( ret = asn1_get_mpi( &p, end, &r ) ) != 0 ||
        ( ret = asn1_get_mpi( &p, end, &s ) ) != 0 )
    {
        ret += POLARSSL_ERR_ECP_BAD_INPUT_DATA;
        goto cleanup;
    }
393

394
    if( ( ret = ecdsa_verify( &ctx->grp, hash, hlen,
395 396
                              &ctx->Q, &r, &s ) ) != 0 )
        goto cleanup;
397

398
    if( p != end )
399
        ret = POLARSSL_ERR_ECP_SIG_LEN_MISMATCH;
400

401 402 403 404 405
cleanup:
    mpi_free( &r );
    mpi_free( &s );

    return( ret );
406 407
}

408 409 410 411 412 413 414 415 416 417
/*
 * Generate key pair
 */
int ecdsa_genkey( ecdsa_context *ctx, ecp_group_id gid,
                  int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
{
    return( ecp_use_known_dp( &ctx->grp, gid ) ||
            ecp_gen_keypair( &ctx->grp, &ctx->d, &ctx->Q, f_rng, p_rng ) );
}

418 419 420 421 422
/*
 * Set context from an ecp_keypair
 */
int ecdsa_from_keypair( ecdsa_context *ctx, const ecp_keypair *key )
{
423
    int ret;
424

425 426 427 428
    if( ( ret = ecp_group_copy( &ctx->grp, &key->grp ) ) != 0 ||
        ( ret = mpi_copy( &ctx->d, &key->d ) ) != 0 ||
        ( ret = ecp_copy( &ctx->Q, &key->Q ) ) != 0 )
    {
429
        ecdsa_free( ctx );
430
    }
431 432 433

    return( ret );
}
434

435 436 437 438 439
/*
 * Initialize context
 */
void ecdsa_init( ecdsa_context *ctx )
{
440
    ecp_keypair_init( ctx );
441 442 443 444 445 446 447
}

/*
 * Free context
 */
void ecdsa_free( ecdsa_context *ctx )
{
448
    ecp_keypair_free( ctx );
449
}
450

451
#endif /* POLARSSL_ECDSA_C */