dsa_key.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * Copyright 1995-2016 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 <time.h>
  11. #include "internal/cryptlib.h"
  12. #include <openssl/bn.h>
  13. #include "dsa_locl.h"
  14. static int dsa_builtin_keygen(DSA *dsa);
  15. int DSA_generate_key(DSA *dsa)
  16. {
  17. if (dsa->meth->dsa_keygen)
  18. return dsa->meth->dsa_keygen(dsa);
  19. return dsa_builtin_keygen(dsa);
  20. }
  21. static int dsa_builtin_keygen(DSA *dsa)
  22. {
  23. int ok = 0;
  24. BN_CTX *ctx = NULL;
  25. BIGNUM *pub_key = NULL, *priv_key = NULL;
  26. if ((ctx = BN_CTX_new()) == NULL)
  27. goto err;
  28. if (dsa->priv_key == NULL) {
  29. if ((priv_key = BN_secure_new()) == NULL)
  30. goto err;
  31. } else
  32. priv_key = dsa->priv_key;
  33. do
  34. if (!BN_rand_range(priv_key, dsa->q))
  35. goto err;
  36. while (BN_is_zero(priv_key)) ;
  37. if (dsa->pub_key == NULL) {
  38. if ((pub_key = BN_new()) == NULL)
  39. goto err;
  40. } else
  41. pub_key = dsa->pub_key;
  42. {
  43. BIGNUM *prk = BN_new();
  44. if (prk == NULL)
  45. goto err;
  46. BN_with_flags(prk, priv_key, BN_FLG_CONSTTIME);
  47. if (!BN_mod_exp(pub_key, dsa->g, prk, dsa->p, ctx)) {
  48. BN_free(prk);
  49. goto err;
  50. }
  51. /* We MUST free prk before any further use of priv_key */
  52. BN_free(prk);
  53. }
  54. dsa->priv_key = priv_key;
  55. dsa->pub_key = pub_key;
  56. ok = 1;
  57. err:
  58. if (pub_key != dsa->pub_key)
  59. BN_free(pub_key);
  60. if (priv_key != dsa->priv_key)
  61. BN_free(priv_key);
  62. BN_CTX_free(ctx);
  63. return (ok);
  64. }