ecx_key.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. * Copyright 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. #include <openssl/err.h>
  10. #include "crypto/ecx.h"
  11. ECX_KEY *ecx_key_new(OPENSSL_CTX *libctx, ECX_KEY_TYPE type, int haspubkey)
  12. {
  13. ECX_KEY *ret = OPENSSL_zalloc(sizeof(*ret));
  14. if (ret == NULL)
  15. return NULL;
  16. ret->libctx = libctx;
  17. ret->haspubkey = haspubkey;
  18. switch (type) {
  19. case ECX_KEY_TYPE_X25519:
  20. ret->keylen = X25519_KEYLEN;
  21. break;
  22. case ECX_KEY_TYPE_X448:
  23. ret->keylen = X448_KEYLEN;
  24. break;
  25. case ECX_KEY_TYPE_ED25519:
  26. ret->keylen = ED25519_KEYLEN;
  27. break;
  28. case ECX_KEY_TYPE_ED448:
  29. ret->keylen = ED448_KEYLEN;
  30. break;
  31. }
  32. ret->type = type;
  33. ret->references = 1;
  34. ret->lock = CRYPTO_THREAD_lock_new();
  35. if (ret->lock == NULL) {
  36. ERR_raise(ERR_LIB_EC, ERR_R_MALLOC_FAILURE);
  37. OPENSSL_free(ret);
  38. return NULL;
  39. }
  40. return ret;
  41. }
  42. void ecx_key_free(ECX_KEY *key)
  43. {
  44. int i;
  45. if (key == NULL)
  46. return;
  47. CRYPTO_DOWN_REF(&key->references, &i, key->lock);
  48. REF_PRINT_COUNT("ECX_KEY", r);
  49. if (i > 0)
  50. return;
  51. REF_ASSERT_ISNT(i < 0);
  52. OPENSSL_secure_clear_free(key->privkey, key->keylen);
  53. CRYPTO_THREAD_lock_free(key->lock);
  54. OPENSSL_free(key);
  55. }
  56. int ecx_key_up_ref(ECX_KEY *key)
  57. {
  58. int i;
  59. if (CRYPTO_UP_REF(&key->references, &i, key->lock) <= 0)
  60. return 0;
  61. REF_PRINT_COUNT("ECX_KEY", key);
  62. REF_ASSERT_ISNT(i < 2);
  63. return ((i > 1) ? 1 : 0);
  64. }
  65. unsigned char *ecx_key_allocate_privkey(ECX_KEY *key)
  66. {
  67. key->privkey = OPENSSL_secure_zalloc(key->keylen);
  68. return key->privkey;
  69. }