2 * Copyright (C) 2010 Andreas Steffen
3 * Hochschule fuer Technik Rapperswil
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>.
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
16 #include "pem_encoder.h"
18 #define BYTES_PER_LINE 48
23 bool pem_encoder_encode(key_encoding_type_t type
, chunk_t
*encoding
,
29 size_t len
, written
, pem_chars
, pem_lines
;
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
,
44 if (key_encoding_args(args
, KEY_PART_RSA_PRIV_ASN1_DER
,
47 label
="RSA PRIVATE KEY";
50 if (key_encoding_args(args
, KEY_PART_ECDSA_PRIV_ASN1_DER
,
53 label
="EC PRIVATE KEY";
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
);
68 /* write PEM header */
69 written
= snprintf(pos
, len
, "-----BEGIN %s-----\n", label
);
76 chunk_t asn1_line
, pem_line
;
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
);
89 /* write PEM trailer */
90 written
= snprintf(pos
, len
, "-----END %s-----", label
);
94 /* replace termination null character with newline */
99 /* compute effective length of PEM object */
100 encoding
->len
= pos
- encoding
->ptr
;