Skip to content

Commit

Permalink
LibCrypto: Add PEM encoder
Browse files Browse the repository at this point in the history
This commit adds a new method to create a PEM encoded ASN1 from
its DER variant.
  • Loading branch information
fdellwing authored and ADKaster committed Apr 4, 2023
1 parent 7ce75ee commit 8b881ea
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
36 changes: 36 additions & 0 deletions Userland/Libraries/LibCrypto/ASN1/PEM.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

}
6 changes: 6 additions & 0 deletions Userland/Libraries/LibCrypto/ASN1/PEM.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);

}

0 comments on commit 8b881ea

Please sign in to comment.