dh_group_params.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. * Copyright 2017-2020 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. /* DH parameters from RFC7919 and RFC3526 */
  10. /*
  11. * DH low level APIs are deprecated for public use, but still ok for
  12. * internal use.
  13. */
  14. #include "internal/deprecated.h"
  15. #include <stdio.h>
  16. #include "internal/cryptlib.h"
  17. #include "internal/ffc.h"
  18. #include "dh_local.h"
  19. #include <openssl/bn.h>
  20. #include <openssl/objects.h>
  21. #include "internal/nelem.h"
  22. #include "crypto/dh.h"
  23. #include "e_os.h" /* strcasecmp */
  24. static DH *dh_param_init(OSSL_LIB_CTX *libctx, const DH_NAMED_GROUP *group)
  25. {
  26. DH *dh = dh_new_ex(libctx);
  27. if (dh == NULL)
  28. return NULL;
  29. ossl_ffc_named_group_set_pqg(&dh->params, group);
  30. dh->params.nid = ossl_ffc_named_group_get_uid(group);
  31. dh->length = BN_num_bits(dh->params.q);
  32. dh->dirty_cnt++;
  33. return dh;
  34. }
  35. DH *dh_new_by_nid_ex(OSSL_LIB_CTX *libctx, int nid)
  36. {
  37. const DH_NAMED_GROUP *group;
  38. if ((group = ossl_ffc_uid_to_dh_named_group(nid)) != NULL)
  39. return dh_param_init(libctx, group);
  40. ERR_raise(ERR_LIB_DH, DH_R_INVALID_PARAMETER_NID);
  41. return NULL;
  42. }
  43. DH *DH_new_by_nid(int nid)
  44. {
  45. return dh_new_by_nid_ex(NULL, nid);
  46. }
  47. void dh_cache_named_group(DH *dh)
  48. {
  49. const DH_NAMED_GROUP *group;
  50. if (dh == NULL)
  51. return;
  52. dh->params.nid = NID_undef; /* flush cached value */
  53. /* Exit if p or g is not set */
  54. if (dh->params.p == NULL
  55. || dh->params.g == NULL)
  56. return;
  57. if ((group = ossl_ffc_numbers_to_dh_named_group(dh->params.p,
  58. dh->params.q,
  59. dh->params.g)) != NULL) {
  60. if (dh->params.q == NULL)
  61. dh->params.q = (BIGNUM *)ossl_ffc_named_group_get_q(group);
  62. /* cache the nid */
  63. dh->params.nid = ossl_ffc_named_group_get_uid(group);
  64. dh->length = BN_num_bits(dh->params.q);
  65. dh->dirty_cnt++;
  66. }
  67. }
  68. int DH_get_nid(const DH *dh)
  69. {
  70. if (dh == NULL)
  71. return NID_undef;
  72. return dh->params.nid;
  73. }