AuroraRuntime/Source/Crypto/ECC/ECC.cpp
Reece cf70f0d45c [*/+/-] MEGA COMMIT. ~2 weeks compressed.
The intention is to quickly improve and add util apis, enhance functionality given current demands, go back to the build pipeline, finish that, publish runtime tests, and then use what we have to go back to to linux support with a more stable api.

[+] AuMakeSharedArray
[+] Technet ArgvQuote
[+] Grug subsystem (UNIX signal thread async safe ipc + telemetry flusher + log flusher.)
[+] auEndianness -> Endian swap utils
[+] AuGet<N>(...)
[*] AUE_DEFINE conversion for
        ECompresionType, EAnsiColor, EHashType, EStreamError, EHexDump
[+] ConsoleMessage ByteBuffer serialization
[+] CmdLine subsystem for parsing command line arguments and simple switch/flag checks
[*] Split logger from console subsystem
[+] StartupParameters -> A part of a clean up effort under Process
[*] Refactor SysErrors header + get caller hack
[+] Atomic APIs
[+] popcnt
[+] Ring Buffer sink
[+] Added more standard errors
        Catch,
        Submission,
        LockError,
        NoAccess,
        ResourceMissing,
        ResourceLocked,
        MalformedData,
        InSandboxContext,
        ParseError

[+] Added ErrorCategorySet, ErrorCategoryClear, GetStackTrace
[+] IExitSubscriber, ETriggerLevel
[*] Write bias the high performance RWLockImpl read-lock operation operation
[+] ExitHandlerAdd/ExitHandlerRemove (exit subsystem)
[*] Updated API style
        Digests
[+] CpuId::CpuBitCount
[+] GetUserProgramsFolder
[+] GetPackagePath
[*] Split IStreamReader with an inl file
[*] BlobWriter/BlobReader/BlobArbitraryReader can now take shared pointers to bytebuffers. default constructor allocates a new scalable bytebuffer
[+] ICharacterProvider
[+] ICharacterProviderEx
[+] IBufferedCharacterConsumer
[+] ProviderFromSharedString
[+] ProviderFromString
[+] BufferConsumerFromProvider
[*] Parse Subsystem uses character io bufferer
[*] Rewritten NT's high perf semaphore to use userland SRW/ConVars [like mutex, based on generic semaphore]
[+] ByteBuffer::ResetReadPointer
[*] Bug fix bytebuffer base not reset on free and some scaling issues
[+] ProcessMap -> Added kSectionNameStack, kSectionNameFile, kSectionNameHeap for Section
[*] ProcessMap -> Refactor Segment to Section. I was stupid for keeping a type conflict hack API facing
[+] Added 64 *byte* fast RNG seeds
[+] File Advisorys/File Lock Awareness
[+] Added extended IAuroraThread from OS identifier caches for debug purposes
[*] Tweaked how memory is reported on Windows. Better consistency of what values mean across functions.
[*] Broke AuroraUtils/Typedefs out into a separate library
[*] Update build script
[+] Put some more effort into adding detail to the readme before rewriting it, plus, added some media
[*] Improved public API documentation
[*] Bug fix `SetConsoleCtrlHandler`
[+] Locale TimeDateToFileNameISO8601
[+] Console config stdOutShortTime
[*] Begin using internal UTF8/16 decoders when platform support isnt available (instead of stl)
[*] Bug fixes in decoders
[*] Major bug fix, AuMax
[+] RateLimiter
[+] Binary file sink
[+] Log directory sink
[*] Data header usability (more operators)
[+] AuRemoveRange
[+] AuRemove
[+] AuTryRemove
[+] AuTryRemoveRange
[+] auCastUtils
[+] Finish NewLSWin32Source
[+] AuTryFindByTupleN, AuTryRemoveByTupleN
[+] Separated AuRead/Write types, now in auTypeUtils
[+] Added GetPosition/SetPosition to FileWriter
[*] Fix stupid AuMin in place of AuMax in SpawnThread.Unix.Cpp
[*] Refactored Arbitrary readers to SeekingReaders (as in, they could be atomic and/or parallelized, and accept an arbitrary position as a work parameter -> not Seekable, as in, you can simply set the position)
[*] Hack back in the sched deinit
[+] File AIO loop source interop
[+] Begin to prototype a LoopQueue object I had in mind for NT, untested btw
[+] Stub code for networking
[+] Compression BaseStream/IngestableStreamBase
[*] Major: read/write locks now support write-entrant read routines.
[*] Compression subsystem now uses the MemoryView concept
[*] Rewrite the base stream compressions, made them less broken
[*] Update hashing api
[*] WriterTryGoForward and ReaderTryGoForward now revert to the previous relative index instead of panicing
[+] Added new AuByteBuffer apis
    Trim, Pad, WriteFrom, WriteString, [TODO: ReadString]
