Add openconnect_random() function
[platform/upstream/openconnect.git] / openssl.c
1 /*
2  * OpenConnect (SSL + DTLS) VPN client
3  *
4  * Copyright © 2008-2012 Intel Corporation.
5  *
6  * Author: David Woodhouse <dwmw2@infradead.org>
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public License
10  * version 2.1, as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to:
19  *
20  *   Free Software Foundation, Inc.
21  *   51 Franklin Street, Fifth Floor,
22  *   Boston, MA 02110-1301 USA
23  */
24
25 #include <errno.h>
26
27 #include <openssl/evp.h>
28 #include <openssl/rand.h>
29
30 #include "openconnect-internal.h"
31
32 int openconnect_sha1(unsigned char *result, void *data, int len)
33 {
34         EVP_MD_CTX c;
35
36         EVP_MD_CTX_init(&c);
37         EVP_Digest(data, len, result, NULL, EVP_sha1(), NULL);
38         EVP_MD_CTX_cleanup(&c);
39
40         return 0;
41 }
42
43 int openconnect_get_cert_DER(struct openconnect_info *vpninfo,
44                              struct x509_st *cert, unsigned char **buf)
45 {
46         BIO *bp = BIO_new(BIO_s_mem());
47         BUF_MEM *certinfo;
48         size_t l;
49
50         if (!i2d_X509_bio(bp, cert)) {
51                 BIO_free(bp);
52                 return -EIO;
53         }
54
55         BIO_get_mem_ptr(bp, &certinfo);
56         l = certinfo->length;
57         *buf = malloc(l);
58         if (!*buf) {
59                 BIO_free(bp);
60                 return -ENOMEM;
61         }
62         memcpy(*buf, certinfo->data, l);
63         BIO_free(bp);
64         return l;
65 }
66
67 int openconnect_random(void *bytes, int len)
68 {
69         if (RAND_bytes(bytes, len) != 1)
70                 return -EIO;
71         return 0;
72 }