From 4b9690d9abc6d1dec75444dba615fd87508805b4 Mon Sep 17 00:00:00 2001 From: Jack Lloyd Date: Thu, 3 May 2018 22:41:07 -0400 Subject: Improve PEM detection for asn1 printer --- src/cli/asn1.cpp | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) (limited to 'src/cli') diff --git a/src/cli/asn1.cpp b/src/cli/asn1.cpp index 8a424aad8..65f38c060 100644 --- a/src/cli/asn1.cpp +++ b/src/cli/asn1.cpp @@ -9,6 +9,7 @@ #if defined(BOTAN_HAS_ASN1) #include +#include #if defined(BOTAN_HAS_PEM_CODEC) #include @@ -31,6 +32,18 @@ class ASN1_Printer final : public Command return "Decode and print file with ASN.1 Basic Encoding Rules (BER)"; } + bool first_n(const std::vector& data, size_t n, uint8_t b) + { + if(data.size() < n) + return false; + + for(size_t i = 0; i != n; ++i) + if(data[i] != b) + return false; + + return true; + } + void go() override { const std::string input = get_arg("file"); @@ -42,26 +55,30 @@ class ASN1_Printer final : public Command const size_t value_column = 60; const size_t initial_level = 0; - std::vector contents; + std::vector file_contents = slurp_file(input); + std::vector data; - if(flag_set("pem") || (input.size() > 4 && input.substr(input.size() - 4) == ".pem")) + if(flag_set("pem") || + (input.size() > 4 && input.substr(input.size() - 4) == ".pem") || + (file_contents.size() > 20 && first_n(file_contents, 5, '-'))) { #if defined(BOTAN_HAS_PEM_CODEC) std::string pem_label; - contents = unlock(Botan::PEM_Code::decode(slurp_file_as_str(input), pem_label)); + Botan::DataSource_Memory src(file_contents); + data = unlock(Botan::PEM_Code::decode(src, pem_label)); #else throw CLI_Error_Unsupported("PEM decoding not available in this build"); #endif } else { - contents = slurp_file(input); + data.swap(file_contents); } Botan::ASN1_Pretty_Printer printer(print_limit, bin_limit, print_context_specific, initial_level, value_column, max_depth); - printer.print_to_stream(output(), contents.data(), contents.size()); + printer.print_to_stream(output(), data.data(), data.size()); } }; -- cgit v1.2.3