dh_rfc7919.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright 2017 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 <stdio.h>
  10. #include "internal/cryptlib.h"
  11. #include "dh_local.h"
  12. #include <openssl/bn.h>
  13. #include <openssl/objects.h>
  14. #include "crypto/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. dh->dirty_cnt++;
  24. return dh;
  25. }
  26. DH *DH_new_by_nid(int nid)
  27. {
  28. switch (nid) {
  29. case NID_ffdhe2048:
  30. return dh_param_init(&_bignum_ffdhe2048_p, 225);
  31. case NID_ffdhe3072:
  32. return dh_param_init(&_bignum_ffdhe3072_p, 275);
  33. case NID_ffdhe4096:
  34. return dh_param_init(&_bignum_ffdhe4096_p, 325);
  35. case NID_ffdhe6144:
  36. return dh_param_init(&_bignum_ffdhe6144_p, 375);
  37. case NID_ffdhe8192:
  38. return dh_param_init(&_bignum_ffdhe8192_p, 400);
  39. default:
  40. DHerr(DH_F_DH_NEW_BY_NID, DH_R_INVALID_PARAMETER_NID);
  41. return NULL;
  42. }
  43. }
  44. int DH_get_nid(const DH *dh)
  45. {
  46. int nid;
  47. if (BN_get_word(dh->g) != 2)
  48. return NID_undef;
  49. if (!BN_cmp(dh->p, &_bignum_ffdhe2048_p))
  50. nid = NID_ffdhe2048;
  51. else if (!BN_cmp(dh->p, &_bignum_ffdhe3072_p))
  52. nid = NID_ffdhe3072;
  53. else if (!BN_cmp(dh->p, &_bignum_ffdhe4096_p))
  54. nid = NID_ffdhe4096;
  55. else if (!BN_cmp(dh->p, &_bignum_ffdhe6144_p))
  56. nid = NID_ffdhe6144;
  57. else if (!BN_cmp(dh->p, &_bignum_ffdhe8192_p))
  58. nid = NID_ffdhe8192;
  59. else
  60. return NID_undef;
  61. if (dh->q != NULL) {
  62. BIGNUM *q = BN_dup(dh->p);
  63. /* Check q = p * 2 + 1 we already know q is odd, so just shift right */
  64. if (q == NULL || !BN_rshift1(q, q) || !BN_cmp(dh->q, q))
  65. nid = NID_undef;
  66. BN_free(q);
  67. }
  68. return nid;
  69. }