GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: usr.sbin/acme-client/rsa.c Lines: 0 30 0.0 %
Date: 2017-11-13 Branches: 0 18 0.0 %

Line Branch Exec Source
1
/*	$Id: rsa.c,v 1.6 2017/01/24 13:32:55 jsing Exp $ */
2
/*
3
 * Copyright (c) 2016 Kristaps Dzonsons <kristaps@bsd.lv>
4
 *
5
 * Permission to use, copy, modify, and distribute this software for any
6
 * purpose with or without fee is hereby granted, provided that the above
7
 * copyright notice and this permission notice appear in all copies.
8
 *
9
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
10
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
12
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16
 */
17
18
#include <err.h>
19
#include <stdlib.h>
20
#include <unistd.h>
21
22
#include <openssl/evp.h>
23
#include <openssl/pem.h>
24
#include <openssl/rsa.h>
25
26
#include "rsa.h"
27
28
/*
29
 * Default number of bits when creating a new key.
30
 */
31
#define	KBITS 4096
32
33
/*
34
 * Create an RSA key with the default KBITS number of bits.
35
 */
36
EVP_PKEY *
37
rsa_key_create(FILE *f, const char *fname)
38
{
39
	EVP_PKEY_CTX	*ctx = NULL;
40
	EVP_PKEY	*pkey = NULL;
41
42
	/* First, create the context and the key. */
43
44
	if ((ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, NULL)) == NULL) {
45
		warnx("EVP_PKEY_CTX_new_id");
46
		goto err;
47
	} else if (EVP_PKEY_keygen_init(ctx) <= 0) {
48
		warnx("EVP_PKEY_keygen_init");
49
		goto err;
50
	} else if (EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, KBITS) <= 0) {
51
		warnx("EVP_PKEY_set_rsa_keygen_bits");
52
		goto err;
53
	} else if (EVP_PKEY_keygen(ctx, &pkey) <= 0) {
54
		warnx("EVP_PKEY_keygen");
55
		goto err;
56
	}
57
58
	/* Serialise the key to the disc. */
59
60
	if (PEM_write_PrivateKey(f, pkey, NULL, NULL, 0, NULL, NULL))
61
		goto out;
62
63
	warnx("%s: PEM_write_PrivateKey", fname);
64
err:
65
	if (pkey != NULL)
66
		EVP_PKEY_free(pkey);
67
	pkey = NULL;
68
out:
69
	if (ctx != NULL)
70
		EVP_PKEY_CTX_free(ctx);
71
	return pkey;
72
}
73
74
75
EVP_PKEY *
76
rsa_key_load(FILE *f, const char *fname)
77
{
78
	EVP_PKEY	*pkey;
79
80
	pkey = PEM_read_PrivateKey(f, NULL, NULL, NULL);
81
	if (pkey == NULL) {
82
		warnx("%s: PEM_read_PrivateKey", fname);
83
		return NULL;
84
	} else if (EVP_PKEY_type(pkey->type) == EVP_PKEY_RSA)
85
		return pkey;
86
87
	warnx("%s: unsupported key type", fname);
88
	EVP_PKEY_free(pkey);
89
	return NULL;
90
}