2021-02-14 11:20:42 +00:00
|
|
|
/*
|
|
|
|
* Copyright (c) 2021, the SerenityOS developers.
|
|
|
|
*
|
2021-04-22 08:24:48 +00:00
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
2021-02-14 11:20:42 +00:00
|
|
|
*/
|
|
|
|
|
|
|
|
#include <AK/Base64.h>
|
|
|
|
#include <AK/GenericLexer.h>
|
|
|
|
#include <LibCrypto/ASN1/PEM.h>
|
|
|
|
|
|
|
|
namespace Crypto {
|
|
|
|
|
|
|
|
ByteBuffer decode_pem(ReadonlyBytes data)
|
|
|
|
{
|
|
|
|
GenericLexer lexer { data };
|
|
|
|
ByteBuffer decoded;
|
|
|
|
|
|
|
|
// FIXME: Parse multiple.
|
|
|
|
enum {
|
|
|
|
PreStartData,
|
|
|
|
Started,
|
|
|
|
Ended,
|
|
|
|
} state { PreStartData };
|
|
|
|
while (!lexer.is_eof()) {
|
|
|
|
switch (state) {
|
|
|
|
case PreStartData:
|
|
|
|
if (lexer.consume_specific("-----BEGIN"))
|
|
|
|
state = Started;
|
|
|
|
lexer.consume_line();
|
|
|
|
break;
|
|
|
|
case Started: {
|
|
|
|
if (lexer.consume_specific("-----END")) {
|
|
|
|
state = Ended;
|
|
|
|
lexer.consume_line();
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
auto b64decoded = decode_base64(lexer.consume_line().trim_whitespace(TrimMode::Right));
|
2021-10-23 13:43:59 +00:00
|
|
|
if (!b64decoded.has_value()) {
|
|
|
|
dbgln("Failed to decode PEM, likely bad Base64");
|
|
|
|
return {};
|
|
|
|
}
|
2021-11-10 13:33:44 +00:00
|
|
|
if (decoded.try_append(b64decoded.value().data(), b64decoded.value().size()).is_error()) {
|
2021-09-05 22:58:46 +00:00
|
|
|
dbgln("Failed to decode PEM, likely OOM condition");
|
|
|
|
return {};
|
|
|
|
}
|
2021-02-14 11:20:42 +00:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
case Ended:
|
|
|
|
lexer.consume_all();
|
|
|
|
break;
|
|
|
|
default:
|
2021-02-23 19:42:32 +00:00
|
|
|
VERIFY_NOT_REACHED();
|
2021-02-14 11:20:42 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return decoded;
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|