Add ECDSA key import.
[tinc] / src / openssl / ecdsa.c
1 /*
2     ecdsa.c -- ECDSA key handling
3     Copyright (C) 2011 Guus Sliepen <guus@tinc-vpn.org>
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License along
16     with this program; if not, write to the Free Software Foundation, Inc.,
17     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "system.h"
21
22 #include <openssl/pem.h>
23 #include <openssl/err.h>
24
25 #include "logger.h"
26 #include "ecdsa.h"
27 #include "utils.h"
28
29 // Set ECDSA keys
30
31 bool ecdsa_set_base64_public_key(ecdsa_t *ecdsa, const char *p) {
32         *ecdsa = EC_KEY_new_by_curve_name(NID_secp521r1);
33
34         int len = strlen(p);
35         unsigned char pubkey[len / 4 * 3 + 3];
36         const unsigned char *ppubkey = pubkey;
37         len = b64decode(p, pubkey, len);
38
39         if(!o2i_ECPublicKey(ecdsa, &ppubkey, len)) {
40                 logger(LOG_DEBUG, "o2i_ECPublicKey failed: %s", ERR_error_string(ERR_get_error(), NULL));
41                 abort();
42         }
43
44         return true;
45 }
46
47 // Read PEM ECDSA keys
48
49 bool ecdsa_read_pem_public_key(ecdsa_t *ecdsa, FILE *fp) {
50         *ecdsa = PEM_read_EC_PUBKEY(fp, ecdsa, NULL, NULL);
51
52         if(*ecdsa)
53                 return true;
54
55         logger(LOG_ERR, "Unable to read ECDSA public key: %s", ERR_error_string(ERR_get_error(), NULL));
56         return false;
57 }
58
59 bool ecdsa_read_pem_private_key(ecdsa_t *ecdsa, FILE *fp) {
60         *ecdsa = PEM_read_ECPrivateKey(fp, NULL, NULL, NULL);
61
62         if(*ecdsa)
63                 return true;
64         
65         logger(LOG_ERR, "Unable to read ECDSA private key: %s", ERR_error_string(ERR_get_error(), NULL));
66         return false;
67 }
68
69 size_t ecdsa_size(ecdsa_t *ecdsa) {
70         return ECDSA_size(*ecdsa);
71 }
72
73 bool ecdsa_sign(ecdsa_t *ecdsa, const void *in, size_t len, void *sig) {
74         logger(LOG_ERR, "Unable to perform ECDSA signature: %s", ERR_error_string(ERR_get_error(), NULL));
75         return false;   
76 }
77
78 bool ecdsa_verify(ecdsa_t *ecdsa, const void *in, size_t len, const void *sig) {
79         logger(LOG_ERR, "Unable to perform ECDSA verification: %s", ERR_error_string(ERR_get_error(), NULL));
80         return false;   
81 }