From aba862f45cbde3debe99e31bc8ec3e338c5bbf4a Mon Sep 17 00:00:00 2001 From: Per Larsson Date: Mon, 7 Feb 2022 13:00:29 +0100 Subject: Replaced crypto transform abstraction with a concrete API. --- zencore/include/zencore/crypto.h | 67 ++++++++++++++++++++++++++++++---------- 1 file changed, 50 insertions(+), 17 deletions(-) (limited to 'zencore/include') diff --git a/zencore/include/zencore/crypto.h b/zencore/include/zencore/crypto.h index 44783cdeb..83d416b0f 100644 --- a/zencore/include/zencore/crypto.h +++ b/zencore/include/zencore/crypto.h @@ -7,36 +7,69 @@ #include #include +#include namespace zen { -/** - * Experimental interface for a symmetric encryption/decryption algorithm. - * Currenlty only AES 256 bit CBC is supported using OpenSSL. - */ -class SymmetricCipher +template +struct CryptoBits { public: - virtual ~SymmetricCipher() = default; + static constexpr size_t ByteCount = BitCount / 8; - virtual bool Initialize(MemoryView Key, MemoryView InitVector) = 0; + CryptoBits() = default; - struct CipherSettings + bool IsNull() const { return memcmp(&m_Bits, &Zero, ByteCount) == 0; } + bool IsValid() const { return IsNull() == false; } + + size_t GetSize() const { return ByteCount; } + size_t GetBitCount() const { return BitCount; } + + MemoryView GetView() const { return MemoryView(m_Bits, ByteCount); } + + static CryptoBits FromMemoryView(MemoryView Bits) { - size_t KeySize = 0; - size_t InitVectorSize = 0; - size_t BlockSize = 0; - }; + if (Bits.GetSize() != ByteCount) + { + return CryptoBits(); + } - virtual CipherSettings Settings() = 0; + return CryptoBits(Bits); + } + + static CryptoBits FromString(std::string_view Str) { return FromMemoryView(MakeMemoryView(Str)); } + +private: + CryptoBits(MemoryView Bits) + { + ZEN_ASSERT(Bits.GetSize() == GetSize()); + memcpy(&m_Bits, Bits.GetData(), GetSize()); + } - virtual MemoryView Encrypt(MemoryView Data, MutableMemoryView EncryptionBuffer) = 0; + static constexpr uint8_t Zero[ByteCount] = {0}; - virtual MemoryView Decrypt(MemoryView Data, MutableMemoryView DecryptionBuffer) = 0; + uint8_t m_Bits[ByteCount] = {0}; +}; + +using AesKey256Bit = CryptoBits<256>; +using AesIV128Bit = CryptoBits<128>; + +class Aes +{ +public: + static constexpr size_t BlockSize = 16; - static std::unique_ptr CreateNoOp(); + static MemoryView Encrypt(const AesKey256Bit& Key, + const AesIV128Bit& IV, + MemoryView In, + MutableMemoryView Out, + std::optional& Reason); - static std::unique_ptr CreateAes(); + static MemoryView Decrypt(const AesKey256Bit& Key, + const AesIV128Bit& IV, + MemoryView In, + MutableMemoryView Out, + std::optional& Reason); }; void crypto_forcelink(); -- cgit v1.2.3