59643cc6adc0c5087ccdea594d5249c6919c3709
[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(size_t keylen, int haspubkey)
14 {
15     ECX_KEY *ret = OPENSSL_zalloc(sizeof(*ret));
16
17     if (ret == NULL)
18         return NULL;
19
20     ret->haspubkey = haspubkey;
21     ret->keylen = keylen;
22     ret->references = 1;
23
24     ret->lock = CRYPTO_THREAD_lock_new();
25     if (ret->lock == NULL) {
26         ERR_raise(ERR_LIB_EC, ERR_R_MALLOC_FAILURE);
27         OPENSSL_free(ret);
28         return NULL;
29     }
30
31     return ret;
32 }
33
34 void ecx_key_free(ECX_KEY *key)
35 {
36     int i;
37
38     if (key == NULL)
39         return;
40
41     CRYPTO_DOWN_REF(&key->references, &i, key->lock);
42     REF_PRINT_COUNT("ECX_KEY", r);
43     if (i > 0)
44         return;
45     REF_ASSERT_ISNT(i < 0);
46
47     OPENSSL_secure_clear_free(key->privkey, key->keylen);
48     CRYPTO_THREAD_lock_free(key->lock);
49     OPENSSL_free(key);
50 }
51
52 int ecx_key_up_ref(ECX_KEY *key)
53 {
54     int i;
55
56     if (CRYPTO_UP_REF(&key->references, &i, key->lock) <= 0)
57         return 0;
58
59     REF_PRINT_COUNT("ECX_KEY", key);
60     REF_ASSERT_ISNT(i < 2);
61     return ((i > 1) ? 1 : 0);
62 }
63
64 unsigned char *ecx_key_allocate_privkey(ECX_KEY *key)
65 {
66     key->privkey = OPENSSL_secure_zalloc(key->keylen);
67
68     return key->privkey;
69 }