This source file includes following definitions.
- GetNext
- Init
#include "net/cert/pem_tokenizer.h"
#include "base/base64.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
namespace {
const char kPEMSearchBlock[] = "-----BEGIN ";
const char kPEMBeginBlock[] = "-----BEGIN %s-----";
const char kPEMEndBlock[] = "-----END %s-----";
}
namespace net {
using base::StringPiece;
struct PEMTokenizer::PEMType {
std::string type;
std::string header;
std::string footer;
};
PEMTokenizer::PEMTokenizer(
const StringPiece& str,
const std::vector<std::string>& allowed_block_types) {
Init(str, allowed_block_types);
}
PEMTokenizer::~PEMTokenizer() {
}
bool PEMTokenizer::GetNext() {
while (pos_ != StringPiece::npos) {
pos_ = str_.find(kPEMSearchBlock, pos_);
if (pos_ == StringPiece::npos)
return false;
std::vector<PEMType>::const_iterator it;
for (it = block_types_.begin(); it != block_types_.end(); ++it) {
if (!str_.substr(pos_).starts_with(it->header))
continue;
StringPiece::size_type footer_pos = str_.find(it->footer, pos_);
if (footer_pos == StringPiece::npos) {
pos_ = StringPiece::npos;
return false;
}
StringPiece::size_type data_begin = pos_ + it->header.size();
pos_ = footer_pos + it->footer.size();
block_type_ = it->type;
StringPiece encoded = str_.substr(data_begin,
footer_pos - data_begin);
if (!base::Base64Decode(base::CollapseWhitespaceASCII(encoded.as_string(),
true), &data_)) {
break;
}
return true;
}
if (it == block_types_.end())
pos_ += sizeof(kPEMSearchBlock);
}
return false;
}
void PEMTokenizer::Init(
const StringPiece& str,
const std::vector<std::string>& allowed_block_types) {
str_ = str;
pos_ = 0;
for (std::vector<std::string>::const_iterator it =
allowed_block_types.begin(); it != allowed_block_types.end(); ++it) {
PEMType allowed_type;
allowed_type.type = *it;
allowed_type.header = base::StringPrintf(kPEMBeginBlock, it->c_str());
allowed_type.footer = base::StringPrintf(kPEMEndBlock, it->c_str());
block_types_.push_back(allowed_type);
}
}
}