[+] Added ByteBufferPushReadState
[+] Added ByteBufferPushWriteState
[*] Move from USC-16 to full UTF-16. Win32 can handle full UTF-16.
[*] ELogLevel is now an Aurora enum
[+] Raised arbitrary limit in header to 255, the max filter buffer
[+] Explicit GZip support
[+] Explicit Zip support
[+] Added [some] compressors

et al
2022-02-17 00:11:40 +00:00

255 lines
7.0 KiB
C++

/***
Copyright (C) 2021 J Reece Wilson (a/k/a "Reece"). All rights reserved.
File: ECC.cpp
Date: 2021-9-17
Author: Reece
***/
#include <Source/RuntimeInternal.hpp>
#include "ECC.hpp"
#include "ECCGeneric.hpp"
#include "ECCCurves.hpp"
#include "PublicECCImpl.hpp"
#include "PrivateECCImpl.hpp"
#include "ECCx25519Public.hpp"
#include "ECCX25519Private.hpp"
extern "C" int x509_decode_subject_public_key_info_2(const unsigned char *in, unsigned long inlen,
const unsigned long *oid,
void *parameters, unsigned long *parameters_len);
namespace Aurora::Crypto::ECC
{
static bool IsKeyGeneric(const void *ptr, AuUInt length, AuArray<unsigned long, 16> &curveOidm, unsigned long &oidLen)
{
const unsigned long oid[16]
{
1, 2, 840, 10045, 2, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
return x509_decode_subject_public_key_info_2((const unsigned char *)ptr, length, oid, curveOidm.data(), &oidLen) == CRYPT_OK;
}
static EECCCurve GetEdECCCurveType(const void *ptr, AuUInt length)
{
AuArray<unsigned long, 16> ec;
unsigned long ecLen;
if (IsKeyGeneric(ptr, length, ec, ecLen))
{
return OIDToCurve(ec.data(), ecLen);
}
return EECCCurve::kEnumInvalid;
}
static bool IsBlobCurveX25519(const void *ptr, AuUInt length)
{
const unsigned long oidX25519[16]
{
1, 3, 101, 110,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
return x509_decode_subject_public_key_info_2((const unsigned char *)ptr, length, oidX25519, NULL, 0) == CRYPT_OK;
}
static bool IsBlobCurveEd25519(const void *ptr, AuUInt length)
{
const unsigned long oidEd25519[16]
{
1, 3, 101, 112,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
return x509_decode_subject_public_key_info_2((const unsigned char *)ptr, length, oidEd25519, NULL, 0) == CRYPT_OK;
}
template<bool IsPublic, typename T>
static T New25519ECC(bool isX25519, const Memory::MemoryViewRead &pk, bool cert = false)
{
curve25519_key in {};
int ret;
if (cert)
{
if (!IsPublic)
{
SysPushErrorArg();
return nullptr;
}
ret = isX25519 ? x25519_import_x509(pk.Begin<const unsigned char>(), pk.length, &in) : ed25519_import_x509(pk.Begin<const unsigned char>(), pk.length, &in);
}
else
{
constexpr auto type = IsPublic ? PK_PUBLIC : PK_PRIVATE;
ret = isX25519 ? x25519_import_raw(pk.Begin<const unsigned char>(), pk.length, type, &in) : ed25519_import_raw(pk.Begin<const unsigned char>(), pk.length, type, &in);
}
if (ret != CRYPT_OK)
{
SysPushErrorCrypto("{}", ret);
return nullptr;
}
if constexpr (IsPublic)
{
return _new PublicCurve25519Impl(isX25519, AuMove(in));
}
else
{
return _new PrivateCurve25519Impl(isX25519, AuMove(in));
}
}
static IECCPrivate *Gen25519ECC(bool isX25519)
{
curve25519_key in {};
int ret;
const int prng_idx = register_prng(&sprng_desc);
ret = isX25519 ? x25519_make_key(NULL, prng_idx, &in) : ed25519_make_key(NULL, prng_idx, &in);
if (ret != CRYPT_OK)
{
SysPushErrorCrypto("{}", ret);
return nullptr;
}
return _new PrivateCurve25519Impl(isX25519, AuMove(in));
}
static void ReleasePublicECC(IECCPublic *pub)
{
switch (pub->GetType())
{
case EECCCurve::eCurveEd25519:
case EECCCurve::eCurveX25519:
AuSafeDelete<PublicCurve25519Impl *>(pub);
return;
default:
AuSafeDelete<PublicECCImpl *>(pub);
return;
}
}
static void ReleasePrivateECC(IECCPrivate *priv)
{
switch (priv->GetType())
{
case EECCCurve::eCurveEd25519:
case EECCCurve::eCurveX25519:
AuSafeDelete<PrivateCurve25519Impl *>(priv);
return;
default:
AuSafeDelete<PrivateECCImpl *>(priv);
return;
}
}
AUKN_SYM IECCPrivate *NewECC(EECCCurve curve)
{
switch (curve)
{
case EECCCurve::eCurveEd25519:
return Gen25519ECC(false);
case EECCCurve::eCurveX25519:
return Gen25519ECC(true);
default:
return GenerateNewGenericECC(curve).value_or(nullptr);
}
}
AUKN_SYM IECCPrivate *OpenPrivateECC(const AuMemoryViewRead &pk)
{
auto type = GetEdECCCurveType(pk.ptr, pk.length);
if (type != EECCCurve::eEnumInvalid)
{
if (auto ret = NewStdECC<PrivateECCImpl>(type, pk, false))
{
return ret;
}
}
if (IsBlobCurveX25519(pk.ptr, pk.length))
{
return New25519ECC<false, IECCPrivate*>(true, pk, false);
}
if (IsBlobCurveEd25519(pk.ptr, pk.length))
{
return New25519ECC<false, IECCPrivate *>(false, pk, false);
}
return {};
}
AUKN_SYM IECCPublic *OpenPublicECC(const AuMemoryViewRead &pk)
{
auto type = GetEdECCCurveType(pk.ptr, pk.length);
if (type != EECCCurve::eEnumInvalid)
{
if (auto ret = NewStdECC<PublicECCImpl>(type, pk, false))
{
return ret;
}
}
if (IsBlobCurveX25519(pk.ptr, pk.length))
{
return New25519ECC<true, IECCPublic *>(true, pk, false);
}
if (IsBlobCurveEd25519(pk.ptr, pk.length))
{
return New25519ECC<true, IECCPublic *>(false, pk, false);
}
return {};
}
AUKN_SYM IECCPublic *OpenPublicECCFromCert(const AuMemoryViewRead &certificate)
{
auto type = GetEdECCCurveType(certificate.ptr, certificate.length);
if (type != EECCCurve::eEnumInvalid)
{
if (auto ret = NewStdECC<PublicECCImpl>(type, certificate, true))
{
return ret;
}
}
if (IsBlobCurveX25519(certificate.ptr, certificate.length))
{
return New25519ECC<true, IECCPublic *>(true, certificate, true);
}
if (IsBlobCurveEd25519(certificate.ptr, certificate.length))
{
return New25519ECC<true, IECCPublic *>(false, certificate, true);
}
return {};
}
AUKN_SYM void NewECCRelease(IECCPrivate *priv)
{
ReleasePrivateECC(priv);
}
AUKN_SYM void OpenPrivateECCRelease(IECCPrivate *priv)
{
ReleasePrivateECC(priv);
}
AUKN_SYM void OpenPublicECCRelease(IECCPublic *pub)
{
ReleasePublicECC(pub);
}
AUKN_SYM void OpenPublicECCFromCertRelease(IECCPublic *pub)
{
ReleasePublicECC(pub);
}
}