10#include <botan/base64.h>
11#include <botan/data_src.h>
12#include <botan/exceptn.h>
13#include <botan/internal/fmt.h>
21std::string linewrap(
size_t width, std::string_view in) {
23 for(
size_t i = 0; i != in.size(); ++i) {
24 if(i > 0 && i % width == 0) {
29 if(!out.empty() && out[out.size() - 1] !=
'\n') {
41std::string
encode(
const uint8_t der[],
size_t length, std::string_view label,
size_t width) {
42 const std::string PEM_HEADER =
fmt(
"-----BEGIN {}-----\n", label);
43 const std::string PEM_TRAILER =
fmt(
"-----END {}-----\n", label);
45 return (PEM_HEADER + linewrap(width,
base64_encode(der, length)) + PEM_TRAILER);
52 std::string label_got;
54 if(label_got != label_want) {
55 throw Decoding_Error(
fmt(
"PEM: Label mismatch, wanted '{}' got '{}'", label_want, label_got));
65 const size_t RANDOM_CHAR_LIMIT = 8;
69 const std::string PEM_HEADER1 =
"-----BEGIN ";
70 const std::string PEM_HEADER2 =
"-----";
73 while(position != PEM_HEADER1.length()) {
79 if(
static_cast<char>(*b) == PEM_HEADER1[position]) {
81 }
else if(position >= RANDOM_CHAR_LIMIT) {
88 while(position != PEM_HEADER2.length()) {
94 if(
static_cast<char>(*b) == PEM_HEADER2[position]) {
96 }
else if(position > 0) {
101 if(label.size() >= 128) {
104 label +=
static_cast<char>(*b);
108 std::vector<char> b64;
110 const std::string PEM_TRAILER =
fmt(
"-----END {}-----", label);
112 while(position != PEM_TRAILER.length()) {
118 if(
static_cast<char>(*b) == PEM_TRAILER[position]) {
120 }
else if(position > 0) {
139 return decode(src, label);
147 const std::string PEM_HEADER =
fmt(
"-----BEGIN {}", extra);
149 std::array<uint8_t, 4096> stack_buf{};
150 std::vector<uint8_t> heap_buf;
151 uint8_t* search_buf = stack_buf.data();
152 if(search_range > stack_buf.size()) {
153 heap_buf.resize(search_range);
154 search_buf = heap_buf.data();
157 const size_t got = source.
peek(search_buf, search_range, 0);
159 if(got < PEM_HEADER.length()) {
163 return std::search(search_buf, search_buf + got, PEM_HEADER.begin(), PEM_HEADER.end()) != search_buf + got;
size_t read_byte(uint8_t &out)
virtual size_t peek(uint8_t out[], size_t length, size_t peek_offset) const =0
std::string encode(const uint8_t der[], size_t length, std::string_view label, size_t width)
secure_vector< uint8_t > decode_check_label(DataSource &source, std::string_view label_want)
bool matches(DataSource &source, std::string_view extra, size_t search_range)
secure_vector< uint8_t > decode(DataSource &source, std::string &label)
std::string fmt(std::string_view format, const T &... args)
size_t base64_encode(char out[], const uint8_t in[], size_t input_length, size_t &input_consumed, bool final_inputs)
size_t base64_decode(uint8_t out[], const char in[], size_t input_length, size_t &input_consumed, bool final_inputs, bool ignore_ws)
std::vector< T, secure_allocator< T > > secure_vector