AuroraRuntime/Source/Parse/AuBase64.cpp

84 lines
2.4 KiB
C++
Raw Normal View History

2021-06-27 21:25:29 +00:00
/***
Copyright (C) 2021 J Reece Wilson (a/k/a "Reece"). All rights reserved.
2022-11-17 07:46:07 +00:00
File: AuBase64.cpp
2021-06-27 21:25:29 +00:00
Date: 2021-6-12
Author: Reece
***/
2021-09-30 14:57:41 +00:00
#include <Source/RuntimeInternal.hpp>
2022-11-17 07:46:07 +00:00
#include "AuBase64.hpp"
2021-06-27 21:25:29 +00:00
#include <tomcrypt.h>
namespace Aurora::Parse
{
2022-11-17 07:46:07 +00:00
AUKN_SYM bool Base64Decode(const AuString &in, AuByteBuffer &decoded, bool bUrl)
2021-06-27 21:25:29 +00:00
{
2022-09-19 20:34:54 +00:00
int iRet;
2022-11-17 07:46:07 +00:00
unsigned long uLength = (unsigned long)in.size();
2022-11-17 07:46:07 +00:00
auto writeView = decoded.GetOrAllocateLinearWriteable(uLength);
if (!writeView)
2021-06-27 21:25:29 +00:00
{
SysPushErrorMem();
return {};
}
2021-06-27 21:25:29 +00:00
2022-11-17 07:46:07 +00:00
if (bUrl)
{
2022-09-19 20:34:54 +00:00
iRet = ::base64url_decode(AuReinterpretCast<const char *>(decoded.writePtr),
2022-11-17 07:46:07 +00:00
(unsigned long)uLength,
2022-09-19 20:34:54 +00:00
AuReinterpretCast<unsigned char *>(&decoded[0]),
2022-11-17 07:46:07 +00:00
&uLength);
}
else
{
2022-09-19 20:34:54 +00:00
iRet = ::base64_decode(AuReinterpretCast<const char *>(decoded.writePtr),
2022-11-17 07:46:07 +00:00
(unsigned long)uLength,
2022-09-19 20:34:54 +00:00
AuReinterpretCast<unsigned char *>(&decoded[0]),
2022-11-17 07:46:07 +00:00
&uLength);
2022-09-19 20:34:54 +00:00
}
if (iRet != CRYPT_OK)
{
return false;
2021-06-27 21:25:29 +00:00
}
2022-11-17 07:46:07 +00:00
decoded.writePtr += uLength;
2022-09-19 20:34:54 +00:00
return true;
2021-06-27 21:25:29 +00:00
}
2022-11-17 07:46:07 +00:00
AUKN_SYM bool Base64Encode(const Memory::MemoryViewRead &input, AuString &encoded, bool bUrl)
2021-06-27 21:25:29 +00:00
{
2022-09-19 20:34:54 +00:00
int iRet;
2022-11-17 07:46:07 +00:00
unsigned long uOutLength = input.length + (input.length / 3.0) + 16;
2021-06-27 21:25:29 +00:00
2022-11-17 07:46:07 +00:00
if (!AuTryResize(encoded, uOutLength))
{
SysPushErrorMem();
return false;
}
2021-06-27 21:25:29 +00:00
2022-11-17 07:46:07 +00:00
if (bUrl)
{
2022-09-19 20:34:54 +00:00
iRet = ::base64url_encode(AuReinterpretCast<const unsigned char*>(input.ptr),
(unsigned long)input.length,
&encoded[0],
2022-11-17 07:46:07 +00:00
&uOutLength);
2021-06-27 21:25:29 +00:00
}
else
2021-06-27 21:25:29 +00:00
{
2022-11-17 07:46:07 +00:00
iRet = ::base64_encode(AuReinterpretCast<const unsigned char*>(input.ptr),
(unsigned long)input.length,
&encoded[0],
&uOutLength);
}
2022-11-17 07:46:07 +00:00
if (!AuTryResize(encoded, uOutLength))
{
SysPushErrorMem();
2021-06-27 21:25:29 +00:00
return false;
}
2022-09-19 20:34:54 +00:00
return iRet == CRYPT_OK;
2021-06-27 21:25:29 +00:00
}
}