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