summaryrefslogtreecommitdiff
path: root/Userland/Libraries
diff options
context:
space:
mode:
authorFabian Dellwing <fabian.dellwing@gmail.com>2023-04-01 21:20:29 +0200
committerAndrew Kaster <andrewdkaster@gmail.com>2023-04-03 19:58:47 -0600
commit8b881eaf026ff432e7edab7562cad46d94f23ab1 (patch)
tree0beb2a588f4dfd9cf2878a3ae6399146f0a91f63 /Userland/Libraries
parent7ce75ee3c5db93aa0e24d6dda6bd33be04222d3d (diff)
downloadserenity-8b881eaf026ff432e7edab7562cad46d94f23ab1.zip
LibCrypto: Add PEM encoder
This commit adds a new method to create a PEM encoded ASN1 from its DER variant.
Diffstat (limited to 'Userland/Libraries')
-rw-r--r--Userland/Libraries/LibCrypto/ASN1/PEM.cpp36
-rw-r--r--Userland/Libraries/LibCrypto/ASN1/PEM.h6
2 files changed, 42 insertions, 0 deletions
diff --git a/Userland/Libraries/LibCrypto/ASN1/PEM.cpp b/Userland/Libraries/LibCrypto/ASN1/PEM.cpp
index f682493f56..ec9fe526c6 100644
--- a/Userland/Libraries/LibCrypto/ASN1/PEM.cpp
+++ b/Userland/Libraries/LibCrypto/ASN1/PEM.cpp
@@ -93,4 +93,40 @@ ErrorOr<Vector<ByteBuffer>> decode_pems(ReadonlyBytes data)
return pems;
}
+ErrorOr<ByteBuffer> encode_pem(ReadonlyBytes data, PEMType type)
+{
+ ByteBuffer encoded;
+ StringView block_start;
+ StringView block_end;
+
+ switch (type) {
+ case Certificate:
+ block_start = "-----BEGIN CERTIFICATE-----\n"sv;
+ block_end = "-----END CERTIFICATE-----\n"sv;
+ break;
+ case PrivateKey:
+ block_start = "-----BEGIN PRIVATE KEY-----\n"sv;
+ block_end = "-----END PRIVATE KEY-----\n"sv;
+ break;
+ default:
+ VERIFY_NOT_REACHED();
+ }
+
+ auto b64encoded = TRY(encode_base64(data));
+
+ TRY(encoded.try_append(block_start.bytes()));
+
+ size_t to_read = 64;
+ for (size_t i = 0; i < b64encoded.bytes().size(); i += to_read) {
+ if (i + to_read > b64encoded.bytes().size())
+ to_read = b64encoded.bytes().size() - i;
+ TRY(encoded.try_append(b64encoded.bytes().slice(i, to_read)));
+ TRY(encoded.try_append("\n"sv.bytes()));
+ }
+
+ TRY(encoded.try_append(block_end.bytes()));
+
+ return encoded;
+}
+
}
diff --git a/Userland/Libraries/LibCrypto/ASN1/PEM.h b/Userland/Libraries/LibCrypto/ASN1/PEM.h
index 396a41fd05..15a1914852 100644
--- a/Userland/Libraries/LibCrypto/ASN1/PEM.h
+++ b/Userland/Libraries/LibCrypto/ASN1/PEM.h
@@ -12,7 +12,13 @@
namespace Crypto {
+enum PEMType {
+ Certificate,
+ PrivateKey,
+};
+
ByteBuffer decode_pem(ReadonlyBytes);
ErrorOr<Vector<ByteBuffer>> decode_pems(ReadonlyBytes);
+ErrorOr<ByteBuffer> encode_pem(ReadonlyBytes, PEMType = PEMType::Certificate);
}