diff --git a/Chaos/Cipher/Block/Decryptor.hpp b/Chaos/Cipher/Block/Decryptor.hpp new file mode 100644 index 0000000..ea90e7b --- /dev/null +++ b/Chaos/Cipher/Block/Decryptor.hpp @@ -0,0 +1,40 @@ +#ifndef CHAOS_CIPHER_BLOCK_DECRYPTOR_HPP +#define CHAOS_CIPHER_BLOCK_DECRYPTOR_HPP + +namespace Chaos::Cipher::Block +{ + +template +class Decryptor +{ +public: + template + void DecryptBlock(OutputIt out, InputIt inBegin, InputIt inEnd) + { + Impl().DecryptBlock(out, inBegin, inEnd); + } + + template + auto DecryptBlock(Block block) + { + return Impl().DecryptBlock(block); + } + +protected: + Decryptor() = default; + +private: + const T & Impl() const + { + return static_cast(*this); + } + + T & Impl() + { + return static_cast(*this); + } +}; + +} // namespace Chaos::Cipher::Block + +#endif // CHAOS_CIPHER_BLOCK_DECRYPTOR_HPP diff --git a/Chaos/Cipher/Block/Des/DesCrypt.hpp b/Chaos/Cipher/Block/Des/DesCrypt.hpp index d4a2c11..50b540d 100644 --- a/Chaos/Cipher/Block/Des/DesCrypt.hpp +++ b/Chaos/Cipher/Block/Des/DesCrypt.hpp @@ -8,6 +8,7 @@ #include "Service/SeArray.hpp" #include "Cipher/Block/Encryptor.hpp" +#include "Cipher/Block/Decryptor.hpp" namespace Chaos::Cipher::Block::Des::Inner_ { @@ -258,7 +259,7 @@ public: Inner_::KeySchedule Schedule_; }; - class DesDecryptor + class DesDecryptor : public Decryptor { public: DesDecryptor(const Key & key) diff --git a/ChaosTests/Cipher/DesCryptTests.cpp b/ChaosTests/Cipher/DesCryptTests.cpp index 6b16c80..f7e4139 100644 --- a/ChaosTests/Cipher/DesCryptTests.cpp +++ b/ChaosTests/Cipher/DesCryptTests.cpp @@ -537,3 +537,44 @@ TEST(DesCryptTests, EncryptUInt64BlockThroughBaseTest) ASSERT_EQ(expected, EncryptUInt64BlockThroughBase(enc, data)); } + +template +static std::array DecryptThroughBase(Decryptor & dec, + InputIt begin, InputIt end) +{ + std::array result; + dec.DecryptBlock(result.begin(), begin, end); + return result; +} + +TEST(DesCryptTests, DecryptThroughBaseTest) +{ + std::array key = { 0x13, 0x34, 0x57, 0x79, 0x9b, 0xbc, 0xdf, 0xf1 }; + + std::array data = { 0x85, 0xe8, 0x13, 0x54, 0x0f, 0x0a, 0xb4, 0x05 }; + std::array expected = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef }; + + DesCrypt::Key desKey(key.begin(), key.end()); + DesCrypt::DesDecryptor dec(desKey); + + ASSERT_EQ(expected, DecryptThroughBase(dec, data.begin(), data.end())); +} + +template +static uint64_t DecryptUInt64BlockThroughBase(Decryptor & dec, uint64_t block) +{ + return dec.DecryptBlock(block); +} + +TEST(DesCryptTests, DecryptUInt64BlockThroughBaseTest) +{ + std::array key = { 0x13, 0x34, 0x57, 0x79, 0x9b, 0xbc, 0xdf, 0xf1 }; + + uint64_t data = 0x85e813540f0ab405; + uint64_t expected = 0x0123456789abcdef; + + DesCrypt::Key desKey(key.begin(), key.end()); + DesCrypt::DesDecryptor dec(desKey); + + ASSERT_EQ(expected, DecryptUInt64BlockThroughBase(dec, data)); +}