PEM encoding for OpenSSL RSA and EC public and private keys
[strongswan.git] / src / libstrongswan / plugins / pem / pem_encoder.c
1 /*
2 * Copyright (C) 2010 Andreas Steffen
3 * Hochschule fuer Technik Rapperswil
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * for more details.
14 */
15
16 #include "pem_encoder.h"
17
18 #define BYTES_PER_LINE 48
19
20 /**
21 * See header.
22 */
23 bool pem_encoder_encode(key_encoding_type_t type, chunk_t *encoding,
24 va_list args)
25 {
26 chunk_t asn1;
27 char *label;
28 u_char *pos;
29 size_t len, written, pem_chars, pem_lines;
30
31 switch (type)
32 {
33 case KEY_PUB_PEM:
34 if (key_encoding_args(args, KEY_PART_RSA_PUB_ASN1_DER,
35 &asn1, KEY_PART_END) ||
36 key_encoding_args(args, KEY_PART_ECDSA_PUB_ASN1_DER,
37 &asn1, KEY_PART_END))
38 {
39 label ="PUBLIC KEY";
40 break;
41 }
42 return FALSE;
43 case KEY_PRIV_PEM:
44 if (key_encoding_args(args, KEY_PART_RSA_PRIV_ASN1_DER,
45 &asn1, KEY_PART_END))
46 {
47 label ="RSA PRIVATE KEY";
48 break;
49 }
50 if (key_encoding_args(args, KEY_PART_ECDSA_PRIV_ASN1_DER,
51 &asn1, KEY_PART_END))
52 {
53 label ="EC PRIVATE KEY";
54 break;
55 }
56 return FALSE;
57 default:
58 return FALSE;
59 }
60
61 /* compute and allocate maximum size of PEM object */
62 pem_chars = 4*(asn1.len + 2)/3;
63 pem_lines = (asn1.len + BYTES_PER_LINE - 1) / BYTES_PER_LINE;
64 *encoding = chunk_alloc(5 + 2*(6 + strlen(label) + 6) + 3 + pem_chars + pem_lines);
65 pos = encoding->ptr;
66 len = encoding->len;
67
68 /* write PEM header */
69 written = snprintf(pos, len, "-----BEGIN %s-----\n", label);
70 pos += written;
71 len -= written;
72
73 /* write PEM body */
74 while (pem_lines--)
75 {
76 chunk_t asn1_line, pem_line;
77
78 asn1_line = chunk_create(asn1.ptr, min(asn1.len, BYTES_PER_LINE));
79 asn1.ptr += asn1_line.len;
80 asn1.len -= asn1_line.len;
81 pem_line = chunk_to_base64(asn1_line, pos);
82 pos += pem_line.len;
83 len -= pem_line.len;
84 *pos = '\n';
85 pos++;
86 len--;
87 }
88
89 /* write PEM trailer */
90 written = snprintf(pos, len, "-----END %s-----", label);
91 pos += written;
92 len -= written;
93
94 /* replace termination null character with newline */
95 *pos = '\n';
96 pos++;
97 len--;
98
99 /* compute effective length of PEM object */
100 encoding->len = pos - encoding->ptr;
101 return TRUE;
102 }
103