ecx_key.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*
  2. * Copyright 2020-2021 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 <string.h>
  10. #include <openssl/err.h>
  11. #include "crypto/ecx.h"
  12. ECX_KEY *ossl_ecx_key_new(OSSL_LIB_CTX *libctx, ECX_KEY_TYPE type, int haspubkey,
  13. const char *propq)
  14. {
  15. ECX_KEY *ret = OPENSSL_zalloc(sizeof(*ret));
  16. if (ret == NULL)
  17. return NULL;
  18. ret->libctx = libctx;
  19. ret->haspubkey = haspubkey;
  20. switch (type) {
  21. case ECX_KEY_TYPE_X25519:
  22. ret->keylen = X25519_KEYLEN;
  23. break;
  24. case ECX_KEY_TYPE_X448:
  25. ret->keylen = X448_KEYLEN;
  26. break;
  27. case ECX_KEY_TYPE_ED25519:
  28. ret->keylen = ED25519_KEYLEN;
  29. break;
  30. case ECX_KEY_TYPE_ED448:
  31. ret->keylen = ED448_KEYLEN;
  32. break;
  33. }
  34. ret->type = type;
  35. ret->references = 1;
  36. if (propq != NULL) {
  37. ret->propq = OPENSSL_strdup(propq);
  38. if (ret->propq == NULL)
  39. goto err;
  40. }
  41. ret->lock = CRYPTO_THREAD_lock_new();
  42. if (ret->lock == NULL)
  43. goto err;
  44. return ret;
  45. err:
  46. ERR_raise(ERR_LIB_EC, ERR_R_MALLOC_FAILURE);
  47. OPENSSL_free(ret);
  48. return NULL;
  49. }
  50. void ossl_ecx_key_free(ECX_KEY *key)
  51. {
  52. int i;
  53. if (key == NULL)
  54. return;
  55. CRYPTO_DOWN_REF(&key->references, &i, key->lock);
  56. REF_PRINT_COUNT("ECX_KEY", key);
  57. if (i > 0)
  58. return;
  59. REF_ASSERT_ISNT(i < 0);
  60. OPENSSL_free(key->propq);
  61. OPENSSL_secure_clear_free(key->privkey, key->keylen);
  62. CRYPTO_THREAD_lock_free(key->lock);
  63. OPENSSL_free(key);
  64. }
  65. void ossl_ecx_key_set0_libctx(ECX_KEY *key, OSSL_LIB_CTX *libctx)
  66. {
  67. key->libctx = libctx;
  68. }
  69. int ossl_ecx_key_up_ref(ECX_KEY *key)
  70. {
  71. int i;
  72. if (CRYPTO_UP_REF(&key->references, &i, key->lock) <= 0)
  73. return 0;
  74. REF_PRINT_COUNT("ECX_KEY", key);
  75. REF_ASSERT_ISNT(i < 2);
  76. return ((i > 1) ? 1 : 0);
  77. }
  78. unsigned char *ossl_ecx_key_allocate_privkey(ECX_KEY *key)
  79. {
  80. key->privkey = OPENSSL_secure_zalloc(key->keylen);
  81. return key->privkey;
  82. }