PEM encoding for GMP RSA 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 {
37 return FALSE;
38 }
39 label ="PUBLIC KEY";
40 break;
41 case KEY_PRIV_PEM:
42 if (!key_encoding_args(args, KEY_PART_RSA_PRIV_ASN1_DER,
43 &asn1, KEY_PART_END))
44 {
45 return FALSE;
46 }
47 label ="RSA PRIVATE KEY";
48 break;
49 default:
50 return FALSE;
51 }
52
53 /* compute and allocate maximum size of PEM object */
54 pem_chars = 4*(asn1.len + 2)/3;
55 pem_lines = (asn1.len + BYTES_PER_LINE - 1) / BYTES_PER_LINE;
56 *encoding = chunk_alloc(5 + 2*(6 + strlen(label) + 6) + 3 + pem_chars + pem_lines);
57 pos = encoding->ptr;
58 len = encoding->len;
59
60 /* write PEM header */
61 written = snprintf(pos, len, "-----BEGIN %s-----\n", label);
62 pos += written;
63 len -= written;
64
65 /* write PEM body */
66 while (pem_lines--)
67 {
68 chunk_t asn1_line, pem_line;
69
70 asn1_line = chunk_create(asn1.ptr, min(asn1.len, BYTES_PER_LINE));
71 asn1.ptr += asn1_line.len;
72 asn1.len -= asn1_line.len;
73 pem_line = chunk_to_base64(asn1_line, pos);
74 pos += pem_line.len;
75 len -= pem_line.len;
76 *pos = '\n';
77 pos++;
78 len--;
79 }
80
81 /* write PEM trailer */
82 written = snprintf(pos, len, "-----END %s-----", label);
83 pos += written;
84 len -= written;
85
86 /* replace termination null character with newline */
87 *pos = '\n';
88 pos++;
89 len--;
90
91 /* compute effective length of PEM object */
92 encoding->len = pos - encoding->ptr;
93 return TRUE;
94 }
95