1 /*
2  * Copyright 2013 The Android Open Source Project
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are met:
6  *     * Redistributions of source code must retain the above copyright
7  *       notice, this list of conditions and the following disclaimer.
8  *     * Redistributions in binary form must reproduce the above copyright
9  *       notice, this list of conditions and the following disclaimer in the
10  *       documentation and/or other materials provided with the distribution.
11  *     * Neither the name of Google Inc. nor the names of its contributors may
12  *       be used to endorse or promote products derived from this software
13  *       without specific prior written permission.
14  *
15  * THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
17  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
18  * EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
19  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
21  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
22  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
23  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
24  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include <string.h>
28 
29 #include "mincrypt/p256_ecdsa.h"
30 #include "mincrypt/p256.h"
31 
p256_ecdsa_verify(const p256_int * key_x,const p256_int * key_y,const p256_int * message,const p256_int * r,const p256_int * s)32 int p256_ecdsa_verify(const p256_int* key_x, const p256_int* key_y,
33                       const p256_int* message,
34                       const p256_int* r, const p256_int* s) {
35   p256_int u, v;
36 
37   // Check public key.
38   if (!p256_is_valid_point(key_x, key_y)) return 0;
39 
40   // Check r and s are != 0 % n.
41   p256_mod(&SECP256r1_n, r, &u);
42   p256_mod(&SECP256r1_n, s, &v);
43   if (p256_is_zero(&u) || p256_is_zero(&v)) return 0;
44 
45   p256_modinv_vartime(&SECP256r1_n, s, &v);
46   p256_modmul(&SECP256r1_n, message, 0, &v, &u);  // message / s % n
47   p256_modmul(&SECP256r1_n, r, 0, &v, &v);  // r / s % n
48 
49   p256_points_mul_vartime(&u, &v,
50                           key_x, key_y,
51                           &u, &v);
52 
53   p256_mod(&SECP256r1_n, &u, &u);  // (x coord % p) % n
54   return p256_cmp(r, &u) == 0;
55 }
56 
57