dh_group_params.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /*
  2. * Copyright 2017-2022 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. static DH *dh_param_init(OSSL_LIB_CTX *libctx, const DH_NAMED_GROUP *group)
  24. {
  25. DH *dh = ossl_dh_new_ex(libctx);
  26. if (dh == NULL)
  27. return NULL;
  28. ossl_ffc_named_group_set(&dh->params, group);
  29. dh->params.nid = ossl_ffc_named_group_get_uid(group);
  30. dh->dirty_cnt++;
  31. return dh;
  32. }
  33. DH *ossl_dh_new_by_nid_ex(OSSL_LIB_CTX *libctx, int nid)
  34. {
  35. const DH_NAMED_GROUP *group;
  36. if ((group = ossl_ffc_uid_to_dh_named_group(nid)) != NULL)
  37. return dh_param_init(libctx, group);
  38. ERR_raise(ERR_LIB_DH, DH_R_INVALID_PARAMETER_NID);
  39. return NULL;
  40. }
  41. DH *DH_new_by_nid(int nid)
  42. {
  43. return ossl_dh_new_by_nid_ex(NULL, nid);
  44. }
  45. void ossl_dh_cache_named_group(DH *dh)
  46. {
  47. const DH_NAMED_GROUP *group;
  48. if (dh == NULL)
  49. return;
  50. dh->params.nid = NID_undef; /* flush cached value */
  51. /* Exit if p or g is not set */
  52. if (dh->params.p == NULL
  53. || dh->params.g == NULL)
  54. return;
  55. if ((group = ossl_ffc_numbers_to_dh_named_group(dh->params.p,
  56. dh->params.q,
  57. dh->params.g)) != NULL) {
  58. if (dh->params.q == NULL)
  59. dh->params.q = (BIGNUM *)ossl_ffc_named_group_get_q(group);
  60. /* cache the nid and default key length */
  61. dh->params.nid = ossl_ffc_named_group_get_uid(group);
  62. dh->params.keylength = ossl_ffc_named_group_get_keylength(group);
  63. dh->dirty_cnt++;
  64. }
  65. }
  66. int ossl_dh_is_named_safe_prime_group(const DH *dh)
  67. {
  68. int id = DH_get_nid(dh);
  69. /*
  70. * Exclude RFC5114 groups (id = 1..3) since they do not have
  71. * q = (p - 1) / 2
  72. */
  73. return (id > 3);
  74. }
  75. int DH_get_nid(const DH *dh)
  76. {
  77. if (dh == NULL)
  78. return NID_undef;
  79. return dh->params.nid;
  80. }