dh_rfc7919.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. * Copyright 2017 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the OpenSSL license (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 <stdio.h>
  10. #include "internal/cryptlib.h"
  11. #include "dh_locl.h"
  12. #include <openssl/bn.h>
  13. #include <openssl/objects.h>
  14. #include "internal/bn_dh.h"
  15. static DH *dh_param_init(const BIGNUM *p, int32_t nbits)
  16. {
  17. DH *dh = DH_new();
  18. if (dh == NULL)
  19. return NULL;
  20. dh->p = (BIGNUM *)p;
  21. dh->g = (BIGNUM *)&_bignum_const_2;
  22. dh->length = nbits;
  23. return dh;
  24. }
  25. DH *DH_new_by_nid(int nid)
  26. {
  27. switch (nid) {
  28. case NID_ffdhe2048:
  29. return dh_param_init(&_bignum_ffdhe2048_p, 225);
  30. case NID_ffdhe3072:
  31. return dh_param_init(&_bignum_ffdhe3072_p, 275);
  32. case NID_ffdhe4096:
  33. return dh_param_init(&_bignum_ffdhe4096_p, 325);
  34. case NID_ffdhe6144:
  35. return dh_param_init(&_bignum_ffdhe6144_p, 375);
  36. case NID_ffdhe8192:
  37. return dh_param_init(&_bignum_ffdhe8192_p, 400);
  38. default:
  39. DHerr(DH_F_DH_NEW_BY_NID, DH_R_INVALID_PARAMETER_NID);
  40. return NULL;
  41. }
  42. }
  43. int DH_get_nid(const DH *dh)
  44. {
  45. int nid;
  46. if (BN_get_word(dh->g) != 2)
  47. return NID_undef;
  48. if (!BN_cmp(dh->p, &_bignum_ffdhe2048_p))
  49. nid = NID_ffdhe2048;
  50. else if (!BN_cmp(dh->p, &_bignum_ffdhe3072_p))
  51. nid = NID_ffdhe3072;
  52. else if (!BN_cmp(dh->p, &_bignum_ffdhe4096_p))
  53. nid = NID_ffdhe4096;
  54. else if (!BN_cmp(dh->p, &_bignum_ffdhe6144_p))
  55. nid = NID_ffdhe6144;
  56. else if (!BN_cmp(dh->p, &_bignum_ffdhe8192_p))
  57. nid = NID_ffdhe8192;
  58. else
  59. return NID_undef;
  60. if (dh->q != NULL) {
  61. BIGNUM *q = BN_dup(dh->p);
  62. /* Check q = p * 2 + 1 we already know q is odd, so just shift right */
  63. if (q == NULL || !BN_rshift1(q, q) || !BN_cmp(dh->q, q))
  64. nid = NID_undef;
  65. BN_free(q);
  66. }
  67. return nid;
  68. }