Skip to content

Commit d7dedbf

Browse files
authored
Add PEM codec (#1906)
1 parent 5868b83 commit d7dedbf

File tree

8 files changed

+275
-8
lines changed

8 files changed

+275
-8
lines changed

Packet++/CMakeLists.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ add_library(
3939
src/PacketTrailerLayer.cpp
4040
src/PacketUtils.cpp
4141
src/PayloadLayer.cpp
42+
src/PemCodec.cpp
4243
src/PPPoELayer.cpp
4344
src/RadiusLayer.cpp
4445
src/RawPacket.cpp
@@ -114,6 +115,7 @@ set(
114115
header/PacketTrailerLayer.h
115116
header/PacketUtils.h
116117
header/PayloadLayer.h
118+
header/PemCodec.h
117119
header/PPPoELayer.h
118120
header/ProtocolType.h
119121
header/RadiusLayer.h

Packet++/header/PemCodec.h

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
#pragma once
2+
3+
#include <cstdint>
4+
#include <string>
5+
#include <vector>
6+
7+
/// @file
8+
9+
/// @namespace pcpp
10+
/// @brief The main namespace for the PcapPlusPlus lib
11+
namespace pcpp
12+
{
13+
14+
/**
15+
* @class PemCodec
16+
* @brief A utility class for encoding and decoding data in Privacy-Enhanced Mail (PEM) format.
17+
*
18+
* The PemCodec class provides static methods to convert between binary data and PEM format, which is
19+
* commonly used for cryptographic keys, certificates, and other security-related data. The PEM format
20+
* uses base64 encoding with header and footer lines.
21+
*/
22+
class PemCodec
23+
{
24+
public:
25+
/**
26+
* Encodes binary data into PEM format with the specified label
27+
* @param[in] data The binary data to be encoded
28+
* @param[in] label The label to be used in the PEM header/footer (e.g., "CERTIFICATE", "PRIVATE KEY")
29+
* @return A string containing the PEM-encoded data with appropriate headers and line breaks
30+
* @throws std::invalid_argument if the input data is empty or the label is empty
31+
*/
32+
static std::string encode(const std::vector<uint8_t>& data, const std::string& label);
33+
34+
/**
35+
* Decodes PEM-encoded data back to its binary form
36+
* @param[in] pemData The PEM-encoded string to decode
37+
* @param[in] expectedLabel Optional expected label that should be in the PEM header/footer.
38+
* If provided and doesn't match, an exception will be thrown
39+
* @return A vector containing the decoded binary data
40+
* @throws std::invalid_argument if the input is not valid PEM format, if the label doesn't match or if base64
41+
* decoding fails
42+
*/
43+
static std::vector<uint8_t> decode(const std::string& pemData, const std::string& expectedLabel = "");
44+
45+
private:
46+
static constexpr const char* pemDelimiter = "-----";
47+
static constexpr const char* pemBegin = "-----BEGIN ";
48+
static constexpr const char* pemEnd = "-----END ";
49+
static constexpr size_t pemBeginLen = 11;
50+
static constexpr size_t pemEndLen = 9;
51+
static constexpr size_t pemDelimiterLen = 5;
52+
static constexpr size_t lineLength = 64;
53+
};
54+
} // namespace pcpp

Packet++/src/PemCodec.cpp

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
#include "PemCodec.h"
2+
#include "GeneralUtils.h"
3+
#include <sstream>
4+
#include <iostream>
5+
#include <algorithm>
6+
7+
namespace pcpp
8+
{
9+
std::string PemCodec::encode(const std::vector<uint8_t>& data, const std::string& label)
10+
{
11+
if (label.empty())
12+
{
13+
throw std::invalid_argument("PEM label cannot be empty");
14+
}
15+
16+
if (data.empty())
17+
{
18+
throw std::invalid_argument("PEM data cannot be empty");
19+
}
20+
21+
auto base64Str = Base64::encode(data);
22+
std::ostringstream oss;
23+
24+
oss << pemBegin << label << pemDelimiter << "\n";
25+
26+
auto base64StrSize = base64Str.size();
27+
for (size_t i = 0; i < base64StrSize; i += lineLength)
28+
{
29+
auto len = base64StrSize - i < lineLength ? base64StrSize - i : lineLength;
30+
oss.write(&base64Str[i], len);
31+
oss.put('\n');
32+
}
33+
34+
oss << pemEnd << label << pemDelimiter << "\n";
35+
return oss.str();
36+
}
37+
38+
std::vector<uint8_t> PemCodec::decode(const std::string& pemData, const std::string& expectedLabel)
39+
{
40+
std::istringstream iss(pemData);
41+
std::string line;
42+
std::string base64Data;
43+
std::string beginLabel, endLabel;
44+
bool inBody = false;
45+
46+
while (std::getline(iss, line))
47+
{
48+
line.erase(std::remove(line.begin(), line.end(), '\r'), line.end());
49+
50+
if (line.find(pemBegin) == 0)
51+
{
52+
if (inBody)
53+
{
54+
throw std::invalid_argument("Unexpected BEGIN while already inside a PEM block");
55+
}
56+
57+
beginLabel = line.substr(pemBeginLen, line.find(pemDelimiter, pemBeginLen) - pemBeginLen);
58+
if (beginLabel.empty())
59+
{
60+
throw std::invalid_argument("Invalid BEGIN label in PEM");
61+
}
62+
63+
if (!expectedLabel.empty() && beginLabel != expectedLabel)
64+
{
65+
throw std::invalid_argument("Unexpected BEGIN label in PEM - expected '" + expectedLabel +
66+
"' but got '" + beginLabel + "'");
67+
}
68+
69+
if (line.compare(line.size() - pemDelimiterLen, pemDelimiterLen, pemDelimiter) != 0)
70+
{
71+
throw std::invalid_argument("Invalid BEGIN suffix in PEM");
72+
}
73+
74+
inBody = true;
75+
continue;
76+
}
77+
78+
if (line.find(pemEnd) == 0)
79+
{
80+
if (!inBody)
81+
{
82+
throw std::invalid_argument("END found before BEGIN in PEM");
83+
}
84+
85+
endLabel = line.substr(pemEndLen, line.find(pemDelimiter, pemEndLen) - pemEndLen);
86+
if (endLabel != beginLabel)
87+
{
88+
throw std::invalid_argument("BEGIN and END labels do not match in PEM");
89+
}
90+
break;
91+
}
92+
93+
if (inBody && !line.empty())
94+
{
95+
base64Data += line;
96+
}
97+
}
98+
99+
if (beginLabel.empty() || endLabel.empty())
100+
{
101+
throw std::invalid_argument("Missing BEGIN or END in PEM data");
102+
}
103+
104+
if (base64Data.empty())
105+
{
106+
throw std::invalid_argument("No base64 content found in PEM data");
107+
}
108+
109+
return Base64::decodeToByteVector(base64Data);
110+
}
111+
} // namespace pcpp

README.md

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -278,14 +278,15 @@ PcapPlusPlus currently supports parsing, editing and creation of packets of the
278278
43. HTTP headers (request & response)
279279
44. LDAP
280280
45. NTP (v3, v4)
281-
46. Radius
282-
47. S7 Communication (S7comm)
283-
48. SMTP
284-
49. SOME/IP
285-
50. SSH - parsing only (no editing capabilities)
286-
51. Telnet - parsing only (no editing capabilities)
287-
52. X509 certificates - parsing only (no editing capabilities)
288-
53. Generic payload
281+
46. PEM decoder and encoder
282+
47. Radius
283+
48. S7 Communication (S7comm)
284+
49. SMTP
285+
50. SOME/IP
286+
51. SSH - parsing only (no editing capabilities)
287+
52. Telnet - parsing only (no editing capabilities)
288+
53. X509 certificates - parsing only (no editing capabilities)
289+
54. Generic payload
289290
290291
## DPDK And PF_RING Support
291292

Tests/Packet++Test/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ add_executable(
2727
Tests/NtpTests.cpp
2828
Tests/PacketTests.cpp
2929
Tests/PacketUtilsTests.cpp
30+
Tests/PemTests.cpp
3031
Tests/PPPoETests.cpp
3132
Tests/RadiusTests.cpp
3233
Tests/S7CommTests.cpp

Tests/Packet++Test/TestDefinition.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,3 +327,7 @@ PTF_TEST_CASE(X509ExtensionDataTest);
327327
// Implemented in Base64Tests.cpp
328328
PTF_TEST_CASE(Base64EncodingTest);
329329
PTF_TEST_CASE(Base64DecodingTest);
330+
331+
// Implemented in PemTests.cpp
332+
PTF_TEST_CASE(PemEncodingTest);
333+
PTF_TEST_CASE(PemDecodingTest);

Tests/Packet++Test/Tests/PemTests.cpp

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
#include "../TestDefinition.h"
2+
#include "PemCodec.h"
3+
4+
PTF_TEST_CASE(PemEncodingTest)
5+
{
6+
// Encode short vector
7+
{
8+
std::vector<uint8_t> data = { 0x10, 0x11, 0x12 };
9+
PTF_ASSERT_EQUAL(pcpp::PemCodec::encode(data, "LABEL"), "-----BEGIN LABEL-----\nEBES\n-----END LABEL-----\n");
10+
}
11+
12+
// Encode long vector
13+
{
14+
std::vector<uint8_t> data = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D,
15+
0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A,
16+
0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
17+
0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34,
18+
0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41,
19+
0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A };
20+
std::string expectedPem =
21+
"-----BEGIN LABEL-----\nAQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8w\nMTIzNDU2Nzg5Ojs8PT4/QEFCQ0RFRkdISUo=\n-----END LABEL-----\n";
22+
PTF_ASSERT_EQUAL(pcpp::PemCodec::encode(data, "LABEL"), expectedPem);
23+
}
24+
25+
// Invalid arguments
26+
{
27+
PTF_ASSERT_RAISES(pcpp::PemCodec::encode({ 0x10, 0x11, 0x12 }, ""), std::invalid_argument,
28+
"PEM label cannot be empty");
29+
PTF_ASSERT_RAISES(pcpp::PemCodec::encode({}, "LABEL"), std::invalid_argument, "PEM data cannot be empty");
30+
}
31+
}
32+
33+
PTF_TEST_CASE(PemDecodingTest)
34+
{
35+
// Decode a public key
36+
{
37+
std::string pem =
38+
"-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArkF7tOmIYqz7dST6kX6F\n8c9jB+DC7L5qvHApTyHyADTwXCNT4o3xppuzKOI5mlG8VK0yei4BIkUJXBfzts0j\nH7s5cQccpK0K4yOfoR2Isry43xwrchZnO6MAjH01/J7fMYwdKJkGdlUlAbFgYN2/\nyd5IK2SDAAPLWS4KzViR3TZn5leWBdrGyepAN31sONOBlxZ96pnF5BsCmokmVvct\nkocb8LKMMrDmSLchoOIzrrLaatYNmIM3uRkQWY0JpsPsA8zQLaDqsEO77JaSg2P9\nsfWF8CJOEVHQEFzbExXhsFzkb0Pr57G3PMkDmaR3aY/x/6Wsk8T1IkClnp84WFMQ\nGQIDAQAB\n-----END PUBLIC KEY-----\n";
39+
std::vector<uint8_t> expectedData = {
40+
0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05,
41+
0x00, 0x03, 0x82, 0x01, 0x0f, 0x00, 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, 0x00, 0xae, 0x41, 0x7b,
42+
0xb4, 0xe9, 0x88, 0x62, 0xac, 0xfb, 0x75, 0x24, 0xfa, 0x91, 0x7e, 0x85, 0xf1, 0xcf, 0x63, 0x07, 0xe0, 0xc2,
43+
0xec, 0xbe, 0x6a, 0xbc, 0x70, 0x29, 0x4f, 0x21, 0xf2, 0x00, 0x34, 0xf0, 0x5c, 0x23, 0x53, 0xe2, 0x8d, 0xf1,
44+
0xa6, 0x9b, 0xb3, 0x28, 0xe2, 0x39, 0x9a, 0x51, 0xbc, 0x54, 0xad, 0x32, 0x7a, 0x2e, 0x01, 0x22, 0x45, 0x09,
45+
0x5c, 0x17, 0xf3, 0xb6, 0xcd, 0x23, 0x1f, 0xbb, 0x39, 0x71, 0x07, 0x1c, 0xa4, 0xad, 0x0a, 0xe3, 0x23, 0x9f,
46+
0xa1, 0x1d, 0x88, 0xb2, 0xbc, 0xb8, 0xdf, 0x1c, 0x2b, 0x72, 0x16, 0x67, 0x3b, 0xa3, 0x00, 0x8c, 0x7d, 0x35,
47+
0xfc, 0x9e, 0xdf, 0x31, 0x8c, 0x1d, 0x28, 0x99, 0x06, 0x76, 0x55, 0x25, 0x01, 0xb1, 0x60, 0x60, 0xdd, 0xbf,
48+
0xc9, 0xde, 0x48, 0x2b, 0x64, 0x83, 0x00, 0x03, 0xcb, 0x59, 0x2e, 0x0a, 0xcd, 0x58, 0x91, 0xdd, 0x36, 0x67,
49+
0xe6, 0x57, 0x96, 0x05, 0xda, 0xc6, 0xc9, 0xea, 0x40, 0x37, 0x7d, 0x6c, 0x38, 0xd3, 0x81, 0x97, 0x16, 0x7d,
50+
0xea, 0x99, 0xc5, 0xe4, 0x1b, 0x02, 0x9a, 0x89, 0x26, 0x56, 0xf7, 0x2d, 0x92, 0x87, 0x1b, 0xf0, 0xb2, 0x8c,
51+
0x32, 0xb0, 0xe6, 0x48, 0xb7, 0x21, 0xa0, 0xe2, 0x33, 0xae, 0xb2, 0xda, 0x6a, 0xd6, 0x0d, 0x98, 0x83, 0x37,
52+
0xb9, 0x19, 0x10, 0x59, 0x8d, 0x09, 0xa6, 0xc3, 0xec, 0x03, 0xcc, 0xd0, 0x2d, 0xa0, 0xea, 0xb0, 0x43, 0xbb,
53+
0xec, 0x96, 0x92, 0x83, 0x63, 0xfd, 0xb1, 0xf5, 0x85, 0xf0, 0x22, 0x4e, 0x11, 0x51, 0xd0, 0x10, 0x5c, 0xdb,
54+
0x13, 0x15, 0xe1, 0xb0, 0x5c, 0xe4, 0x6f, 0x43, 0xeb, 0xe7, 0xb1, 0xb7, 0x3c, 0xc9, 0x03, 0x99, 0xa4, 0x77,
55+
0x69, 0x8f, 0xf1, 0xff, 0xa5, 0xac, 0x93, 0xc4, 0xf5, 0x22, 0x40, 0xa5, 0x9e, 0x9f, 0x38, 0x58, 0x53, 0x10,
56+
0x19, 0x02, 0x03, 0x01, 0x00, 0x01
57+
};
58+
auto decodedData = pcpp::PemCodec::decode(pem, "PUBLIC KEY");
59+
PTF_ASSERT_TRUE(decodedData == expectedData);
60+
}
61+
62+
// Decode short data
63+
{
64+
std::string pem = "-----BEGIN LABEL-----\nERIT\n-----END LABEL-----\n";
65+
std::vector<uint8_t> expectedData = { 0x11, 0x12, 0x13 };
66+
auto decodedData = pcpp::PemCodec::decode(pem);
67+
PTF_ASSERT_TRUE(decodedData == expectedData);
68+
}
69+
70+
// Invalid data
71+
{
72+
PTF_ASSERT_RAISES(pcpp::PemCodec::decode(""), std::invalid_argument, "Missing BEGIN or END in PEM data");
73+
PTF_ASSERT_RAISES(pcpp::PemCodec::decode("foo"), std::invalid_argument, "Missing BEGIN or END in PEM data");
74+
PTF_ASSERT_RAISES(pcpp::PemCodec::decode("-----BEGIN FOO-----\nERIT\n-----END FOO-----\n", "LABEL"),
75+
std::invalid_argument, "Unexpected BEGIN label in PEM - expected 'LABEL' but got 'FOO'");
76+
PTF_ASSERT_RAISES(pcpp::PemCodec::decode("-----BEGIN LABEL-----\nabc\n-----BEGIN LABEL-----\n"),
77+
std::invalid_argument, "Unexpected BEGIN while already inside a PEM block");
78+
PTF_ASSERT_RAISES(pcpp::PemCodec::decode("-----BEGIN -----"), std::invalid_argument,
79+
"Invalid BEGIN label in PEM");
80+
PTF_ASSERT_RAISES(pcpp::PemCodec::decode("-----BEGIN foo\nbar"), std::invalid_argument,
81+
"Invalid BEGIN suffix in PEM");
82+
PTF_ASSERT_RAISES(pcpp::PemCodec::decode("-----END LABEL-----\nfoo"), std::invalid_argument,
83+
"END found before BEGIN in PEM");
84+
PTF_ASSERT_RAISES(pcpp::PemCodec::decode("-----BEGIN L1-----\nERIT\n-----END L2-----\n"), std::invalid_argument,
85+
"BEGIN and END labels do not match in PEM");
86+
PTF_ASSERT_RAISES(pcpp::PemCodec::decode("-----BEGIN LABEL-----\n-----END LABEL-----\n"), std::invalid_argument,
87+
"No base64 content found in PEM data");
88+
PTF_ASSERT_RAISES(pcpp::PemCodec::decode("-----BEGIN LABEL-----\nfoo\n-----END LABEL-----\n"),
89+
std::invalid_argument, "Invalid base64 encoded data - Size not divisible by 4");
90+
}
91+
}

Tests/Packet++Test/main.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -392,5 +392,8 @@ int main(int argc, char* argv[])
392392
PTF_RUN_TEST(Base64EncodingTest, "base64");
393393
PTF_RUN_TEST(Base64DecodingTest, "base64");
394394

395+
PTF_RUN_TEST(PemEncodingTest, "pem");
396+
PTF_RUN_TEST(PemDecodingTest, "pem");
397+
395398
PTF_END_RUNNING_TESTS;
396399
}

0 commit comments

Comments
 (0)