ec_check.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. * Copyright 2002-2019 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 "ec_lcl.h"
  10. #include <openssl/err.h>
  11. int EC_GROUP_check_named_curve(const EC_GROUP *group, int nist_only)
  12. {
  13. int nid;
  14. nid = ec_curve_nid_from_params(group);
  15. if (nid > 0 && nist_only && EC_curve_nid2nist(nid) == NULL)
  16. nid = NID_undef;
  17. return nid;
  18. }
  19. int EC_GROUP_check(const EC_GROUP *group, BN_CTX *ctx)
  20. {
  21. int ret = 0;
  22. const BIGNUM *order;
  23. BN_CTX *new_ctx = NULL;
  24. EC_POINT *point = NULL;
  25. if (group == NULL || group->meth == NULL) {
  26. ECerr(EC_F_EC_GROUP_CHECK, ERR_R_PASSED_NULL_PARAMETER);
  27. return 0;
  28. }
  29. /* Custom curves assumed to be correct */
  30. if ((group->meth->flags & EC_FLAGS_CUSTOM_CURVE) != 0)
  31. return 1;
  32. if (ctx == NULL) {
  33. ctx = new_ctx = BN_CTX_new();
  34. if (ctx == NULL) {
  35. ECerr(EC_F_EC_GROUP_CHECK, ERR_R_MALLOC_FAILURE);
  36. goto err;
  37. }
  38. }
  39. /* check the discriminant */
  40. if (!EC_GROUP_check_discriminant(group, ctx)) {
  41. ECerr(EC_F_EC_GROUP_CHECK, EC_R_DISCRIMINANT_IS_ZERO);
  42. goto err;
  43. }
  44. /* check the generator */
  45. if (group->generator == NULL) {
  46. ECerr(EC_F_EC_GROUP_CHECK, EC_R_UNDEFINED_GENERATOR);
  47. goto err;
  48. }
  49. if (EC_POINT_is_on_curve(group, group->generator, ctx) <= 0) {
  50. ECerr(EC_F_EC_GROUP_CHECK, EC_R_POINT_IS_NOT_ON_CURVE);
  51. goto err;
  52. }
  53. /* check the order of the generator */
  54. if ((point = EC_POINT_new(group)) == NULL)
  55. goto err;
  56. order = EC_GROUP_get0_order(group);
  57. if (order == NULL)
  58. goto err;
  59. if (BN_is_zero(order)) {
  60. ECerr(EC_F_EC_GROUP_CHECK, EC_R_UNDEFINED_ORDER);
  61. goto err;
  62. }
  63. if (!EC_POINT_mul(group, point, order, NULL, NULL, ctx))
  64. goto err;
  65. if (!EC_POINT_is_at_infinity(group, point)) {
  66. ECerr(EC_F_EC_GROUP_CHECK, EC_R_INVALID_GROUP_ORDER);
  67. goto err;
  68. }
  69. ret = 1;
  70. err:
  71. BN_CTX_free(new_ctx);
  72. EC_POINT_free(point);
  73. return ret;
  74. }