AuroraRuntime/Source/Crypto/PEM/PEM.cpp

117 lines
3.3 KiB
C++

/***
Copyright (C) 2021 J Reece Wilson (a/k/a "Reece"). All rights reserved.
File: PEM.cpp
Date: 2021-6-12
Author: Reece
***/
#include <Source/RuntimeInternal.hpp>
#include "../Crypto.hpp"
#include "PEM.hpp"
namespace Aurora::Crypto::PEM
{
static bool ParsePEM(const AuString &begin, const AuString &end, const AuString &src, AuByteBuffer &buf)
{
AuUInt lines = 0;
AuString str;
int fail = 0;
bool finished = 0;
str.reserve(src.size());
Parse::SplitNewlines(src,
[&](const AuString &src)
{
if (lines == 0)
{
fail |= (int)(src != begin);
lines++;
return;
}
if (src == end)
{
fail |= (int)!Parse::Base64Decode(str, buf);
finished = true;
return;
}
str += src;
}
);
return fail ? false : finished;
}
static AuString SerializePEM(const AuString &begin, const AuString &end, const AuByteBuffer &buf)
{
auto delm = AuBuild::kCurrentVendor == AuBuild::EVendor::eGenericMicrosoft ? "\r\n" : "\n";
AuString ret;
ret += begin;
ret += delm;
AuString b64;
if (!Parse::Base64Encode(buf, b64))
{
return "";
}
else
{
b64 = Parse::SplitStringDelm(b64, delm, 16);
}
ret += b64;
ret += delm;
ret += end;
return ret;
}
AUKN_SYM AuString ToString(const Aurora::Crypto::X509::Certificate &in)
{
return SerializePEM("-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----", in);
}
AUKN_SYM AuString PrivateToString(const DerBuffer &in)
{
return SerializePEM("-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----", in);
}
AUKN_SYM AuString PublicToString(const DerBuffer &in)
{
return SerializePEM("-----BEGIN PUBLIC KEY-----", "-----END PUBLIC KEY-----", in);
}
AUKN_SYM AuString PublicRSAToString(const DerBuffer &in)
{
return SerializePEM("-----BEGIN RSA PUBLIC KEY-----", "-----END RSA PUBLIC KEY-----", in);
}
AUKN_SYM AuString PrivateRSAToString(const DerBuffer &in)
{
return SerializePEM("-----BEGIN RSA PRIVATE KEY-----", "-----END RSA PRIVATE KEY-----", in);
}
AUKN_SYM bool FromString(const AuString &in, Aurora::Crypto::X509::Certificate &out)
{
return ParsePEM("-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----", in, out);
}
AUKN_SYM bool PrivateFromString(const AuString &in, DerBuffer &out)
{
return ParsePEM("-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----", in, out);
}
AUKN_SYM bool PublicRSAFromString(const AuString &in, DerBuffer &out)
{
return ParsePEM("-----BEGIN RSA PUBLIC KEY-----", "-----END RSA PUBLIC KEY-----", in, out);
}
AUKN_SYM bool PrivateRSAFromString(const AuString &in, DerBuffer &out)
{
return ParsePEM("-----BEGIN RSA PRIVATE KEY-----", "-----END RSA PRIVATE KEY-----", in, out);
}
AUKN_SYM bool PublicFromString(const AuString &in, DerBuffer &out)
{
return ParsePEM("-----BEGIN PUBLIC KEY-----", "-----END PUBLIC KEY-----", in, out);
}
}