Path: blob/main/contrib/bearssl/src/ec/ec_keygen.c
39507 views
/*1* Copyright (c) 2018 Thomas Pornin <[email protected]>2*3* Permission is hereby granted, free of charge, to any person obtaining4* a copy of this software and associated documentation files (the5* "Software"), to deal in the Software without restriction, including6* without limitation the rights to use, copy, modify, merge, publish,7* distribute, sublicense, and/or sell copies of the Software, and to8* permit persons to whom the Software is furnished to do so, subject to9* the following conditions:10*11* The above copyright notice and this permission notice shall be12* included in all copies or substantial portions of the Software.13*14* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,15* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF16* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND17* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS18* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN19* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN20* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE21* SOFTWARE.22*/2324#include "inner.h"2526/* see bearssl_ec.h */27size_t28br_ec_keygen(const br_prng_class **rng_ctx,29const br_ec_impl *impl, br_ec_private_key *sk,30void *kbuf, int curve)31{32const unsigned char *order;33unsigned char *buf;34size_t len;35unsigned mask;3637if (curve < 0 || curve >= 3238|| ((impl->supported_curves >> curve) & 1) == 0)39{40return 0;41}42order = impl->order(curve, &len);43while (len > 0 && *order == 0) {44order ++;45len --;46}47if (kbuf == NULL || len == 0) {48return len;49}50mask = order[0];51mask |= (mask >> 1);52mask |= (mask >> 2);53mask |= (mask >> 4);5455/*56* We generate sequences of random bits of the right size, until57* the value is strictly lower than the curve order (we also58* check for all-zero values, which are invalid).59*/60buf = kbuf;61for (;;) {62size_t u;63unsigned cc, zz;6465(*rng_ctx)->generate(rng_ctx, buf, len);66buf[0] &= mask;67cc = 0;68u = len;69zz = 0;70while (u -- > 0) {71cc = ((unsigned)(buf[u] - order[u] - cc) >> 8) & 1;72zz |= buf[u];73}74if (cc != 0 && zz != 0) {75break;76}77}7879if (sk != NULL) {80sk->curve = curve;81sk->x = buf;82sk->xlen = len;83}84return len;85}868788