2
0

ffc_key_generate.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. #include "internal/ffc.h"
  10. /*
  11. * SP800-56Ar3 5.6.1.1.4 Key pair generation by testing candidates.
  12. * Generates a private key in the interval [1, min(2 ^ N - 1, q - 1)].
  13. *
  14. * ctx must be set up with a libctx (for fips mode).
  15. * params contains the FFC domain parameters p, q and g (for DH or DSA).
  16. * N is the maximum bit length of the generated private key,
  17. * s is the security strength.
  18. * priv_key is the returned private key,
  19. */
  20. int ossl_ffc_generate_private_key(BN_CTX *ctx, const FFC_PARAMS *params,
  21. int N, int s, BIGNUM *priv)
  22. {
  23. int ret = 0, qbits = BN_num_bits(params->q);
  24. BIGNUM *m, *two_powN = NULL;
  25. /* Deal with the edge cases where the value of N and/or s is not set */
  26. if (s == 0)
  27. goto err;
  28. if (N == 0)
  29. N = params->keylength ? params->keylength : 2 * s;
  30. /* Step (2) : check range of N */
  31. if (N < 2 * s || N > qbits)
  32. return 0;
  33. two_powN = BN_new();
  34. /* 2^N */
  35. if (two_powN == NULL || !BN_lshift(two_powN, BN_value_one(), N))
  36. goto err;
  37. /* Step (5) : M = min(2 ^ N, q) */
  38. m = (BN_cmp(two_powN, params->q) > 0) ? params->q : two_powN;
  39. do {
  40. /* Steps (3, 4 & 7) : c + 1 = 1 + random[0..2^N - 1] */
  41. if (!BN_priv_rand_range_ex(priv, two_powN, 0, ctx)
  42. || !BN_add_word(priv, 1))
  43. goto err;
  44. /* Step (6) : loop if c > M - 2 (i.e. c + 1 >= M) */
  45. if (BN_cmp(priv, m) < 0)
  46. break;
  47. } while (1);
  48. ret = 1;
  49. err:
  50. BN_free(two_powN);
  51. return ret;
  52. }