Add the ability to ECX to import keys with only the private key
[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(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->haspubkey = haspubkey;
21     switch (type) {
22     case ECX_KEY_TYPE_X25519:
23         ret->keylen = X25519_KEYLEN;
24         break;
25     case ECX_KEY_TYPE_X448:
26         ret->keylen = X448_KEYLEN;
27         break;
28     case ECX_KEY_TYPE_ED25519:
29         ret->keylen = ED25519_KEYLEN;
30         break;
31     case ECX_KEY_TYPE_ED448:
32         ret->keylen = ED448_KEYLEN;
33         break;
34     }
35     ret->type = type;
36     ret->references = 1;
37
38     ret->lock = CRYPTO_THREAD_lock_new();
39     if (ret->lock == NULL) {
40         ERR_raise(ERR_LIB_EC, ERR_R_MALLOC_FAILURE);
41         OPENSSL_free(ret);
42         return NULL;
43     }
44
45     return ret;
46 }
47
48 void ecx_key_free(ECX_KEY *key)
49 {
50     int i;
51
52     if (key == NULL)
53         return;
54
55     CRYPTO_DOWN_REF(&key->references, &i, key->lock);
56     REF_PRINT_COUNT("ECX_KEY", r);
57     if (i > 0)
58         return;
59     REF_ASSERT_ISNT(i < 0);
60
61     OPENSSL_secure_clear_free(key->privkey, key->keylen);
62     CRYPTO_THREAD_lock_free(key->lock);
63     OPENSSL_free(key);
64 }
65
66 int ecx_key_up_ref(ECX_KEY *key)
67 {
68     int i;
69
70     if (CRYPTO_UP_REF(&key->references, &i, key->lock) <= 0)
71         return 0;
72
73     REF_PRINT_COUNT("ECX_KEY", key);
74     REF_ASSERT_ISNT(i < 2);
75     return ((i > 1) ? 1 : 0);
76 }
77
78 unsigned char *ecx_key_allocate_privkey(ECX_KEY *key)
79 {
80     key->privkey = OPENSSL_secure_zalloc(key->keylen);
81
82     return key->privkey;
83 }