AuroraRuntime/Source/Parse/Base64.cpp

84 lines
2.4 KiB
C++

/***
Copyright (C) 2021 J Reece Wilson (a/k/a "Reece"). All rights reserved.
File: Base64.cpp
Date: 2021-6-12
Author: Reece
***/
#include <Source/RuntimeInternal.hpp>
#include "Base64.hpp"
#include <tomcrypt.h>
namespace Aurora::Parse
{
AUKN_SYM bool Base64Decode(const AuString &in, AuByteBuffer &decoded, bool url)
{
int iRet;
unsigned long length = (unsigned long)in.size();
auto writeView = decoded.GetOrAllocateLinearWriteable(length);
if (!writeView)
{
SysPushErrorMem();
return {};
}
if (url)
{
iRet = ::base64url_decode(AuReinterpretCast<const char *>(decoded.writePtr),
(unsigned long)length,
AuReinterpretCast<unsigned char *>(&decoded[0]),
&length);
}
else
{
iRet = ::base64_decode(AuReinterpretCast<const char *>(decoded.writePtr),
(unsigned long)length,
AuReinterpretCast<unsigned char *>(&decoded[0]),
&length);
}
if (iRet != CRYPT_OK)
{
return false;
}
decoded.writePtr += length;
return true;
}
AUKN_SYM bool Base64Encode(const Memory::MemoryViewRead &input, AuString &encoded, bool url)
{
int iRet;
unsigned long outLength = input.length + (input.length / 3.0) + 16;
if (!AuTryResize(encoded, outLength))
{
SysPushErrorMem();
return false;
}
if (url)
{
iRet = ::base64url_encode(AuReinterpretCast<const unsigned char*>(input.ptr),
(unsigned long)input.length,
&encoded[0],
&outLength);
}
else
{
iRet =::base64_encode(AuReinterpretCast<const unsigned char*>(input.ptr),
(unsigned long)input.length,
&encoded[0],
&outLength);
}
if (!AuTryResize(encoded, outLength))
{
SysPushErrorMem();
return false;
}
return iRet == CRYPT_OK;
}
}