From e397f9eeebdb0c38e0edeb1ea5eecd00b71ab58c Mon Sep 17 00:00:00 2001 From: barrier Date: Wed, 17 Dec 2025 12:55:20 +0900 Subject: [PATCH 01/21] =?UTF-8?q?pull=20request=E3=81=AB=E5=A4=A7=E5=A4=89?= =?UTF-8?q?=E6=84=9F=E8=AC=9D=E3=81=97=E3=81=AA=E3=81=8C=E3=82=89=E3=80=81?= =?UTF-8?q?=E5=AE=9A=E6=95=B0=E8=A8=88=E7=AE=97=E3=81=A7=E3=81=8D=E3=81=AA?= =?UTF-8?q?=E3=81=84=E3=81=A8=E3=81=95=E3=82=8C=E3=81=9F=E9=83=A8=E5=88=86?= =?UTF-8?q?=E3=82=92=E4=BF=AE=E6=AD=A3=20=E3=81=A4=E3=81=84=E3=81=A7?= =?UTF-8?q?=E3=81=ABAES=E3=81=AE=E3=82=B3=E3=83=B3=E3=82=B9=E3=83=88?= =?UTF-8?q?=E3=83=A9=E3=82=AF=E3=82=BF=E3=82=92=E5=AE=8C=E5=85=A8=E3=81=AB?= =?UTF-8?q?=E5=AE=9A=E6=95=B0=E8=A8=88=E7=AE=97=E5=AF=BE=E5=BF=9C=E3=81=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/Cryptgraphy/AES128.h | 25 +++++++++++++++++-------- include/Cryptgraphy/MultiWordInt.h | 8 +++++--- include/Cryptgraphy/SHAKE256.h | 12 +++++++----- 3 files changed, 29 insertions(+), 16 deletions(-) diff --git a/include/Cryptgraphy/AES128.h b/include/Cryptgraphy/AES128.h index e6f262c..7967385 100644 --- a/include/Cryptgraphy/AES128.h +++ b/include/Cryptgraphy/AES128.h @@ -248,13 +248,22 @@ class AES128 { constexpr block_t(word_t from) noexcept { m_words[0] = from; } constexpr block_t(const cbytearray& from) noexcept { m_bytes = from; } constexpr block_t(cbytearray&& from) noexcept { m_bytes = std::move(from); } - block_t(byte_view from) noexcept { std::memcpy(m_bytes.data(), from.data(), std::min(from.size(), block_size)); } - block_t(const bytearray& from) noexcept : block_t(byte_view(from)) {} - block_t(bytearray&& from) noexcept : block_t(byte_view(from)) {} + constexpr block_t(byte_view from) noexcept { + auto it = std::bit_cast(m_bytes.data()); + auto end = std::bit_cast(m_bytes.data() + block_size); + for (auto&& c : from) { + *it = c; + if (++it == end) { + break; + } + } + } + constexpr block_t(const bytearray& from) noexcept : block_t(byte_view(from)) {} + constexpr block_t(bytearray&& from) noexcept : block_t(byte_view(from)) {} constexpr block_t(const block_t&) noexcept = default; constexpr block_t(block_t&&) noexcept = default; - block_t Reverse() const { + constexpr block_t Reverse() const { block_t ret = *this; std::reverse(ret.m_bytes.begin(), ret.m_bytes.end()); return ret; @@ -733,10 +742,10 @@ class AES128 { mixcolumn(b.m_byte4s[i], b.m_int4[i]); } } - constexpr static void invmixcolumn(const typename block_t::byte4_t& r, uint32_t& dest)noexcept { + constexpr static void invmixcolumn(const typename block_t::byte4_t& r, uint32_t& dest) noexcept { dest = InvColumnTable[0][r[0]] ^ InvColumnTable[1][r[1]] ^ InvColumnTable[2][r[2]] ^ InvColumnTable[3][r[3]]; } - constexpr static void invmixcolumns(block_t& b)noexcept { + constexpr static void invmixcolumns(block_t& b) noexcept { constexpr size_t loop = sizeof(block_t::byte4_t) / sizeof(byte_t); for (size_t i = 0; i < loop; ++i) { invmixcolumn(b.m_byte4s[i], b.m_int4[i]); @@ -745,10 +754,10 @@ class AES128 { constexpr static void addroundkey(block_t& s, const block_t& rk)noexcept { s ^= rk; } - constexpr static void rotword(uint32_t& w)noexcept { + constexpr static void rotword(uint32_t& w) noexcept { w = ROR(w, 8); } - constexpr static void subword(uint32_t& w)noexcept { + constexpr static void subword(uint32_t& w) noexcept { w = (static_cast(SBox[(w >> 0) & 0xff]) << 0) | (static_cast(SBox[(w >> 8) & 0xff]) << 8) | (static_cast(SBox[(w >> 16) & 0xff]) << 16) | diff --git a/include/Cryptgraphy/MultiWordInt.h b/include/Cryptgraphy/MultiWordInt.h index 48c9379..bb020ab 100644 --- a/include/Cryptgraphy/MultiWordInt.h +++ b/include/Cryptgraphy/MultiWordInt.h @@ -68,7 +68,7 @@ struct bigint { constexpr count_t totalbytes = WordBytes; const count_t copycount = (arr.size() * sizeof(T) < totalbytes) ? arr.size() : totalbytes / sizeof(T); std::fill(words().begin(), words().end(), 0); - auto it = reinterpret_cast(words().data()); // TODO: resolve potential undefined behavior + auto it = std::bit_cast(words().data()); // TODO: resolve potential undefined behavior auto end = it + copycount; for (auto&& elem : arr) { *it = elem; @@ -634,10 +634,12 @@ struct bigint { constexpr arr_t& words() { return *m_words; } constexpr const arr_t& words() const { return *m_words; } constexpr bits_t& bits() { - return *reinterpret_cast(m_words->data()); // TODO: resolve potential undefined behavior + return *std::bit_cast(m_words->data()); // TODO: resolve potential undefined behavior + // NOTE: temporary fix } constexpr const bits_t& bits() const { - return *reinterpret_cast(m_words->data()); // TODO: resolve potential undefined behavior + return *std::bit_cast(m_words->data()); // TODO: resolve potential undefined behavior + // NOTE: temporary fix } private: diff --git a/include/Cryptgraphy/SHAKE256.h b/include/Cryptgraphy/SHAKE256.h index 293653d..9aa09da 100644 --- a/include/Cryptgraphy/SHAKE256.h +++ b/include/Cryptgraphy/SHAKE256.h @@ -18,9 +18,9 @@ class SHAKE256 { struct state { constexpr state() {} - constexpr state(const bytearray& from) { - auto it = reinterpret_cast(m_words.data()); // NOTE: not constexpr - auto end = reinterpret_cast(m_words.data() + b); // NOTE: not constexpr + constexpr state(byte_view from) { + auto it = std::bit_cast(m_words.data()); + auto end = std::bit_cast(m_words.data() + b); for (auto&& c : from) { *it = c; if (++it == end) { @@ -28,6 +28,8 @@ class SHAKE256 { } } } + constexpr state(const bytearray& from) : state(byte_view(from)) {} + constexpr state(bytearray&& from) : state(byte_view(from)) {} struct reference { friend state; @@ -58,7 +60,7 @@ class SHAKE256 { return *ptr & posword(); } constexpr bool operator~() const { - return !*this; + return !(*this); } constexpr void flip() { *this = ~(*this); @@ -90,7 +92,7 @@ class SHAKE256 { bytearray ret; ret.reserve(sizeof(m_words)); for (size_t i = 0, c = sizeof(m_words); i < c; ++i) { - ret.push_back(*(reinterpret_cast(m_words.data()) + i)); // NOTE: not constexpr + ret.push_back(*(std::bit_cast(m_words.data()) + i)); // NOTE: but temporary fix } return ret; } From 014728541759c7522b1c94e245412ea789e67dc0 Mon Sep 17 00:00:00 2001 From: barrier Date: Wed, 17 Dec 2025 12:59:38 +0900 Subject: [PATCH 02/21] =?UTF-8?q?=E6=9B=96=E6=98=A7=E3=81=AA=E3=82=B3?= =?UTF-8?q?=E3=83=B3=E3=82=B9=E3=83=88=E3=83=A9=E3=82=AF=E3=82=BF=E3=82=92?= =?UTF-8?q?=E4=BD=BF=E3=81=A3=E3=81=A6=E3=81=9F=E9=83=A8=E5=88=86=E3=82=92?= =?UTF-8?q?=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/Cryptgraphy/SHAKE256.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/Cryptgraphy/SHAKE256.h b/include/Cryptgraphy/SHAKE256.h index 9aa09da..bee4d2e 100644 --- a/include/Cryptgraphy/SHAKE256.h +++ b/include/Cryptgraphy/SHAKE256.h @@ -238,7 +238,7 @@ class SHAKE256 { byte_view t(P.begin() + (i * r_8), r_8); state pS = S; - state ps = {{t.begin(), t.end()}}; + state ps = static_cast(t); for (size_t y = 0; y < 5; ++y) { for (size_t x = 0; x < 5; ++x) { From 33b5c59c2b3021750aa6b078d503c308293e2172 Mon Sep 17 00:00:00 2001 From: barrier Date: Wed, 17 Dec 2025 13:19:26 +0900 Subject: [PATCH 03/21] =?UTF-8?q?=E3=82=AD=E3=83=A3=E3=82=B9=E3=83=88?= =?UTF-8?q?=E6=8A=9C=E3=81=91=E3=82=92=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/Cryptgraphy/SHAKE256.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/include/Cryptgraphy/SHAKE256.h b/include/Cryptgraphy/SHAKE256.h index bee4d2e..df66ad9 100644 --- a/include/Cryptgraphy/SHAKE256.h +++ b/include/Cryptgraphy/SHAKE256.h @@ -92,7 +92,7 @@ class SHAKE256 { bytearray ret; ret.reserve(sizeof(m_words)); for (size_t i = 0, c = sizeof(m_words); i < c; ++i) { - ret.push_back(*(std::bit_cast(m_words.data()) + i)); // NOTE: but temporary fix + ret.push_back(*(std::bit_cast(m_words.data()) + i)); } return ret; } @@ -194,10 +194,10 @@ class SHAKE256 { for (size_t j = 0; j <= l; ++j) { size_t idx = ((static_cast(1) << j) - 1); if (rc(j + 7 * ir)) { - RC |= (word_t)1 << idx; + RC |= static_cast(1) << idx; } else { - RC &= ~((word_t)1 << idx); + RC &= ~(static_cast(1) << idx); } } @@ -215,7 +215,7 @@ class SHAKE256 { for (size_t i = 12 + 2 * l - nr, c = 12 + 2 * l; i != c; ++i) { A = Round(A, i); } - return (bytearray)A; + return static_cast(A); } static constexpr bytearray SPONGE(const bytearray& N, size_t outlen) { constexpr size_t r_8 = r / 8; From b802bc91f35b23f8a903a56d3770b41aca81ce28 Mon Sep 17 00:00:00 2001 From: barrier Date: Wed, 17 Dec 2025 13:39:59 +0900 Subject: [PATCH 04/21] =?UTF-8?q?ROR=E3=83=9E=E3=82=AF=E3=83=AD=E3=81=A8?= =?UTF-8?q?=E8=87=AA=E4=BD=9C=E9=96=A2=E6=95=B0=E3=82=92=E6=B6=88=E5=8E=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/Cryptgraphy/AES128.h | 62 +++++++++++++----------------------- 1 file changed, 23 insertions(+), 39 deletions(-) diff --git a/include/Cryptgraphy/AES128.h b/include/Cryptgraphy/AES128.h index 7967385..95c28b8 100644 --- a/include/Cryptgraphy/AES128.h +++ b/include/Cryptgraphy/AES128.h @@ -1,21 +1,7 @@ #pragma once #include "common.h" -static constexpr size_t _bit_width(uint64_t test) noexcept { - constexpr size_t bits = sizeof(size_t) * 8; - constexpr size_t testmask = size_t(1) << (bits - 1); - for (size_t i = 1; i < bits; ++i) { - if ((test << i) & testmask) { - return bits - i; - } - } - return bits; -} - class AES128 { - -#define ROR(v, s) (((v) >> (s)) | ((v) << (32 - s))) - public: using byte_t = Cryptgraphy::byte_t; @@ -29,7 +15,7 @@ class AES128 { static constexpr size_t block_size = 0x10; static constexpr size_t block_size_mask = block_size - 1; - static constexpr size_t block_size_shift = _bit_width(block_size_mask); + static constexpr size_t block_size_shift = std::bit_width(block_size_mask); static constexpr byte_t RCon[11] = { 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36 @@ -685,85 +671,85 @@ class AES128 { private: - constexpr static void subbytes(block_t& b) noexcept { + static constexpr void subbytes(block_t& b) noexcept { for (size_t i = 0; i < block_size; ++i) { b[i] = SBox[b[i]]; } } - constexpr static void invsubbytes(block_t& b) noexcept { + static constexpr void invsubbytes(block_t& b) noexcept { for (size_t i = 0; i < block_size; ++i) { b[i] = InvSBox[b[i]]; } } - constexpr static void shiftrows(block_t& b) noexcept { + static constexpr void shiftrows(block_t& b) noexcept { block_t t = b; b.m_byte4s[0][1] = t.m_byte4s[1][1]; b.m_byte4s[0][2] = t.m_byte4s[2][2]; b.m_byte4s[0][3] = t.m_byte4s[3][3]; - + b.m_byte4s[1][1] = t.m_byte4s[2][1]; b.m_byte4s[1][2] = t.m_byte4s[3][2]; b.m_byte4s[1][3] = t.m_byte4s[0][3]; - + b.m_byte4s[2][1] = t.m_byte4s[3][1]; b.m_byte4s[2][2] = t.m_byte4s[0][2]; b.m_byte4s[2][3] = t.m_byte4s[1][3]; - + b.m_byte4s[3][1] = t.m_byte4s[0][1]; b.m_byte4s[3][2] = t.m_byte4s[1][2]; b.m_byte4s[3][3] = t.m_byte4s[2][3]; } - constexpr static void invshiftrows(block_t& b) noexcept { + static constexpr void invshiftrows(block_t& b) noexcept { block_t t = b; b.m_byte4s[0][1] = t.m_byte4s[3][1]; b.m_byte4s[0][2] = t.m_byte4s[2][2]; b.m_byte4s[0][3] = t.m_byte4s[1][3]; - + b.m_byte4s[1][1] = t.m_byte4s[0][1]; b.m_byte4s[1][2] = t.m_byte4s[3][2]; b.m_byte4s[1][3] = t.m_byte4s[2][3]; - + b.m_byte4s[2][1] = t.m_byte4s[1][1]; b.m_byte4s[2][2] = t.m_byte4s[0][2]; b.m_byte4s[2][3] = t.m_byte4s[3][3]; - + b.m_byte4s[3][1] = t.m_byte4s[2][1]; b.m_byte4s[3][2] = t.m_byte4s[1][2]; b.m_byte4s[3][3] = t.m_byte4s[0][3]; } - constexpr static void mixcolumn(const typename block_t::byte4_t& r, uint32_t& dest) noexcept { + static constexpr void mixcolumn(const typename block_t::byte4_t& r, uint32_t& dest) noexcept { dest = ColumnTable[0][r[0]] ^ ColumnTable[1][r[1]] ^ ColumnTable[2][r[2]] ^ ColumnTable[3][r[3]]; } - constexpr static void mixcolumns(block_t& b) noexcept { + static constexpr void mixcolumns(block_t& b) noexcept { constexpr size_t loop = sizeof(block_t::byte4_t) / sizeof(byte_t); for (size_t i = 0; i < loop; ++i) { mixcolumn(b.m_byte4s[i], b.m_int4[i]); } } - constexpr static void invmixcolumn(const typename block_t::byte4_t& r, uint32_t& dest) noexcept { + static constexpr void invmixcolumn(const typename block_t::byte4_t& r, uint32_t& dest) noexcept { dest = InvColumnTable[0][r[0]] ^ InvColumnTable[1][r[1]] ^ InvColumnTable[2][r[2]] ^ InvColumnTable[3][r[3]]; } - constexpr static void invmixcolumns(block_t& b) noexcept { + static constexpr void invmixcolumns(block_t& b) noexcept { constexpr size_t loop = sizeof(block_t::byte4_t) / sizeof(byte_t); for (size_t i = 0; i < loop; ++i) { invmixcolumn(b.m_byte4s[i], b.m_int4[i]); } } - constexpr static void addroundkey(block_t& s, const block_t& rk)noexcept { + static constexpr void addroundkey(block_t& s, const block_t& rk)noexcept { s ^= rk; } - constexpr static void rotword(uint32_t& w) noexcept { - w = ROR(w, 8); + static constexpr void rotword(uint32_t& w) noexcept { + w = std::rotr(w, 8); } - constexpr static void subword(uint32_t& w) noexcept { + static constexpr void subword(uint32_t& w) noexcept { w = (static_cast(SBox[(w >> 0) & 0xff]) << 0) | (static_cast(SBox[(w >> 8) & 0xff]) << 8) | (static_cast(SBox[(w >> 16) & 0xff]) << 16) | (static_cast(SBox[(w >> 24) & 0xff]) << 24); } - constexpr static roundkeys _KeyExpansion(const block_t& key) noexcept { + static constexpr roundkeys _KeyExpansion(const block_t& key) noexcept { constexpr size_t startwords = block_size / sizeof(uint32_t); roundkeys rk{}; rk[0] = key; @@ -774,7 +760,7 @@ class AES128 { while (wordgenerated < itercount) { constexpr size_t mask = (sizeof(uint32_t) - 1); - constexpr size_t shift = _bit_width(sizeof(uint32_t) - 1); + constexpr size_t shift = std::bit_width(sizeof(uint32_t) - 1); size_t shifted = wordgenerated >> shift; uint32_t temp = rk[(wordgenerated - 1) >> shift].m_int4[(wordgenerated - 1) & mask]; @@ -791,7 +777,7 @@ class AES128 { return rk; } - constexpr static block_t _Encrypt(const block_t& src, const roundkeys& key) noexcept { + static constexpr block_t _Encrypt(const block_t& src, const roundkeys& key) noexcept { block_t state = src; addroundkey(state, key[0]); for (size_t i = 1; i < Nr; ++i) { @@ -805,7 +791,7 @@ class AES128 { addroundkey(state, key[Nr]); return state; } - constexpr static block_t _Decrypt(const block_t& src, const roundkeys& key) noexcept { + static constexpr block_t _Decrypt(const block_t& src, const roundkeys& key) noexcept { block_t state = src; addroundkey(state, key[Nr]); for (size_t i = Nr - 1; 1 <= i; i--) { @@ -819,6 +805,4 @@ class AES128 { addroundkey(state, key[0]); return state; } - -#undef ROR }; From a0f1938c1d5d3ee981abbdf8db6cd144f2c64b56 Mon Sep 17 00:00:00 2001 From: barrier Date: Mon, 22 Dec 2025 04:50:17 +0900 Subject: [PATCH 05/21] =?UTF-8?q?=E4=BD=BF=E7=94=A8=E4=BE=8B=E3=81=AE?= =?UTF-8?q?=E3=82=BD=E3=83=BC=E3=82=B9=E3=82=B3=E3=83=BC=E3=83=89=E3=82=92?= =?UTF-8?q?=E7=B0=A1=E6=98=93=E7=9A=84=E3=81=AB=E8=BF=BD=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CMakeLists.txt | 19 +- Socket.cpp | 363 +------------------------- example/BytesConvert/BytesConvert.cpp | 84 ++++++ example/EC_Signature/EC_Signature.cpp | 25 ++ example/KeyExchange/KeyExchange.cpp | 34 +++ example/Network/Network.cpp | 230 ++++++++++++++++ example/template/template.cpp | 6 + 7 files changed, 383 insertions(+), 378 deletions(-) create mode 100644 example/BytesConvert/BytesConvert.cpp create mode 100644 example/EC_Signature/EC_Signature.cpp create mode 100644 example/KeyExchange/KeyExchange.cpp create mode 100644 example/Network/Network.cpp create mode 100644 example/template/template.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 4338a15..117471b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -14,23 +14,10 @@ project ("Socket") # ソースをこのプロジェクトの実行可能ファイルに追加します。 add_executable (Socket "Socket.cpp" +) - # include - "include/common.h" - "include/Packet.h" - "include/Socket.h" - - # include/Cryptgraphy - "include/Cryptgraphy/AES128.h" - "include/Cryptgraphy/common.h" - "include/Cryptgraphy/ECDSA.h" - "include/Cryptgraphy/ECPoint.h" - "include/Cryptgraphy/KeyManager.h" - "include/Cryptgraphy/ModInt.h" - "include/Cryptgraphy/MultiWordInt.h" - "include/Cryptgraphy/NumberSet.h" - "include/Cryptgraphy/RandomGenerator.h" - "include/Cryptgraphy/SHAKE256.h" +include_directories( + ${PROJECT_SOURCE_DIR}/include ) if (CMAKE_VERSION VERSION_GREATER 3.12) diff --git a/Socket.cpp b/Socket.cpp index c71f978..59b5f6c 100644 --- a/Socket.cpp +++ b/Socket.cpp @@ -4,370 +4,9 @@ #include #include "include/Socket.h" - -void Server(); -void Client(); - -AES128::cbytearray<16> sharedkey = {'0', 'x', '7', '4', '0', 'x', '6', '5', '0', 'x', '7', '3', '0', 'x', '7', '4', }; - -struct ClientData { - - int Level = 0; - std::string Name = "NoName"; - - Packet::bytearray ToBytes() const { - Packet::bytearray ret; - Packet::StoreBytes(ret, Level); - Packet::StoreBytes(ret, Name); - return ret; - } - - Packet::byte_view FromBytes(Packet::byte_view view) { - Packet::LoadBytes(view, Level); - Packet::LoadBytes(view, Name); - return view; - } -}; - -struct ContainerInContainer { - - std::vector names; - - Packet::bytearray ToBytes() const { - Packet::bytearray ret; - Packet::StoreBytes(ret, names); - return ret; - } - - Packet::byte_view FromBytes(Packet::byte_view view) { - Packet::LoadBytes(view, names); - return view; - } -}; - -struct ContainerInVariable { - std::vector container; - - Packet::bytearray ToBytes() const { - Packet::bytearray ret; - Packet::StoreBytes(ret, container); - return ret; - } - - Packet::byte_view FromBytes(Packet::byte_view view) { - Packet::LoadBytes(view, container); - return view; - } -}; #include "include/Cryptgraphy/KeyManager.h" int main(int argc, char* argv[]) { - //KeyManager Keya; - //KeyManager Keyb; - // - //auto tp = std::chrono::high_resolution_clock::now(); - // - //auto kE = Keya.MakeQKey(); - //auto kF = Keyb.MakeQKey(); - // - //auto Ga = Keya.MakeSharedKey(kF); - //auto Gb = Keyb.MakeSharedKey(kE); - // - //auto ns = std::chrono::duration_cast(std::chrono::high_resolution_clock::now() - tp).count(); - // - //bool same = Ga == Gb; - // - //std::cout << (double)ns / 1000 / 1000 / 1000 << "s" << std::endl; - //std::cout << std::boolalpha << "shared key same: " << same << std::endl; - // - //for (auto&& b : Ga) { - // std::cout << std::hex << std::setw(2) << std::setfill('0') << std::right << (int)b; - //} - //std::cout << std::endl; - // - //for (auto&& b : Gb) { - // std::cout << std::hex << std::setw(2) << std::setfill('0') << std::right << (int)b; - //} - //std::cout << std::endl; - - KeyManager key; - std::string message = "I have skill is write low level programing language."; - - auto q = ECDSA::MakePublicKey(key.GetSecretKey()); - - auto v = ECDSA::Sign(key.GetSecretKey(), {message.begin(), message.end()}); - - bool ret = ECDSA::Verify(q, v, {message.begin(), message.end()}); - - std::cout << "message: \"" << message << "\"" << std::endl; - std::cout << "Q: {" << q.x.value.ToString(16) << ", " << q.y.value.ToString(16) << "}" << std::endl; - std::cout << "(r, s)(bytes): "; - for (auto&& b : v) { - std::cout << std::hex << std::setw(2) << std::setfill('0') << std::right << (int)b; - } - std::cout << std::endl; - - std::cout << std::boolalpha << ret; - - //std::string message = "0123456789abcdef"; - //Cryptgraphy::bytearray data{message.begin(), message.end()}; - // - //auto tp = std::chrono::high_resolution_clock::now(); - // - //auto ret = SHAKE256::HasherN(data, 64); - // - //auto ns = std::chrono::duration_cast(std::chrono::high_resolution_clock::now() - tp).count(); - // - //std::cout << (double)ns / 1000 / 1000 << "ms" << std::endl; - //std::cout << std::boolalpha << "hash: "; - // - //for (auto&& c : ret) { - // std::cout << std::hex << std::right << std::setw(2) << std::setfill('0') << (int)c; - //} - - //using int_t = bigint<8>; - //using modint_t = ModInt; - //using projective_t = ECProjective; - // - //modint_t::Factory xmodp = "ffffffff00000001000000000000000000000000ffffffffffffffffffffffff"; - //projective_t::Factory projective = WeierstrassParameter( - // xmodp("ffffffff00000001000000000000000000000000fffffffffffffffffffffffc"), - // xmodp("5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b") - //); - // - //auto G = projective( - // xmodp("6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"), - // xmodp("4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"), - // xmodp(1) - //); - // - //auto view = [](const std::string& name, const projective_t& p) { - // std::cout << name << ": {" - // << p.x.value.ToString(16) << ", " - // << p.y.value.ToString(16) << ", " - // << p.z.value.ToString(16) << "}" - // << std::endl; - //}; - //auto check = [](const projective_t& p) { - // auto a = p.ToAfinPoint(); - // std::cout << "Check: " << std::boolalpha - // << a.GetParam().CheckPoint(a.x, a.y) - // << std::endl; - //}; - // - //auto d = G.Double(); - // - //view("double", d); - //check(d); - // - //auto add = G.Add(d); - // - //view("add", add); - //check(add); - // - //auto scaler = G.Scaler(xmodp(100)); - // - //view("scaler", scaler); - //check(scaler); - - // arg[1]{ 0 = server, 1 = client } - - //std::vector args; - //args.insert(args.end(), argv, argv + argc); - // - //if (args.size() <= 1) { - // return -1; - //} - // - //if (std::stoi(args[1]) == 0) { - // Server(); - //} - //else { - // Client(); - //} - // - //return 0; -} - -void Server() { - - TCPServer server(8080); - - std::map> clients; - std::vector> joinqueue; - std::deque lostqueue; - - while (true) { - auto sock = server.Accept(); - - if (sock) { - bool emptyfound = false; - for (auto&& state : joinqueue) { - if (!state) { - state = std::move(*sock); - emptyfound = true; - break; - } - } - if (!emptyfound) { - joinqueue.push_back(std::move(*sock)); - } - } - - for (auto&& [_, pair] : clients) { - auto&& [c, cd] = pair; - if (c.LostConnection()) { - lostqueue.push_back(&c); - std::cout << "lost connection: " << cd.Name << std::endl; - } - } - - for (auto&& c : joinqueue) { - - if (!c) { - continue; - } - - if (c->Available() <= 0) { - continue; - } - - c->CryptEngine.Init(sharedkey); - - auto cd = c->EncryptionRecv()->Get(); - - if (cd) { - std::cout << "connected: " << cd->Name << std::endl; - auto addr = c->GetPeerAddress(); - clients[*addr] = {std::move(*c), std::move(*cd)}; - c.reset(); - } - } - - while (!lostqueue.empty()) { - auto p = lostqueue.front(); - lostqueue.pop_front(); - - clients.erase(*p->GetPeerAddress()); - } - - for (auto&& [_, pair] : clients) { - auto&& [c, cd] = pair; - - int available = c.Available(); - - if (available <= 0) { - continue; - } - - auto val = c.EncryptionRecv(); - - if (!val) { - continue; - } - - std::string send = cd.Name + "(" + std::to_string(cd.Level) + "): " + *val->Get(); - - std::cout << send << std::endl; - - for (auto&& [_, topair] : clients) { - auto&& [oc, __] = topair; - if (oc == c) { - continue; - } - oc.EncryptionSend(send); - } - } - } -} - -void Client() { - - TCPSocket server; - - std::cout << "input connect server address" << std::endl; - std::string str_addr; - std::cin >> str_addr; - - auto op_addr = IPAddress::SolveHostName(str_addr); - - if (!op_addr) { - std::cout << "can't solved address" << std::endl; - return; - } - - std::cout << "input port" << std::endl; - unsigned short port; - std::cin >> port; - - if (server.Connect(op_addr->Port(port))) { - std::cout << "connected server." << std::endl; - } - else { - std::cout << "can't connect server." << std::endl; - return; - } - - server.CryptEngine.Init(sharedkey); - - ClientData _data; - - std::cout << "input your Level\n"; - std::cin >> _data.Level; - std::cout << "input your Name\n"; - std::cin >> _data.Name; - - Packet p = Packet(_data); - - server.EncryptionSend(p); - - bool stopflag = false; - - std::mutex mtx; - - std::thread inputthread = std::thread{ - [&] { - while (!stopflag) { - std::string sendval; - std::cin >> sendval; - - if (sendval == "/exit") { - stopflag = true; - break; - } - - std::lock_guard lock(mtx); - - Packet pak = Packet(sendval); - server.EncryptionSend(sendval); - } - } - }; - - while (!stopflag) { - - if (server.LostConnection()) { - break; - } - - if (server.Available() <= 0) { - continue; - } - - auto pak = server.EncryptionRecv(); - - if (!pak) { - continue; - } - - std::lock_guard lock(mtx); - - auto val = *pak->Get(); - std::cout << val << std::endl; - } - - stopflag = true; - - inputthread.join(); + return 0; } diff --git a/example/BytesConvert/BytesConvert.cpp b/example/BytesConvert/BytesConvert.cpp new file mode 100644 index 0000000..55767dd --- /dev/null +++ b/example/BytesConvert/BytesConvert.cpp @@ -0,0 +1,84 @@ +#include "include/Socket.h" + +struct ContainerInContainer { + + std::vector names; + + Packet::bytearray ToBytes() const { + Packet::bytearray ret; + Packet::StoreBytes(ret, names); + return ret; + } + + Packet::byte_view FromBytes(Packet::byte_view view) { + Packet::LoadBytes(view, names); + return view; + } +}; + +struct ContainerInVariable { + std::vector container; + + Packet::bytearray ToBytes() const { + Packet::bytearray ret; + Packet::StoreBytes(ret, container); + return ret; + } + + Packet::byte_view FromBytes(Packet::byte_view view) { + Packet::LoadBytes(view, container); + return view; + } +}; + +int main(int argc, char* argv[]) { + + ContainerInVariable data{}; + ContainerInContainer cic{}; + + std::string str = "test"; + + cic.names.push_back(str); str += "t"; + cic.names.push_back(str); str += "t"; + cic.names.push_back(str); str += "t"; + cic.names.push_back(str); str += "t"; + + data.container.push_back(cic); + + str = "test2"; + + cic.names.push_back(str); str += "b"; + cic.names.push_back(str); str += "b"; + cic.names.push_back(str); str += "b"; + cic.names.push_back(str); str += "b"; + + data.container.push_back(cic); + + str = "magic"; + + cic.names.push_back(str); str += "m"; + cic.names.push_back(str); str += "m"; + cic.names.push_back(str); str += "m"; + cic.names.push_back(str); str += "m"; + + data.container.push_back(cic); + + str = "test"; + + cic.names.push_back(str); str += "z"; + cic.names.push_back(str); str += "z"; + cic.names.push_back(str); str += "z"; + cic.names.push_back(str); str += "z"; + + data.container.push_back(cic); + + Packet pak = Packet(data); + + auto& buf = pak.GetBuffer(); + + for (auto&& c : buf) { + std::cout << std::uppercase << std::setfill('0') << std::setw(2) << std::hex << std::right << static_cast(c); + } + + return 0; +} \ No newline at end of file diff --git a/example/EC_Signature/EC_Signature.cpp b/example/EC_Signature/EC_Signature.cpp new file mode 100644 index 0000000..5de2a2e --- /dev/null +++ b/example/EC_Signature/EC_Signature.cpp @@ -0,0 +1,25 @@ +#include "include/Socket.h" + +int main(int argc, char* argv[]) { + + KeyManager key; + std::string message = "I have skill is write low level programing language."; + + auto q = ECDSA::MakePublicKey(key.GetSecretKey()); + + auto v = ECDSA::Sign(key.GetSecretKey(), {message.begin(), message.end()}); + + bool ret = ECDSA::Verify(q, v, {message.begin(), message.end()}); + + std::cout << "message: \"" << message << "\"" << std::endl; + std::cout << "Q: {" << q.x.value.ToString(16) << ", " << q.y.value.ToString(16) << "}" << std::endl; + std::cout << "(r, s)(bytes): "; + for (auto&& b : v) { + std::cout << std::hex << std::setw(2) << std::setfill('0') << std::right << (int)b; + } + std::cout << std::endl; + + std::cout << std::boolalpha << ret; + + return 0; +} \ No newline at end of file diff --git a/example/KeyExchange/KeyExchange.cpp b/example/KeyExchange/KeyExchange.cpp new file mode 100644 index 0000000..8146d41 --- /dev/null +++ b/example/KeyExchange/KeyExchange.cpp @@ -0,0 +1,34 @@ +#include "include/Cryptgraphy/KeyManager.h" + +int main(int argc, char* argv[]) { + + KeyManager Keya; + KeyManager Keyb; + + auto tp = std::chrono::high_resolution_clock::now(); + + auto kE = Keya.MakeQKey(); + auto kF = Keyb.MakeQKey(); + + auto Ga = Keya.MakeSharedKey(kF); + auto Gb = Keyb.MakeSharedKey(kE); + + auto ns = std::chrono::duration_cast(std::chrono::high_resolution_clock::now() - tp).count(); + + bool same = Ga == Gb; + + std::cout << (double)ns / 1000 / 1000 / 1000 << "s" << std::endl; + std::cout << std::boolalpha << "shared key same: " << same << std::endl; + + for (auto&& b : Ga) { + std::cout << std::hex << std::setw(2) << std::setfill('0') << std::right << (int)b; + } + std::cout << std::endl; + + for (auto&& b : Gb) { + std::cout << std::hex << std::setw(2) << std::setfill('0') << std::right << (int)b; + } + std::cout << std::endl; + + return 0; +} \ No newline at end of file diff --git a/example/Network/Network.cpp b/example/Network/Network.cpp new file mode 100644 index 0000000..5578b03 --- /dev/null +++ b/example/Network/Network.cpp @@ -0,0 +1,230 @@ +#include "include/Socket.h" + +void Server(); +void Client(); + +AES128::cbytearray<16> sharedkey = {'0', 'x', '7', '4', '0', 'x', '6', '5', '0', 'x', '7', '3', '0', 'x', '7', '4',}; + +struct ClientData { + + int Level = 0; + std::string Name = "NoName"; + + Packet::bytearray ToBytes() const { + Packet::bytearray ret; + Packet::StoreBytes(ret, Level); + Packet::StoreBytes(ret, Name); + return ret; + } + + Packet::byte_view FromBytes(Packet::byte_view view) { + Packet::LoadBytes(view, Level); + Packet::LoadBytes(view, Name); + return view; + } +}; + +int main(int argc, char* argv[]) { + + // arg[1]{ 0 = server, 1 = client } + + std::vector args; + args.insert(args.end(), argv, argv + argc); + + if (args.size() <= 1) { + return -1; + } + + if (std::stoi(args[1]) == 0) { + Server(); + } + else { + Client(); + } + + return 0; +} + +void Server() { + + TCPServer server(8080); + + std::map> clients; + std::vector> joinqueue; + std::deque lostqueue; + + while (true) { + auto sock = server.Accept(); + + if (sock) { + bool emptyfound = false; + for (auto&& state : joinqueue) { + if (!state) { + state = std::move(*sock); + emptyfound = true; + break; + } + } + if (!emptyfound) { + joinqueue.push_back(std::move(*sock)); + } + } + + for (auto&& [_, pair] : clients) { + auto&& [c, cd] = pair; + if (c.LostConnection()) { + lostqueue.push_back(&c); + std::cout << "lost connection: " << cd.Name << std::endl; + } + } + + for (auto&& c : joinqueue) { + + if (!c) { + continue; + } + + if (c->Available() <= 0) { + continue; + } + + c->CryptEngine.Init(sharedkey); + + auto cd = c->EncryptionRecv()->Get(); + + if (cd) { + std::cout << "connected: " << cd->Name << std::endl; + auto addr = c->GetPeerAddress(); + clients[*addr] = {std::move(*c), std::move(*cd)}; + c.reset(); + } + } + + while (!lostqueue.empty()) { + auto p = lostqueue.front(); + lostqueue.pop_front(); + + clients.erase(*p->GetPeerAddress()); + } + + for (auto&& [_, pair] : clients) { + auto&& [c, cd] = pair; + + int available = c.Available(); + + if (available <= 0) { + continue; + } + + auto val = c.EncryptionRecv(); + + if (!val) { + continue; + } + + std::string send = cd.Name + "(" + std::to_string(cd.Level) + "): " + *val->Get(); + + std::cout << send << std::endl; + + for (auto&& [_, topair] : clients) { + auto&& [oc, __] = topair; + if (oc == c) { + continue; + } + oc.EncryptionSend(send); + } + } + } +} + +void Client() { + + TCPSocket server; + + std::cout << "input connect server address" << std::endl; + std::string str_addr; + std::cin >> str_addr; + + auto op_addr = IPAddress::SolveHostName(str_addr); + + if (!op_addr) { + std::cout << "can't solved address" << std::endl; + return; + } + + std::cout << "input port" << std::endl; + unsigned short port; + std::cin >> port; + + if (server.Connect(op_addr->Port(port))) { + std::cout << "connected server." << std::endl; + } + else { + std::cout << "can't connect server." << std::endl; + return; + } + + server.CryptEngine.Init(sharedkey); + + ClientData _data; + + std::cout << "input your Level\n"; + std::cin >> _data.Level; + std::cout << "input your Name\n"; + std::cin >> _data.Name; + + Packet p = Packet(_data); + + server.EncryptionSend(p); + + bool stopflag = false; + + std::mutex mtx; + + std::thread inputthread = std::thread{ + [&] { + while (!stopflag) { + std::string sendval; + std::cin >> sendval; + + if (sendval == "/exit") { + stopflag = true; + break; + } + + std::lock_guard lock(mtx); + + Packet pak = Packet(sendval); + server.EncryptionSend(sendval); + } + } + }; + + while (!stopflag) { + + if (server.LostConnection()) { + break; + } + + if (server.Available() <= 0) { + continue; + } + + auto pak = server.EncryptionRecv(); + + if (!pak) { + continue; + } + + std::lock_guard lock(mtx); + + auto val = *pak->Get(); + std::cout << val << std::endl; + } + + stopflag = true; + + inputthread.join(); +} + + diff --git a/example/template/template.cpp b/example/template/template.cpp new file mode 100644 index 0000000..c320a3c --- /dev/null +++ b/example/template/template.cpp @@ -0,0 +1,6 @@ +#include "include/Socket.h" + +int main(int argc, char* argv[]) { + + return 0; +} \ No newline at end of file From 3310348096fd44a05add37ec3f39833a770f9e17 Mon Sep 17 00:00:00 2001 From: barrier Date: Mon, 22 Dec 2025 08:39:34 +0900 Subject: [PATCH 06/21] =?UTF-8?q?=E3=82=AB=E3=83=A9=E3=83=84=E3=83=90?= =?UTF-8?q?=E6=B3=95=E3=82=92=E5=AE=9F=E8=A3=85...=E5=A4=9A=E5=88=86?= =?UTF-8?q?=E4=BD=BF=E3=82=8F=E3=81=AA=E3=81=84=E3=81=91=E3=81=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Socket.cpp | 37 ++++++++++++ include/Cryptgraphy/MultiWordInt.h | 94 ++++++++++++++++++++++-------- 2 files changed, 108 insertions(+), 23 deletions(-) diff --git a/Socket.cpp b/Socket.cpp index 59b5f6c..a436547 100644 --- a/Socket.cpp +++ b/Socket.cpp @@ -8,5 +8,42 @@ int main(int argc, char* argv[]) { + using int_t = bigint<2048>; + + int_t a = 0x123456789abcdef0; + a = a.Pow(0xffffffff); + int_t b = a.Pow(0xffffffff); + + auto time = [&]() { + return std::chrono::high_resolution_clock::now(); + }; + + std::cout << "condition:" << std::endl; + std::cout << "max digits: 2^" << int_t::AllBits << std::endl; + std::cout << "a = 0x123456789abcdef0^0xffffffff" << std::endl; + std::cout << "b = a^0xffffffff" << std::endl; + std::cout << "ret = a * b" << std::endl << std::endl; + + auto tp = time(); + + int_t ret = int_t::NormalMul(a, b); + + double t = std::chrono::duration_cast(time() - tp).count(); + + std::cout << "Normal: " << t / 1000 << "us" << std::endl; + //std::cout << ret.ToString(16, true, false) << std::endl; + + tp = time(); + + ret = int_t::Karatuba(a, b); + + t = std::chrono::duration_cast(time() - tp).count(); + + std::cout << "Karatuba: " << t / 1000 << "us" << std::endl; + //std::cout << ret.ToString(16, true, false) << std::endl; + + // before: 2.0759ms + // after : + return 0; } diff --git a/include/Cryptgraphy/MultiWordInt.h b/include/Cryptgraphy/MultiWordInt.h index bb020ab..75975e7 100644 --- a/include/Cryptgraphy/MultiWordInt.h +++ b/include/Cryptgraphy/MultiWordInt.h @@ -274,41 +274,89 @@ struct bigint { return { t1, t2 }; } - constexpr bigint& AssignMul(bigint src) { - - bigint base = *this; - *this = 0; + static constexpr bigint NormalMul(const bigint& x, const bigint& y) { + bigint ret = 0; + for (count_t j = 0; j < Words; ++j) { - const word_t src_word = src.words()[j]; - - if (src_word == 0) { + const word_t y_word = y.words()[j]; + + if (y_word == 0) { continue; } - + word_t carry = 0; bool carryflag = false; - + for (count_t i = 0; i + j < Words; ++i) { word_t temp = carry; - + const auto [lower, upper] = MulBase( - src_word, - base.words()[i] + y_word, + x.words()[i] ); - + carryflag = AddBase(&temp, lower, carryflag); - + carry = upper + carryflag; - + carryflag = AddBase( - std::addressof(this->words()[i + j]), + std::addressof(ret.words()[i + j]), temp, false ); } } + + return ret; + } + static constexpr bigint Karatuba(const bigint& x, const bigint& y) { + bigint ret = 0; + + if (x == 0 || y == 0) { + return ret; + } + + count_t nbit = std::max(x.GetNBit(), y.GetNBit()); + count_t halfbits = (nbit + (nbit & 1)) / 2; - return *this; + if (halfbits <= WordBits * 2) { + ret = NormalMul(x, y); + return ret; + } + + bigint halfmask = (bigint(1) << halfbits) - 1; + + bigint xl = x; + bigint xh = x; + bigint yl = y; + bigint yh = y; + + xl &= halfmask; + xh >>= halfbits; + yl &= halfmask; + yh >>= halfbits; + + bigint z0 = Karatuba(xl, yl); + bigint z2 = Karatuba(xh, yh); + + xl += xh; + yl += yh; + bigint z1 = Karatuba(xl, yl); + + z1 -= z0; + z1 -= z2; + ret += z0; + + z1 <<= halfbits; + z2 <<= (2 * halfbits); + + ret += z1; + ret += z2; + + return ret; + } + constexpr bigint& AssignMul(bigint src) { + return *this = NormalMul(*this, src); } constexpr std::pair AssignDivMod(bigint src) { @@ -356,11 +404,11 @@ struct bigint { constexpr friend bool operator<=(const bigint& lhs, const bigint& rhs) { return lhs.Compare(rhs) <= 0; } constexpr friend bool operator> (const bigint& lhs, const bigint& rhs) { return lhs.Compare(rhs) > 0; } constexpr friend bool operator>=(const bigint& lhs, const bigint& rhs) { return lhs.Compare(rhs) >= 0; } - constexpr bigint& AssignLeftShift(word_t c) { + constexpr bigint& AssignLeftShift(count_t c) { bits() <<= c; return *this; } - constexpr bigint& AssignRightShift(word_t c) { + constexpr bigint& AssignRightShift(count_t c) { if constexpr (IsSigned) { if (this->IsNegative()) { unsigned_t shiftmask = 1; @@ -379,10 +427,10 @@ struct bigint { } return *this; } - constexpr bigint& operator<<=(word_t c) { return AssignLeftShift(c); } - constexpr bigint& operator>>=(word_t c) { return AssignRightShift(c); } - constexpr friend bigint operator<<(bigint lhs, word_t c) { return lhs.AssignLeftShift(c); } - constexpr friend bigint operator>>(bigint lhs, word_t c) { return lhs.AssignRightShift(c); } + constexpr bigint& operator<<=(count_t c) { return AssignLeftShift(c); } + constexpr bigint& operator>>=(count_t c) { return AssignRightShift(c); } + constexpr friend bigint operator<<(bigint lhs, count_t c) { return lhs.AssignLeftShift(c); } + constexpr friend bigint operator>>(bigint lhs, count_t c) { return lhs.AssignRightShift(c); } constexpr bigint& AssignNot() { bits().flip(); return *this; } constexpr bigint operator~() const { return bigint(*this).AssignNot(); } constexpr bigint& AssignAnd(const bigint& src) { bits() &= src.bits(); return *this; } From 64703a635feb73c9bd1363502de69c1ed011ca1e Mon Sep 17 00:00:00 2001 From: barrier Date: Tue, 10 Feb 2026 15:22:30 +0900 Subject: [PATCH 07/21] =?UTF-8?q?=E3=81=A8=E3=82=8A=E3=81=82=E3=81=88?= =?UTF-8?q?=E3=81=9A=E3=82=88=E3=81=8F=E3=82=8F=E3=81=8B=E3=82=89=E3=81=AA?= =?UTF-8?q?=E3=81=84=E3=81=91=E3=81=A9=E3=81=93=E3=81=AE=E7=8F=BE=E7=8A=B6?= =?UTF-8?q?=E3=82=92=E3=82=B3=E3=83=9F=E3=83=83=E3=83=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- example/EC_Signature/EC_Signature.cpp | 2 + example/KeyExchange/KeyExchange.cpp | 2 + include/Cryptgraphy/MultiWordInt.h | 295 ++++++++++++++++++++++++-- include/Cryptgraphy/common.h | 1 + 4 files changed, 287 insertions(+), 13 deletions(-) diff --git a/example/EC_Signature/EC_Signature.cpp b/example/EC_Signature/EC_Signature.cpp index 5de2a2e..d57de07 100644 --- a/example/EC_Signature/EC_Signature.cpp +++ b/example/EC_Signature/EC_Signature.cpp @@ -21,5 +21,7 @@ int main(int argc, char* argv[]) { std::cout << std::boolalpha << ret; + assert(ret); + return 0; } \ No newline at end of file diff --git a/example/KeyExchange/KeyExchange.cpp b/example/KeyExchange/KeyExchange.cpp index 8146d41..e4c8f2f 100644 --- a/example/KeyExchange/KeyExchange.cpp +++ b/example/KeyExchange/KeyExchange.cpp @@ -30,5 +30,7 @@ int main(int argc, char* argv[]) { } std::cout << std::endl; + assert(same); + return 0; } \ No newline at end of file diff --git a/include/Cryptgraphy/MultiWordInt.h b/include/Cryptgraphy/MultiWordInt.h index 75975e7..ef0a108 100644 --- a/include/Cryptgraphy/MultiWordInt.h +++ b/include/Cryptgraphy/MultiWordInt.h @@ -1,6 +1,10 @@ #pragma once #include "common.h" +/// +/// fixed-size +/// + template struct bigint { using count_t = size_t; @@ -17,9 +21,9 @@ struct bigint { static constexpr count_t WordCharSize = WordByte * 2; static constexpr count_t AllBits = Words * WordBits; - static_assert(Words > 0, "invalid WordCount"); - using arr_t = std::array; + using arr_view = std::span; + using arr_ref = std::span; using bits_t = std::bitset; using signed_t = bigint; using unsigned_t = bigint; @@ -216,16 +220,29 @@ struct bigint { constexpr operator unsigned_t& () requires(!IsSigned) { return *this; // TODO: remove unneccesary conversion } + template + requires (std::is_convertible_v>) + constexpr bigint& FromWords(R&& r) { + auto fb = std::ranges::begin(r); + auto fe = std::ranges::end(r); + for (auto& elem : words()) { + if (fb == fe) { + break; + } + elem = *(fb++); + } + return *this; + } /// Arithmetic Module - static constexpr bool AddBase(word_t *dest, word_t src, bool carry) { + static constexpr bool AddBase(word_t *dest, word_t src, bool carry) noexcept { word_t a = *dest; word_t b = src + static_cast(carry); *dest += b; return (b < src) || (*dest < a); } - constexpr bigint& AssignAdd(const bigint& src) { + constexpr bigint& AssignAdd(const bigint& src) noexcept { bool carry = false; for (count_t i = 0; i < Words; ++i) { carry = AddBase( @@ -309,7 +326,7 @@ struct bigint { return ret; } - static constexpr bigint Karatuba(const bigint& x, const bigint& y) { + static constexpr bigint Karatuba_Legacy(const bigint& x, const bigint& y) { bigint ret = 0; if (x == 0 || y == 0) { @@ -318,12 +335,12 @@ struct bigint { count_t nbit = std::max(x.GetNBit(), y.GetNBit()); count_t halfbits = (nbit + (nbit & 1)) / 2; - + if (halfbits <= WordBits * 2) { ret = NormalMul(x, y); return ret; } - + bigint halfmask = (bigint(1) << halfbits) - 1; bigint xl = x; @@ -355,6 +372,50 @@ struct bigint { return ret; } + static constexpr bigint Karatuba(const bigint& x, const bigint& y) { + if (x == 0 || y == 0) { + return bigint(0); + } + + bigint t[4]{}; + + bigint z0; + bigint z1; + bigint z2; + + auto rec = [&](auto&& self, arr_view vx, arr_view vy) -> bigint& { + + count_t halfwords = vx.size() >> 1; + + if (halfwords <= 1) { + auto [low, high] = MulBase(vx.front(), vy.front()); + word_t words[2] = {low, high}; + return z0.FromWords(words); + } + + arr_view xl = vx.subspan(0, halfwords); + arr_view xh = vx.subspan(halfwords); + arr_view yl = vy.subspan(0, halfwords); + arr_view yh = vy.subspan(halfwords); + + z0 = self(self, xl, yl); + z2 = self(self, xh, yh); + + t[0].FromWords(xl) += t[2].FromWords(xh); + t[1].FromWords(yl) += t[2].FromWords(yh); + + xl = arr_view(t[0].words()).subspan(halfwords); + yl = arr_view(t[1].words()).subspan(halfwords); + + z1 = self(self, xl, yl); + z1 -= z0; + z1 -= z2; + + return z0.AssignAdd(z1.AssignLeftShift(halfwords * WordBits)).AssignAdd(z2.AssignLeftShift(2 * halfwords * WordBits)); + }; + + return rec(rec, x.words(), y.words()); + } constexpr bigint& AssignMul(bigint src) { return *this = NormalMul(*this, src); } @@ -679,18 +740,226 @@ struct bigint { /// Internal Resource - constexpr arr_t& words() { return *m_words; } - constexpr const arr_t& words() const { return *m_words; } + constexpr arr_t& words() noexcept { return *m_words; } + constexpr const arr_t& words() const noexcept { return *m_words; } constexpr bits_t& bits() { - return *std::bit_cast(m_words->data()); // TODO: resolve potential undefined behavior - // NOTE: temporary fix + return *reinterpret_cast(m_words->data()); // TODO: resolve potential undefined behavior } constexpr const bits_t& bits() const { - return *std::bit_cast(m_words->data()); // TODO: resolve potential undefined behavior - // NOTE: temporary fix + return *reinterpret_cast(m_words->data()); // TODO: resolve potential undefined behavior } private: arr_t* m_words = new arr_t(); }; + + +/// +/// variable-size +/// + +template +struct bigint<0, _sign> { + using count_t = size_t; + using diff_t = int64_t; + using word_t = uint64_t; + using sword_t = int64_t; + + static constexpr bool IsSigned = _sign; + // static constexpr count_t Words = 0; + static constexpr count_t WordByte = sizeof(word_t); + static constexpr count_t WordBits = WordByte * 8; + static constexpr count_t WordCharSize = WordByte * 2; + // static constexpr count_t WordBytes = Words * WordByte; + // static constexpr count_t AllBits = Words * WordBits; + + using arr_t = std::vector; + using arr_view = std::span; + using arr_ref = std::span; + using signed_t = bigint<0, true>; + using unsigned_t = bigint<0, false>; + + constexpr count_t GetWords() const noexcept { + return m_words.size(); + } + constexpr count_t GetWordBytes() const noexcept { + return GetWords() * WordByte; + } + constexpr count_t GetAllBits() const noexcept { + return GetWords() * WordBits; + } + constexpr count_t GetNWord() const noexcept { + for (count_t i = m_words.size(); i-- > 0;) { + if (m_words[i] != 0) { + return i + 1; + } + } + return GetWords(); + } + constexpr count_t GetNBit() const noexcept { + count_t idx = GetWords() - 1; + count_t word_nbit = std::bit_width(m_words[idx]); + return word_nbit == 0 ? GetAllBits() : idx * WordBits + word_nbit; + } + + constexpr void Resize(count_t newsize) noexcept { + m_words.resize(newsize, 0); + } + + static constexpr bool AddBase(word_t src, word_t *dest, bool carry) noexcept { + word_t a = *dest; + word_t b = src + static_cast(carry); + *dest += b; + return (b < src) || (*dest < a); + } + constexpr bigint& AssignAdd(const bigint& rhs) noexcept { + bool carry = false; + for (count_t i = 0; i < GetWords(); ++i) { + carry = AddBase( + rhs.m_words[i], + std::addressof(this->m_words[i]), + carry + ); + } + return *this; + } + + constexpr bigint& AssignNOT() noexcept { + std::transform( + std::execution::unseq, + m_words.begin(), + m_words.end(), + m_words.begin(), + std::bit_not() + ); + return *this; + } + constexpr bigint& AssignAND(const bigint& rhs) noexcept { + std::transform( + std::execution::unseq, + m_words.begin(), + m_words.end(), + rhs.m_words.begin(), + m_words.begin(), + std::bit_and() + ); + return *this; + } + constexpr bigint& AssignOR(const bigint& rhs) noexcept { + std::transform( + std::execution::unseq, + m_words.begin(), + m_words.end(), + rhs.m_words.begin(), + m_words.begin(), + std::bit_or() + ); + return *this; + } + constexpr bigint& AssignXOR(const bigint& rhs) noexcept { + std::transform( + std::execution::unseq, + m_words.begin(), + m_words.end(), + rhs.m_words.begin(), + m_words.begin(), + std::bit_xor() + ); + return *this; + } + static constexpr word_t WordShiftBase(word_t low, word_t high, count_t n) noexcept { + return (low >> n) | (high << (WordBits - n)); + } + constexpr bigint& AssignLeftShift(count_t n) noexcept { + count_t wordshift = n >> std::bit_width(WordBits - 1); + count_t bitshift = n & (WordBits - 1); + + for (count_t i = GetWords() - wordshift; i-- > 0;) { + m_words[i + wordshift] = WordShiftBase( + i == 0 ? 0 : m_words[i - 1], + m_words[i], + bitshift + ); + } + + auto offset = std::min(wordshift, GetWords()); + std::fill(std::execution::unseq, m_words.begin(), m_words.begin() + offset, 0); + + return *this; + } + constexpr bigint& AssignRightShift(count_t n) noexcept { + count_t wordshift = n >> std::bit_width(WordBits - 1); + count_t bitshift = WordBits - (n & (WordBits - 1)); + + for (count_t i = wordshift, c = GetWords(); i < c; ++i) { + m_words[i - wordshift] = WordShiftBase( + m_words[i], + m_words[i + 1], + bitshift + ); + } + + auto offset = std::min(wordshift, GetWords()); + std::fill(std::execution::unseq, m_words.rbegin(), m_words.rbegin() + offset, 0); + + return *this; + } + + constexpr bigint& operator~() noexcept { + return AssignNOT(); + } + constexpr bigint& operator&=(const bigint& rhs) noexcept { + return AssignAND(rhs); + } + constexpr bigint& operator|=(const bigint& rhs) noexcept { + return AssignOR(rhs); + } + constexpr bigint& operator^=(const bigint& rhs) noexcept { + return AssignXOR(rhs); + } + + static constexpr auto Compare(const bigint& lhs, const bigint& rhs) noexcept { + count_t words[2] = {lhs.GetWords(), rhs.GetWords()}; + auto [words_min, words_max] = std::minmax(words[0], words[1]); + + bool is_bigger_l = words_max == words[0]; + + const bigint& longer = is_bigger_l ? lhs : rhs; + const bigint& shorter = is_bigger_l ? rhs : lhs; + + if (!IsZeroInRef(arr_view(longer.m_words).last(words_max - words_min))) { + return is_bigger_l ? + std::strong_ordering::greater : std::strong_ordering::less; + } + + for (count_t i = words_min; i-- > 0;) { + auto com = lhs.m_words[i] <=> rhs.m_words[i]; + if (!std::is_eq(com)) { + return com; + } + } + + return std::strong_ordering::equal; + } + constexpr auto Compare(const bigint& rhs) const noexcept { + return Compare(*this, rhs); + } + friend constexpr auto operator<=>(const bigint& lhs, const bigint& rhs) noexcept { + return Compare(lhs, rhs); + } + +private: + + static constexpr bool IsZeroInRef(arr_view v) noexcept { + for (auto&& elem : v) { + if (elem != 0) { + return false; + } + } + return true; + } + + arr_t m_words{}; + +}; \ No newline at end of file diff --git a/include/Cryptgraphy/common.h b/include/Cryptgraphy/common.h index ed82480..782a364 100644 --- a/include/Cryptgraphy/common.h +++ b/include/Cryptgraphy/common.h @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include From 83491e055d76341cb686aae13211f891293993a9 Mon Sep 17 00:00:00 2001 From: barrier Date: Tue, 10 Feb 2026 15:24:41 +0900 Subject: [PATCH 08/21] =?UTF-8?q?=E4=BB=A3=E5=85=A5=E5=91=A8=E3=82=8A?= =?UTF-8?q?=E3=81=8Cdelete=E6=8C=87=E5=AE=9A=E3=81=AA=E3=81=AE=E3=81=8Bdef?= =?UTF-8?q?ault=E6=8C=87=E5=AE=9A=E3=81=AA=E3=81=AE=E3=81=8B=E6=9B=96?= =?UTF-8?q?=E6=98=A7=E3=81=A7=E3=81=82=E3=81=A3=E3=81=9F=E9=83=A8=E5=88=86?= =?UTF-8?q?=E3=82=92=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/Packet.h | 77 ++++++++++++------------------------------------ 1 file changed, 19 insertions(+), 58 deletions(-) diff --git a/include/Packet.h b/include/Packet.h index 7e20988..20a8fe8 100644 --- a/include/Packet.h +++ b/include/Packet.h @@ -89,7 +89,9 @@ struct Header { }; /// -/// Packet +/// Packet +/// | header (16 byte) | data (variable) | +/// | size and data type | raw binary data | /// struct Packet { @@ -109,28 +111,22 @@ struct Packet { template static constexpr bool memcpyable = SocketDetail::memcpyable; - + template static constexpr bool to_byteable = SocketDetail::to_byteable; - + template static constexpr bool from_byteable = SocketDetail::from_byteable; template static constexpr bool cross_convertible = SocketDetail::cross_convertible; - Packet(const Packet&) = default; + Packet() {}; + Packet(const Packet&) = delete; Packet(Packet&&) = default; - - Packet& operator=(const Packet&) = default; + Packet& operator=(const Packet&) = delete; Packet& operator=(Packet&&) = default; - Packet() {}; - Packet(const bytearray&) = delete; - Packet(bytearray&&) = delete; - Packet& operator=(const bytearray&) = delete; - Packet& operator=(bytearray&&) = delete; - Packet(uint32_t id, const void* src, uint32_t size) { Header head(id); head.Size = size; @@ -144,7 +140,7 @@ struct Packet { Packet(uint32_t id, const bytearray& data) : Packet(id, data.data(), data.size()) {} template Packet(enumT type, const bytearray& data) requires (is_enum32) : Packet(type, data.data(), data.size()) {} - + template Packet(size_t id, const char(&data)[len]) : Packet(id, std::addressof(data), len - 1) {} template @@ -156,28 +152,25 @@ struct Packet { template Packet(enumT type, const std::string& data) requires (is_enum32) : Packet(type, data.data(), data.size()) {} Packet(const std::string& data) : Packet(Header::type_hash_code(), data.data(), data.size()) {} - + template Packet(uint32_t id, const T& data) requires (memcpyable && !cross_convertible) : Packet(id, std::addressof(data), sizeof(T)) {} template - Packet(enumT type, const T& data) requires (is_enum32 && memcpyable && !cross_convertible) : Packet(static_cast(type), std::addressof(data), sizeof(T)) {} + Packet(enumT type, const T& data) requires (is_enum32&& memcpyable && !cross_convertible) : Packet(static_cast(type), std::addressof(data), sizeof(T)) {} template Packet(const T& data) requires (memcpyable && !cross_convertible) : Packet(Header::type_hash_code(), std::addressof(data), sizeof(T)) {} template Packet(uint32_t id, const std::vector& data) requires (memcpyable && !cross_convertible) : Packet(id, data.data(), data.size() * sizeof(T)) {} template - Packet(enumT type, const std::vector& data) requires (is_enum32 && memcpyable && !cross_convertible) : Packet(static_cast(type), data.data(), data.size() * sizeof(T)) {} + Packet(enumT type, const std::vector& data) requires (is_enum32&& memcpyable && !cross_convertible) : Packet(static_cast(type), data.data(), data.size() * sizeof(T)) {} template Packet(const std::vector& data) requires (memcpyable && !cross_convertible) : Packet(Header::type_hash_code>(), data.data(), data.size() * sizeof(T)) {} template - Packet(uint32_t id, const T& data) requires (cross_convertible) { - bytearray _data = Convert(data); - *this = Packet(id, _data.data(), _data.size()); - } + Packet(uint32_t id, const T& data) requires (cross_convertible) : Packet(id, Convert(data)); template - Packet(enumT type, const T& data) requires (is_enum32 && cross_convertible) : Packet(static_cast(type), data) {} + Packet(enumT type, const T& data) requires (is_enum32&& cross_convertible) : Packet(static_cast(type), data) {} template Packet(const T& data) requires (cross_convertible) : Packet(Header::type_hash_code(), data) {} @@ -192,7 +185,7 @@ struct Packet { *this = Packet(id, b.data(), b.size()); } template - Packet(enumT type, const std::vector& data) requires (is_enum32 && cross_convertible) : Packet(static_cast(type), data) {} + Packet(enumT type, const std::vector& data) requires (is_enum32&& cross_convertible) : Packet(static_cast(type), data) {} template Packet(const std::vector& data) requires (cross_convertible) : Packet(Header::type_hash_code>(), data) {} @@ -213,38 +206,6 @@ struct Packet { Packet(enumT type, std::ifstream& ifs) requires (is_enum32) : Packet(static_cast(type), ifs) {} explicit Packet(std::ifstream& ifs) : Packet(Header::type_hash_code(), ifs) {} - /* - - explicit Packet(uint32_t id, const std::filesystem::path& path) { - std::error_code ec; - if (path.empty() || !std::filesystem::exists(path, ec) || ec) { - return; - } - - const auto size = std::filesystem::file_size(path, ec); - if (ec) { - return; - } - - std::ifstream ifs(path, std::ios::binary); - - if (!ifs.is_open()) { - return; - } - - buf_t data(size); - ifs.read(reinterpret_cast(data.data()), size); - - ifs.close(); - - *this = Packet(id, data); - } - template - explicit Packet(enumT type, const std::filesystem::path& path, Header::enum32 dummy_0 = {}) : Packet(static_cast(type), path) {} - explicit Packet(const std::filesystem::path& path) : Packet(Header::type_hash_code(), path) {} - - */ - size_t Size() const { return m_buffer.size(); } const bytearray& GetBuffer() const { return m_buffer; } @@ -280,7 +241,7 @@ struct Packet { auto&& [ret, _] = Convert(byte_view(m_buffer).subspan(HeaderSize)); return ret; } - + template std::optional Get() const requires (std::same_as) { if (CheckHeader()) { @@ -293,7 +254,7 @@ struct Packet { } template - std::optional> GetArray() const requires (memcpyable && !from_byteable){ + std::optional> GetArray() const requires (memcpyable && !from_byteable) { if (CheckHeader()) { return std::nullopt; } @@ -319,7 +280,7 @@ struct Packet { } template - static bytearray Convert(const T &from) requires (to_byteable) { + static bytearray Convert(const T& from) requires (to_byteable) { return from.ToBytes(); } @@ -329,7 +290,7 @@ struct Packet { byte_view view = ret.FromBytes(from); return {ret, view}; } - + static void StoreBytes(bytearray& dest, const void* src, uint32_t size) { dest.insert(dest.end(), static_cast(src), static_cast(src) + size); } From cd0770b476c21a047b12d081d347b3af9d3f34ff Mon Sep 17 00:00:00 2001 From: barrier Date: Tue, 10 Feb 2026 16:58:14 +0900 Subject: [PATCH 09/21] =?UTF-8?q?=E3=83=90=E3=83=83=E3=83=95=E3=82=A1?= =?UTF-8?q?=E3=81=AE=E6=93=8D=E4=BD=9C=E9=96=A2=E4=BF=82=E3=82=92=E8=AA=BF?= =?UTF-8?q?=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 変更・追加 GetBuffer -> GetRawPacketにリネーム GetRawData -> イミュータブルな生データ参照を返す RefRawData -> ミュータブルな生データ参照を返す 削除 SetBuffer -> ヘッダーを考慮しないバッファが渡される可能性、代替として前述のRefRawDataを実装したので削除 --- include/Packet.h | 16 ++++++++++++---- include/Socket.h | 4 ++-- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/include/Packet.h b/include/Packet.h index 20a8fe8..6bb510f 100644 --- a/include/Packet.h +++ b/include/Packet.h @@ -208,10 +208,18 @@ struct Packet { size_t Size() const { return m_buffer.size(); } - const bytearray& GetBuffer() const { return m_buffer; } - Packet& SetBuffer(bytearray&& src) { - m_buffer = std::move(src); - return *this; + const bytearray& GetRawPacket() const { return m_buffer; } + std::optional GetRawData() const { + if (CheckHeader()) { + return std::nullopt; + } + return byte_view(m_buffer.begin(), m_buffer.end()).first(HeaderSize); + } + std::optional RefRawData() { + if (CheckHeader()) { + return std::nullopt; + } + return byte_ref(m_buffer.begin(), m_buffer.end()).first(HeaderSize); } std::optional
GetHeader() const { diff --git a/include/Socket.h b/include/Socket.h index 50d24b9..496a17b 100644 --- a/include/Socket.h +++ b/include/Socket.h @@ -520,7 +520,7 @@ class basic_TCPSocket : public sockbase { if (src.CheckHeader()) { return false; } - return Send(src.GetBuffer()); + return Send(src.GetRawPacket()); } std::optional Recv() { bytearray head(Packet::HeaderSize); @@ -548,7 +548,7 @@ class basic_TCPSocket : public sockbase { if (src.CheckHeader()) { return false; } - bytearray data(src.GetBuffer().begin() + Packet::HeaderSize, src.GetBuffer().end()); + bytearray data(src.GetRawPacket().begin() + Packet::HeaderSize, src.GetRawPacket().end()); bool flag = Encrypt(data, data); Packet pak = Packet(src.GetHeader()->Type, data); return flag && Send(pak); From 639d95c93a08290146de2d22303ad852cb67c856 Mon Sep 17 00:00:00 2001 From: barrier Date: Tue, 10 Feb 2026 18:04:25 +0900 Subject: [PATCH 10/21] =?UTF-8?q?=E6=9A=97=E5=8F=B7=E5=8C=96=E9=96=A2?= =?UTF-8?q?=E9=80=A3=E3=81=AE=E8=BB=BD=E5=BE=AE=E3=81=AA=E3=83=90=E3=82=B0?= =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E3=81=A8=E6=9B=B8=E3=81=8D=E6=8F=9B=E3=81=88?= =?UTF-8?q?=20=E4=BB=A5=E4=B8=8B=E3=81=AE=E3=82=88=E3=81=86=E3=81=AA?= =?UTF-8?q?=E3=82=A8=E3=82=A4=E3=83=AA=E3=82=A2=E3=82=B9=E3=82=92=E8=BF=BD?= =?UTF-8?q?=E5=8A=A0=20`Packet::header=5Fbytes=20=3D=20std::array`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/Packet.h | 13 +++++----- include/Socket.h | 62 +++++++++++++++++------------------------------- include/common.h | 5 ++-- 3 files changed, 31 insertions(+), 49 deletions(-) diff --git a/include/Packet.h b/include/Packet.h index 6bb510f..2ea81fb 100644 --- a/include/Packet.h +++ b/include/Packet.h @@ -100,6 +100,7 @@ struct Packet { using byte_t = SocketDetail::byte_t; using bytearray = SocketDetail::bytearray; + using header_bytes = SocketDetail::cbytearray; using byte_view = SocketDetail::byte_view; using byte_ref = SocketDetail::byte_ref; @@ -146,33 +147,33 @@ struct Packet { template Packet(enumT type, const char(&data)[len]) requires (is_enum32) : Packet(static_cast(type), std::addressof(data), len - 1) {} template - Packet(const char(&data)[len]) : Packet(Header::type_hash_code(), std::addressof(data), len - 1) {} + explicit Packet(const char(&data)[len]) : Packet(Header::type_hash_code(), std::addressof(data), len - 1) {} Packet(uint32_t id, const std::string& data) : Packet(id, data.data(), data.size()) {} template Packet(enumT type, const std::string& data) requires (is_enum32) : Packet(type, data.data(), data.size()) {} - Packet(const std::string& data) : Packet(Header::type_hash_code(), data.data(), data.size()) {} + explicit Packet(const std::string& data) : Packet(Header::type_hash_code(), data.data(), data.size()) {} template Packet(uint32_t id, const T& data) requires (memcpyable && !cross_convertible) : Packet(id, std::addressof(data), sizeof(T)) {} template Packet(enumT type, const T& data) requires (is_enum32&& memcpyable && !cross_convertible) : Packet(static_cast(type), std::addressof(data), sizeof(T)) {} template - Packet(const T& data) requires (memcpyable && !cross_convertible) : Packet(Header::type_hash_code(), std::addressof(data), sizeof(T)) {} + explicit Packet(const T& data) requires (memcpyable && !cross_convertible) : Packet(Header::type_hash_code(), std::addressof(data), sizeof(T)) {} template Packet(uint32_t id, const std::vector& data) requires (memcpyable && !cross_convertible) : Packet(id, data.data(), data.size() * sizeof(T)) {} template Packet(enumT type, const std::vector& data) requires (is_enum32&& memcpyable && !cross_convertible) : Packet(static_cast(type), data.data(), data.size() * sizeof(T)) {} template - Packet(const std::vector& data) requires (memcpyable && !cross_convertible) : Packet(Header::type_hash_code>(), data.data(), data.size() * sizeof(T)) {} + explicit Packet(const std::vector& data) requires (memcpyable && !cross_convertible) : Packet(Header::type_hash_code>(), data.data(), data.size() * sizeof(T)) {} template Packet(uint32_t id, const T& data) requires (cross_convertible) : Packet(id, Convert(data)); template Packet(enumT type, const T& data) requires (is_enum32&& cross_convertible) : Packet(static_cast(type), data) {} template - Packet(const T& data) requires (cross_convertible) : Packet(Header::type_hash_code(), data) {} + explicit Packet(const T& data) requires (cross_convertible) : Packet(Header::type_hash_code(), data) {} template Packet(uint32_t id, const std::vector& data) requires (cross_convertible) { @@ -187,7 +188,7 @@ struct Packet { template Packet(enumT type, const std::vector& data) requires (is_enum32&& cross_convertible) : Packet(static_cast(type), data) {} template - Packet(const std::vector& data) requires (cross_convertible) : Packet(Header::type_hash_code>(), data) {} + explicit Packet(const std::vector& data) requires (cross_convertible) : Packet(Header::type_hash_code>(), data) {} Packet(uint32_t id, std::ifstream& ifs) { diff --git a/include/Socket.h b/include/Socket.h index 496a17b..c62c5b2 100644 --- a/include/Socket.h +++ b/include/Socket.h @@ -232,19 +232,6 @@ class WinSock { #endif - -/// -/// Socket Base -/// - -struct SocketTraits { - using bytearray = std::vector; - - template - using memcpyable = std::enable_if_t::value, T>; - -}; - template class SocketBase { public: @@ -381,10 +368,10 @@ class basic_TCPSocket : public sockbase { public: - using bytearray = typename SocketTraits::bytearray; + using bytearray = SocketDetail::bytearray; template - using stdlayout = typename SocketTraits::memcpyable; + static constexpr bool memcpyable = SocketDetail::memcpyable; basic_TCPSocket() : sockbase() {} basic_TCPSocket(typename sockbase::IPType addr) : basic_TCPSocket() { @@ -508,10 +495,10 @@ class basic_TCPSocket : public sockbase { return true; } - bool Send(const bytearray& src) { + bool Send(SocketDetail::byte_view src) { return RawSend(src.data(), static_cast(src.size())); } - bool Recv(bytearray& dest) { + bool Recv(SocketDetail::byte_ref dest) { if (dest.empty()) { return false; } return RawRecv(dest.data(), static_cast(dest.size())); } @@ -523,24 +510,23 @@ class basic_TCPSocket : public sockbase { return Send(src.GetRawPacket()); } std::optional Recv() { - bytearray head(Packet::HeaderSize); - if (!Recv(head)) { + Packet::header_bytes headbuf{}; + if (!Recv(headbuf)) { return std::nullopt; } - Packet pak; - pak.SetBuffer(std::move(head)); - bytearray data(pak.GetHeader()->Size); + Header head = std::bit_cast
(headbuf); + bytearray data(head.Size); if (!Recv(data)) { return std::nullopt; } - return Packet(pak.GetHeader()->Type, data); + return Packet(head.Type, data); } - bool EncryptionSend(const bytearray& src) { - bytearray target; + bool EncryptionSend(SocketDetail::byte_view src) { + bytearray target(src.size()); return Encrypt(src, target) && Send(target); } - bool EncryptionRecv(bytearray& dest) { + bool EncryptionRecv(SocketDetail::byte_ref dest) { return Recv(dest) && Decrypt(dest, dest); } @@ -548,23 +534,19 @@ class basic_TCPSocket : public sockbase { if (src.CheckHeader()) { return false; } - bytearray data(src.GetRawPacket().begin() + Packet::HeaderSize, src.GetRawPacket().end()); - bool flag = Encrypt(data, data); - Packet pak = Packet(src.GetHeader()->Type, data); - return flag && Send(pak); + return EncryptionSend(*src.GetRawData()); } std::optional EncryptionRecv() { - bytearray head(Packet::HeaderSize); - if (!Recv(head)) { + Packet::header_bytes headbuf{}; + if (!Recv(headbuf)) { return std::nullopt; } - Packet pak; - pak.SetBuffer(std::move(head)); - bytearray data(pak.GetHeader()->Size); + Header head = std::bit_cast
(headbuf); + bytearray data(head.Size); if (!EncryptionRecv(data)) { return std::nullopt; } - return Packet(pak.GetHeader()->Type, data); + return Packet(head.Type, data); } std::future ASyncSend(const bytearray& src) { @@ -612,22 +594,22 @@ class basic_TCPSocket : public sockbase { } template - bool _Send(const stdlayout& target) { + bool _Send(const T& target) requires (memcpyable) { return RawSend(&target, sizeof(T)); } template - bool _Recv(stdlayout& target) { + bool _Recv(T& target) requires (memcpyable) { return RawRecv(&target, sizeof(T)); } template - std::future _ASyncSend(const stdlayout& target) { + std::future _ASyncSend(const T& target) requires (memcpyable) { return std::async(std::launch::async, [this, target]() { return this->_Send(target); }); } template - std::future _ASyncRecv(stdlayout& target) { + std::future _ASyncRecv(T& target) requires (memcpyable) { return std::async(std::launch::async, [this, &target]() { return this->_Recv(target); }); diff --git a/include/common.h b/include/common.h index 716b8bc..2838ed5 100644 --- a/include/common.h +++ b/include/common.h @@ -23,6 +23,8 @@ namespace SocketDetail { using byte_ref = std::span; using bytearray = std::vector; + template + using cbytearray = std::array; template concept enum32 = std::is_enum_v && (sizeof(T) == sizeof(uint32_t)); @@ -42,7 +44,4 @@ namespace SocketDetail { template concept cross_convertible = to_byteable && from_byteable; - - - } From 6795d2ac92d95c1311d294f1fe135844e0a80f0c Mon Sep 17 00:00:00 2001 From: barrier Date: Tue, 10 Feb 2026 19:38:17 +0900 Subject: [PATCH 11/21] =?UTF-8?q?=E5=8B=95=E4=BD=9C=E3=83=86=E3=82=B9?= =?UTF-8?q?=E3=83=88=E5=AE=8C=E4=BA=86=20=E3=83=90=E3=82=B0=E3=81=8C?= =?UTF-8?q?=E6=BD=9C=E3=82=93=E3=81=A7=E3=81=84=E3=81=9F=E3=81=AE=E3=81=A7?= =?UTF-8?q?=E6=91=98=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Socket.cpp | 241 +++++++++++++++++++++++++++++++----- example/Network/Network.cpp | 8 +- include/Packet.h | 10 +- include/Socket.h | 3 +- 4 files changed, 220 insertions(+), 42 deletions(-) diff --git a/Socket.cpp b/Socket.cpp index a436547..475d60b 100644 --- a/Socket.cpp +++ b/Socket.cpp @@ -1,49 +1,228 @@ -#include -#include -#include +#include "include/Socket.h" #include -#include "include/Socket.h" -#include "include/Cryptgraphy/KeyManager.h" +void Server(); +void Client(); + +AES128::cbytearray<16> sharedkey = {'0', 'x', '7', '4', '0', 'x', '6', '5', '0', 'x', '7', '3', '0', 'x', '7', '4',}; + +struct ClientData { + + int Level = 0; + std::string Name = "NoName"; + + Packet::bytearray ToBytes() const { + Packet::bytearray ret; + Packet::StoreBytes(ret, Level); + Packet::StoreBytes(ret, Name); + return ret; + } + + Packet::byte_view FromBytes(Packet::byte_view view) { + Packet::LoadBytes(view, Level); + Packet::LoadBytes(view, Name); + return view; + } +}; int main(int argc, char* argv[]) { - - using int_t = bigint<2048>; - int_t a = 0x123456789abcdef0; - a = a.Pow(0xffffffff); - int_t b = a.Pow(0xffffffff); + // arg[1]{ 0 = server, 1 = client } - auto time = [&]() { - return std::chrono::high_resolution_clock::now(); - }; + std::vector args; + args.insert(args.end(), argv, argv + argc); - std::cout << "condition:" << std::endl; - std::cout << "max digits: 2^" << int_t::AllBits << std::endl; - std::cout << "a = 0x123456789abcdef0^0xffffffff" << std::endl; - std::cout << "b = a^0xffffffff" << std::endl; - std::cout << "ret = a * b" << std::endl << std::endl; + if (args.size() <= 1) { + return -1; + } - auto tp = time(); + if (std::stoi(args[1]) == 0) { + Server(); + } + else { + Client(); + } - int_t ret = int_t::NormalMul(a, b); + return 0; +} - double t = std::chrono::duration_cast(time() - tp).count(); +void Server() { - std::cout << "Normal: " << t / 1000 << "us" << std::endl; - //std::cout << ret.ToString(16, true, false) << std::endl; + TCPServer server(8080); - tp = time(); + std::map> clients; + std::vector> joinqueue; + std::deque lostqueue; - ret = int_t::Karatuba(a, b); + while (true) { + auto sock = server.Accept(); - t = std::chrono::duration_cast(time() - tp).count(); + if (sock) { + bool emptyfound = false; + for (auto&& state : joinqueue) { + if (!state) { + state = std::move(*sock); + emptyfound = true; + break; + } + } + if (!emptyfound) { + joinqueue.push_back(std::move(*sock)); + } + } - std::cout << "Karatuba: " << t / 1000 << "us" << std::endl; - //std::cout << ret.ToString(16, true, false) << std::endl; + for (auto&& [_, pair] : clients) { + auto&& [c, cd] = pair; + if (c.LostConnection()) { + lostqueue.push_back(&c); + std::cout << "lost connection: " << cd.Name << std::endl; + } + } - // before: 2.0759ms - // after : + for (auto&& c : joinqueue) { - return 0; + if (!c) { + continue; + } + + if (c->Available() <= 0) { + continue; + } + + c->CryptEngine.Init(sharedkey); + + auto cd = c->EncryptionRecv()->Get(); + + if (cd) { + std::cout << "connected: " << cd->Name << std::endl; + auto addr = c->GetPeerAddress(); + clients[*addr] = {std::move(*c), std::move(*cd)}; + c.reset(); + } + } + + while (!lostqueue.empty()) { + auto p = lostqueue.front(); + lostqueue.pop_front(); + + clients.erase(*p->GetPeerAddress()); + } + + for (auto&& [_, pair] : clients) { + auto&& [c, cd] = pair; + + int available = c.Available(); + + if (available <= 0) { + continue; + } + + auto val = c.EncryptionRecv(); + + if (!val) { + continue; + } + + std::string send = cd.Name + "(" + std::to_string(cd.Level) + "): " + *val->Get(); + + std::cout << send << std::endl; + + for (auto&& [_, topair] : clients) { + auto&& [oc, __] = topair; + if (oc == c) { + continue; + } + oc.EncryptionSend(Packet(send)); + } + } + } +} + +void Client() { + + TCPSocket server; + + std::cout << "input connect server address" << std::endl; + std::string str_addr; + std::cin >> str_addr; + + auto op_addr = IPAddress::SolveHostName(str_addr); + + if (!op_addr) { + std::cout << "can't solved address" << std::endl; + return; + } + + std::cout << "input port" << std::endl; + unsigned short port; + std::cin >> port; + + if (server.Connect(op_addr->Port(port))) { + std::cout << "connected server." << std::endl; + } + else { + std::cout << "can't connect server." << std::endl; + return; + } + + server.CryptEngine.Init(sharedkey); + + ClientData _data; + + std::cout << "input your Level\n"; + std::cin >> _data.Level; + std::cout << "input your Name\n"; + std::cin >> _data.Name; + + Packet p = Packet(_data); + + server.EncryptionSend(p); + + bool stopflag = false; + + std::mutex mtx; + + std::thread inputthread = std::thread{ + [&] { + while (!stopflag) { + std::string sendval; + std::cin >> sendval; + + if (sendval == "/exit") { + stopflag = true; + break; + } + + std::lock_guard lock(mtx); + + server.EncryptionSend(Packet(sendval)); + } + } + }; + + while (!stopflag) { + + if (server.LostConnection()) { + break; + } + + if (server.Available() <= 0) { + continue; + } + + auto pak = server.EncryptionRecv(); + + if (!pak) { + continue; + } + + std::lock_guard lock(mtx); + + auto val = *pak->Get(); + std::cout << val << std::endl; + } + + stopflag = true; + + inputthread.join(); } diff --git a/example/Network/Network.cpp b/example/Network/Network.cpp index 5578b03..cd83118 100644 --- a/example/Network/Network.cpp +++ b/example/Network/Network.cpp @@ -1,4 +1,5 @@ #include "include/Socket.h" +#include void Server(); void Client(); @@ -131,7 +132,7 @@ void Server() { if (oc == c) { continue; } - oc.EncryptionSend(send); + oc.EncryptionSend(Packet(send)); } } } @@ -194,8 +195,7 @@ void Client() { std::lock_guard lock(mtx); - Packet pak = Packet(sendval); - server.EncryptionSend(sendval); + server.EncryptionSend(Packet(sendval)); } } }; @@ -226,5 +226,3 @@ void Client() { inputthread.join(); } - - diff --git a/include/Packet.h b/include/Packet.h index 2ea81fb..6b73884 100644 --- a/include/Packet.h +++ b/include/Packet.h @@ -123,9 +123,9 @@ struct Packet { static constexpr bool cross_convertible = SocketDetail::cross_convertible; Packet() {}; - Packet(const Packet&) = delete; + Packet(const Packet&) = default; Packet(Packet&&) = default; - Packet& operator=(const Packet&) = delete; + Packet& operator=(const Packet&) = default; Packet& operator=(Packet&&) = default; Packet(uint32_t id, const void* src, uint32_t size) { @@ -169,7 +169,7 @@ struct Packet { explicit Packet(const std::vector& data) requires (memcpyable && !cross_convertible) : Packet(Header::type_hash_code>(), data.data(), data.size() * sizeof(T)) {} template - Packet(uint32_t id, const T& data) requires (cross_convertible) : Packet(id, Convert(data)); + Packet(uint32_t id, const T& data) requires (cross_convertible) : Packet(id, Convert(data)) {}; template Packet(enumT type, const T& data) requires (is_enum32&& cross_convertible) : Packet(static_cast(type), data) {} template @@ -214,13 +214,13 @@ struct Packet { if (CheckHeader()) { return std::nullopt; } - return byte_view(m_buffer.begin(), m_buffer.end()).first(HeaderSize); + return byte_view(m_buffer.begin(), m_buffer.end()).subspan(HeaderSize); } std::optional RefRawData() { if (CheckHeader()) { return std::nullopt; } - return byte_ref(m_buffer.begin(), m_buffer.end()).first(HeaderSize); + return byte_ref(m_buffer.begin(), m_buffer.end()).subspan(HeaderSize); } std::optional
GetHeader() const { diff --git a/include/Socket.h b/include/Socket.h index c62c5b2..2297e80 100644 --- a/include/Socket.h +++ b/include/Socket.h @@ -534,7 +534,8 @@ class basic_TCPSocket : public sockbase { if (src.CheckHeader()) { return false; } - return EncryptionSend(*src.GetRawData()); + auto head = std::bit_cast(*src.GetHeader()); + return Send(head) && EncryptionSend(*src.GetRawData()); } std::optional EncryptionRecv() { Packet::header_bytes headbuf{}; From 69f0ae7bda4f365db108780aaf87d5f63db8f3f3 Mon Sep 17 00:00:00 2001 From: barrier Date: Tue, 10 Feb 2026 19:51:08 +0900 Subject: [PATCH 12/21] =?UTF-8?q?=E5=90=8D=E5=89=8D=E7=A9=BA=E9=96=93?= =?UTF-8?q?=E9=96=A2=E9=80=A3=E3=81=AE=E5=A4=89=E6=9B=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/Socket.h | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/include/Socket.h b/include/Socket.h index 2297e80..7c8d0e6 100644 --- a/include/Socket.h +++ b/include/Socket.h @@ -21,7 +21,7 @@ #include "common.h" #ifdef SOCKET_H_USE_NAMESPACE -namespace NetIO { +namespace Socket { #endif // SOCKET_H_USE_NAMESPACE #include "Cryptgraphy/AES128.h" @@ -369,6 +369,8 @@ class basic_TCPSocket : public sockbase { public: using bytearray = SocketDetail::bytearray; + using byte_view = SocketDetail::byte_view; + using byte_ref = SocketDetail::byte_ref; template static constexpr bool memcpyable = SocketDetail::memcpyable; @@ -495,10 +497,10 @@ class basic_TCPSocket : public sockbase { return true; } - bool Send(SocketDetail::byte_view src) { + bool Send(byte_view src) { return RawSend(src.data(), static_cast(src.size())); } - bool Recv(SocketDetail::byte_ref dest) { + bool Recv(byte_ref dest) { if (dest.empty()) { return false; } return RawRecv(dest.data(), static_cast(dest.size())); } @@ -522,11 +524,11 @@ class basic_TCPSocket : public sockbase { return Packet(head.Type, data); } - bool EncryptionSend(SocketDetail::byte_view src) { + bool EncryptionSend(byte_view src) { bytearray target(src.size()); return Encrypt(src, target) && Send(target); } - bool EncryptionRecv(SocketDetail::byte_ref dest) { + bool EncryptionRecv(byte_ref dest) { return Recv(dest) && Decrypt(dest, dest); } @@ -550,12 +552,12 @@ class basic_TCPSocket : public sockbase { return Packet(head.Type, data); } - std::future ASyncSend(const bytearray& src) { + std::future ASyncSend(byte_view src) { return std::async(std::launch::async, [&]() { return this->Send(src); }); } - std::future ASyncRecv(bytearray& dest) { + std::future ASyncRecv(byte_ref dest) { return std::async(std::launch::async, [&]() { return this->Recv(dest); }); @@ -572,12 +574,12 @@ class basic_TCPSocket : public sockbase { }); } - std::future ASyncEncryptionSend(const bytearray& src) { + std::future ASyncEncryptionSend(byte_view src) { return std::async(std::launch::async, [&]() { return this->EncryptionSend(src); }); } - std::future ASyncEncryptionRecv(bytearray& dest) { + std::future ASyncEncryptionRecv(byte_ref dest) { return std::async(std::launch::async, [&]() { return this->EncryptionRecv(dest); }); From 84ca50125863bcf33d77d92a29f081bbe4925681 Mon Sep 17 00:00:00 2001 From: barrier Date: Tue, 10 Feb 2026 20:19:35 +0900 Subject: [PATCH 13/21] =?UTF-8?q?Poll=E9=96=A2=E6=95=B0=E3=81=AB=E3=82=BF?= =?UTF-8?q?=E3=82=A4=E3=83=A0=E3=82=A2=E3=82=A6=E3=83=88=E3=82=92=E6=8C=87?= =?UTF-8?q?=E5=AE=9A=E3=81=A7=E3=81=8D=E3=82=8B=E3=82=88=E3=81=86=E3=81=AB?= =?UTF-8?q?=E3=81=97=E3=81=9F(=E4=BB=8A=E6=9B=B4)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/Socket.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/include/Socket.h b/include/Socket.h index 7c8d0e6..c94b913 100644 --- a/include/Socket.h +++ b/include/Socket.h @@ -325,9 +325,9 @@ class SocketBase { static int Poll(poll_t* fds, unsigned int nfds, int timeout) { #ifdef _MSC_BUILD - int ret = WSAPoll(fds, nfds, 0); + int ret = WSAPoll(fds, nfds, timeout); #else - int ret = poll(fds, nfds, 0); + int ret = poll(fds, nfds, timeout); #endif // _MSC_BUILD return ret; } From 5e314abaf5c4fc0095918a913fb2f25a3318a1dd Mon Sep 17 00:00:00 2001 From: barrier <110488117+barrier15300@users.noreply.github.com> Date: Tue, 10 Feb 2026 20:45:41 +0900 Subject: [PATCH 14/21] Update include/Packet.h Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> --- include/Packet.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/Packet.h b/include/Packet.h index 6b73884..7f15eb4 100644 --- a/include/Packet.h +++ b/include/Packet.h @@ -186,7 +186,7 @@ struct Packet { *this = Packet(id, b.data(), b.size()); } template - Packet(enumT type, const std::vector& data) requires (is_enum32&& cross_convertible) : Packet(static_cast(type), data) {} + Packet(enumT type, const std::vector& data) requires (is_enum32&& cross_convertible) : Packet(static_cast(type), data) {} template explicit Packet(const std::vector& data) requires (cross_convertible) : Packet(Header::type_hash_code>(), data) {} From 5928253e607f28915d427fe0e2b0bd228a7f3abf Mon Sep 17 00:00:00 2001 From: barrier Date: Tue, 10 Feb 2026 20:59:28 +0900 Subject: [PATCH 15/21] =?UTF-8?q?=E6=AD=A3=E3=81=97=E3=81=84=E3=83=87?= =?UTF-8?q?=E3=83=BC=E3=82=BF=E3=82=92=E8=AA=AD=E3=81=BF=E5=87=BA=E3=81=95?= =?UTF-8?q?=E3=81=AA=E3=81=84=E7=8A=B6=E6=85=8B=E3=81=AB=E3=81=AA=E3=81=A3?= =?UTF-8?q?=E3=81=A6=E3=81=9F=E3=81=AE=E3=81=A7=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/Packet.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/Packet.h b/include/Packet.h index 6b73884..1b5b94d 100644 --- a/include/Packet.h +++ b/include/Packet.h @@ -279,7 +279,7 @@ struct Packet { return std::nullopt; } std::vector ret; - byte_view view = byte_view(m_buffer.begin(), HeaderSize); + byte_view view = byte_view(m_buffer).subspan(HeaderSize); while (view.begin() < view.end()) { auto&& [elem, last] = Convert(view); ret.push_back(std::move(elem)); From e2ce8418d533dbf47bed85ec06dc96e03ce83894 Mon Sep 17 00:00:00 2001 From: barrier Date: Tue, 10 Feb 2026 21:07:25 +0900 Subject: [PATCH 16/21] =?UTF-8?q?=E3=83=80=E3=83=B3=E3=82=B0=E3=83=AA?= =?UTF-8?q?=E3=83=B3=E3=82=B0=E3=81=8C=E7=99=BA=E7=94=9F=E3=81=99=E3=82=8B?= =?UTF-8?q?=E9=83=A8=E5=88=86=E3=82=92=E4=BF=AE=E6=AD=A3=20=E3=81=9F?= =?UTF-8?q?=E3=81=A0=E3=80=81=E3=81=93=E3=81=AE=E6=96=B9=E5=BC=8F=E3=81=AE?= =?UTF-8?q?=E9=9D=9E=E5=90=8C=E6=9C=9F=E3=81=AF=E3=81=8A=E3=81=9D=E3=82=89?= =?UTF-8?q?=E3=81=8F=E4=BD=BF=E3=81=84=E3=81=A5=E3=82=89=E3=81=84=E3=81=AE?= =?UTF-8?q?=E3=81=A7=E4=BB=8A=E5=BE=8C=E4=BD=BF=E3=81=84=E3=82=84=E3=81=99?= =?UTF-8?q?=E3=81=84=E3=81=AE=E3=82=92=E4=BD=9C=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/Socket.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/include/Socket.h b/include/Socket.h index c094a68..b33a1bc 100644 --- a/include/Socket.h +++ b/include/Socket.h @@ -563,12 +563,12 @@ class basic_TCPSocket : public sockbase { } std::future ASyncSend(byte_view src) { - return std::async(std::launch::async, [&]() { + return std::async(std::launch::async, [=]() { return this->Send(src); }); } std::future ASyncRecv(byte_ref dest) { - return std::async(std::launch::async, [&]() { + return std::async(std::launch::async, [=]() { return this->Recv(dest); }); } @@ -585,12 +585,12 @@ class basic_TCPSocket : public sockbase { } std::future ASyncEncryptionSend(byte_view src) { - return std::async(std::launch::async, [&]() { + return std::async(std::launch::async, [=]() { return this->EncryptionSend(src); }); } std::future ASyncEncryptionRecv(byte_ref dest) { - return std::async(std::launch::async, [&]() { + return std::async(std::launch::async, [=]() { return this->EncryptionRecv(dest); }); } From 65b219732509293bb090ed064f8b1e9ca42d0d56 Mon Sep 17 00:00:00 2001 From: barrier Date: Tue, 10 Feb 2026 21:24:52 +0900 Subject: [PATCH 17/21] =?UTF-8?q?=E3=83=90=E3=83=83=E3=83=95=E3=82=A1?= =?UTF-8?q?=E7=AF=84=E5=9B=B2=E5=A4=96=E3=82=92=E5=8F=82=E7=85=A7=E3=81=99?= =?UTF-8?q?=E3=82=8B=E5=8F=AF=E8=83=BD=E6=80=A7=E3=82=92=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/Packet.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/include/Packet.h b/include/Packet.h index b2035e8..bcda956 100644 --- a/include/Packet.h +++ b/include/Packet.h @@ -211,13 +211,13 @@ struct Packet { const bytearray& GetRawPacket() const { return m_buffer; } std::optional GetRawData() const { - if (CheckHeader()) { + if (CheckHeader(0)) { return std::nullopt; } return byte_view(m_buffer.begin(), m_buffer.end()).subspan(HeaderSize); } std::optional RefRawData() { - if (CheckHeader()) { + if (CheckHeader(0)) { return std::nullopt; } return byte_ref(m_buffer.begin(), m_buffer.end()).subspan(HeaderSize); @@ -269,7 +269,7 @@ struct Packet { } size_t dataSize = (m_buffer.size() - HeaderSize) / sizeof(T); std::vector data(dataSize); - std::memcpy(data.data(), m_buffer.data() + HeaderSize, m_buffer.size() - HeaderSize); + std::memcpy(data.data(), m_buffer.data() + HeaderSize, dataSize * sizeof(T)); return data; } From b597a91bfc2e3da980c999fb474180694c5682ad Mon Sep 17 00:00:00 2001 From: barrier Date: Tue, 10 Feb 2026 21:42:34 +0900 Subject: [PATCH 18/21] =?UTF-8?q?=E5=8F=AF=E5=A4=89=E9=95=B7=E7=89=88?= =?UTF-8?q?=E3=82=92=E4=BD=9C=E6=88=90=E3=81=99=E3=82=8B=E3=83=A1=E3=83=AA?= =?UTF-8?q?=E3=83=83=E3=83=88=E3=81=8C=E4=BB=8A=E3=81=AE=E3=81=A8=E3=81=93?= =?UTF-8?q?=E3=82=8D=E5=AD=98=E5=9C=A8=E3=81=97=E3=81=AA=E3=81=84=E3=81=9F?= =?UTF-8?q?=E3=82=81=E7=84=A1=E5=8A=B9=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/Cryptgraphy/MultiWordInt.h | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/include/Cryptgraphy/MultiWordInt.h b/include/Cryptgraphy/MultiWordInt.h index aaa8c96..ae254ac 100644 --- a/include/Cryptgraphy/MultiWordInt.h +++ b/include/Cryptgraphy/MultiWordInt.h @@ -745,6 +745,7 @@ struct bigint { arr_t* m_words = new arr_t(); }; +#if 0 /// /// variable-size @@ -953,4 +954,6 @@ struct bigint<0, _sign> { arr_t m_words{}; -}; \ No newline at end of file +}; + +#endif \ No newline at end of file From d51c3d0ba0939d588780ae0ff72c0c29970abdcc Mon Sep 17 00:00:00 2001 From: barrier Date: Wed, 11 Feb 2026 00:08:35 +0900 Subject: [PATCH 19/21] =?UTF-8?q?=E5=A4=9A=E5=80=8D=E9=95=B7=E6=95=B4?= =?UTF-8?q?=E6=95=B0=E3=81=AE=E8=BB=BD=E5=BE=AE=E3=81=AA=E3=81=8A=E6=89=8B?= =?UTF-8?q?=E5=85=A5=E3=82=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/Cryptgraphy/MultiWordInt.h | 69 ++++++++---------------------- include/Socket.h | 24 +++++------ 2 files changed, 30 insertions(+), 63 deletions(-) diff --git a/include/Cryptgraphy/MultiWordInt.h b/include/Cryptgraphy/MultiWordInt.h index ae254ac..d0aa246 100644 --- a/include/Cryptgraphy/MultiWordInt.h +++ b/include/Cryptgraphy/MultiWordInt.h @@ -85,7 +85,15 @@ struct bigint { /// Assignment Operator Module constexpr bigint& operator=(const bigint& from) noexcept { *m_words = *from.m_words; return *this; } - constexpr bigint& operator=(bigint&& from) noexcept { delete m_words; m_words = from.m_words; from.m_words = nullptr; return *this; } + constexpr bigint& operator=(bigint&& from) noexcept { + if (from.m_words == m_words) { + return *this; + } + delete m_words; + m_words = from.m_words; + from.m_words = nullptr; + return *this; + } constexpr bigint& operator=(word_t from) noexcept requires(!IsSigned) { *this = std::move(bigint(from)); return *this; @@ -214,13 +222,16 @@ struct bigint { template requires (std::is_convertible_v>) constexpr bigint& FromWords(R&& r) { - auto fb = std::ranges::begin(r); - auto fe = std::ranges::end(r); - for (auto& elem : words()) { - if (fb == fe) { + auto beg = m_words->begin(); + auto end = m_words->end(); + for (const auto&& elem : r) { + if (beg == end) { break; } - elem = *(fb++); + *(beg++) = elem; + } + for (; beg != end; ++beg) { + *beg = 0; } return *this; } @@ -317,7 +328,7 @@ struct bigint { return ret; } - static constexpr bigint Karatuba_Legacy(const bigint& x, const bigint& y) { + static constexpr bigint Karatuba(const bigint& x, const bigint& y) { bigint ret = 0; if (x == 0 || y == 0) { @@ -363,50 +374,6 @@ struct bigint { return ret; } - static constexpr bigint Karatuba(const bigint& x, const bigint& y) { - if (x == 0 || y == 0) { - return bigint(0); - } - - bigint t[4]{}; - - bigint z0; - bigint z1; - bigint z2; - - auto rec = [&](auto&& self, arr_view vx, arr_view vy) -> bigint& { - - count_t halfwords = vx.size() >> 1; - - if (halfwords <= 1) { - auto [low, high] = MulBase(vx.front(), vy.front()); - word_t words[2] = {low, high}; - return z0.FromWords(words); - } - - arr_view xl = vx.subspan(0, halfwords); - arr_view xh = vx.subspan(halfwords); - arr_view yl = vy.subspan(0, halfwords); - arr_view yh = vy.subspan(halfwords); - - z0 = self(self, xl, yl); - z2 = self(self, xh, yh); - - t[0].FromWords(xl) += t[2].FromWords(xh); - t[1].FromWords(yl) += t[2].FromWords(yh); - - xl = arr_view(t[0].words()).subspan(halfwords); - yl = arr_view(t[1].words()).subspan(halfwords); - - z1 = self(self, xl, yl); - z1 -= z0; - z1 -= z2; - - return z0.AssignAdd(z1.AssignLeftShift(halfwords * WordBits)).AssignAdd(z2.AssignLeftShift(2 * halfwords * WordBits)); - }; - - return rec(rec, x.words(), y.words()); - } constexpr bigint& AssignMul(bigint src) { return *this = NormalMul(*this, src); } diff --git a/include/Socket.h b/include/Socket.h index b33a1bc..3258070 100644 --- a/include/Socket.h +++ b/include/Socket.h @@ -562,9 +562,9 @@ class basic_TCPSocket : public sockbase { return Packet(head.Type, data); } - std::future ASyncSend(byte_view src) { - return std::async(std::launch::async, [=]() { - return this->Send(src); + std::future ASyncSend(bytearray&& src) { + return std::async(std::launch::async, [target = std::move(src)]() { + return this->Send(target); }); } std::future ASyncRecv(byte_ref dest) { @@ -573,9 +573,9 @@ class basic_TCPSocket : public sockbase { }); } - std::future ASyncSend(const Packet& src) { - return std::async(std::launch::async, [&]() { - return this->Send(src); + std::future ASyncSend(Packet&& src) { + return std::async(std::launch::async, [target = std::move(src)]() { + return this->Send(target); }); } std::future> ASyncRecv() { @@ -584,9 +584,9 @@ class basic_TCPSocket : public sockbase { }); } - std::future ASyncEncryptionSend(byte_view src) { - return std::async(std::launch::async, [=]() { - return this->EncryptionSend(src); + std::future ASyncEncryptionSend(bytearray&& src) { + return std::async(std::launch::async, [target = std::move(src)]() { + return this->EncryptionSend(target); }); } std::future ASyncEncryptionRecv(byte_ref dest) { @@ -595,9 +595,9 @@ class basic_TCPSocket : public sockbase { }); } - std::future ASyncEncryptionSend(const Packet& src) { - return std::async(std::launch::async, [&]() { - return this->EncryptionSend(src); + std::future ASyncEncryptionSend(Packet&& src) { + return std::async(std::launch::async, [target = std::move(src)]() { + return this->EncryptionSend(target); }); } std::future> ASyncEncryptionRecv() { From 346652a2ec92cff7c28809ebf8020d94877af97d Mon Sep 17 00:00:00 2001 From: barrier Date: Wed, 11 Feb 2026 00:38:04 +0900 Subject: [PATCH 20/21] =?UTF-8?q?=E4=BB=96=E7=92=B0=E5=A2=83=E3=81=AE?= =?UTF-8?q?=E3=82=B3=E3=83=B3=E3=83=91=E3=82=A4=E3=83=AB=E3=82=A8=E3=83=A9?= =?UTF-8?q?=E3=83=BC=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/Socket.h | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/include/Socket.h b/include/Socket.h index 3258070..5dbd5b9 100644 --- a/include/Socket.h +++ b/include/Socket.h @@ -563,18 +563,18 @@ class basic_TCPSocket : public sockbase { } std::future ASyncSend(bytearray&& src) { - return std::async(std::launch::async, [target = std::move(src)]() { + return std::async(std::launch::async, [&, target = std::move(src)]() { return this->Send(target); }); } std::future ASyncRecv(byte_ref dest) { - return std::async(std::launch::async, [=]() { + return std::async(std::launch::async, [=, this]() { return this->Recv(dest); }); } std::future ASyncSend(Packet&& src) { - return std::async(std::launch::async, [target = std::move(src)]() { + return std::async(std::launch::async, [&, target = std::move(src)]() { return this->Send(target); }); } @@ -585,18 +585,18 @@ class basic_TCPSocket : public sockbase { } std::future ASyncEncryptionSend(bytearray&& src) { - return std::async(std::launch::async, [target = std::move(src)]() { + return std::async(std::launch::async, [&, target = std::move(src)]() { return this->EncryptionSend(target); }); } std::future ASyncEncryptionRecv(byte_ref dest) { - return std::async(std::launch::async, [=]() { + return std::async(std::launch::async, [=, this]() { return this->EncryptionRecv(dest); }); } std::future ASyncEncryptionSend(Packet&& src) { - return std::async(std::launch::async, [target = std::move(src)]() { + return std::async(std::launch::async, [&, target = std::move(src)]() { return this->EncryptionSend(target); }); } From 37baadf369d68c86a2155b06b57dfdf92b5825b2 Mon Sep 17 00:00:00 2001 From: barrier Date: Tue, 17 Feb 2026 18:31:04 +0900 Subject: [PATCH 21/21] =?UTF-8?q?=E5=8F=97=E4=BF=A1=E3=81=97=E3=81=9F?= =?UTF-8?q?=E3=83=90=E3=82=A4=E3=83=88=E5=88=97=E3=82=92=E5=8F=97=E3=81=91?= =?UTF-8?q?=E5=8F=96=E3=81=A3=E3=81=A6Packet=E3=82=AA=E3=83=96=E3=82=B8?= =?UTF-8?q?=E3=82=A7=E3=82=AF=E3=83=88=E3=82=92=E7=94=9F=E6=88=90=E3=81=99?= =?UTF-8?q?=E3=82=8B=E9=96=A2=E6=95=B0=E3=82=92=E8=BF=BD=E5=8A=A0=20?= =?UTF-8?q?=E3=83=AB=E3=83=83=E3=82=AF=E3=82=A2=E3=83=83=E3=83=97=E3=83=86?= =?UTF-8?q?=E3=83=BC=E3=83=96=E3=83=AB=E3=81=AB=E8=AA=A4=E3=82=8A=E3=81=8C?= =?UTF-8?q?=E3=81=82=E3=81=A3=E3=81=9F=E3=81=AE=E3=82=92=E8=A8=82=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/Cryptgraphy/MultiWordInt.h | 18 ++++++++---------- include/Cryptgraphy/common.h | 1 + include/Packet.h | 16 +++++++++++----- 3 files changed, 20 insertions(+), 15 deletions(-) diff --git a/include/Cryptgraphy/MultiWordInt.h b/include/Cryptgraphy/MultiWordInt.h index d0aa246..c7b204b 100644 --- a/include/Cryptgraphy/MultiWordInt.h +++ b/include/Cryptgraphy/MultiWordInt.h @@ -473,12 +473,14 @@ struct bigint { (c - ('a' - 'A')) : (c); } + static constexpr std::string_view DigitsTable = "0123456789abcdefghijklmnopqrstuvwxyz"; + static constexpr auto DigitsTableUpper = DigitsTable | std::ranges::views::transform([](auto x) { return ToUpper(x); }); + static constexpr std::string WordToString(word_t v, int base) { - constexpr std::string_view list = "0123456789abcdefghijkmnlopqrstuvwxyz"; std::string ret; ret.reserve(WordCharSize); while (v != 0) { - ret.push_back(list[v % base]); + ret.push_back(DigitsTable[v % base]); v /= base; } std::reverse(ret.begin(), ret.end()); @@ -490,13 +492,11 @@ struct bigint { word_t ret = 0; auto getidx = [&](char c) -> size_t { - constexpr std::string_view listlower = "0123456789abcdefghijkmnlopqrstuvwxyz"; - constexpr std::string_view listupper = "0123456789ABCDEFGHIJKMNLOPQRSTUVWXYZ"; - size_t idx = listlower.find(c); + size_t idx = DigitsTable.find(c); if (idx != std::string_view::npos) { return idx; } - return listupper.find(c); + return DigitsTableUpper.find(c); }; for (; it != end; ++it) { @@ -520,7 +520,7 @@ struct bigint { assert((base >= 2 && base <= 36) && "Invalid base"); - auto proc = text.substr(0, text.find_first_not_of("0123456789abcdefghijkmnlopqrstuvwxyzABCDEFGHIJKMNLOPQRSTUVWXYZ")); + auto proc = text.substr(0, text.find_first_not_of("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")); auto it = proc.rbegin(); auto end = proc.rend(); count_t c = 0; @@ -586,7 +586,7 @@ struct bigint { return ret; } constexpr std::string ToBase64() const { - constexpr std::string_view list = "ABCDEFGHIJKNMLOPQRSTUVWXYZabcdefghijknmlopqrstuvwxyz0123456789+/"; + constexpr std::string_view list = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; std::string ret; ret.reserve(this->GetNBit() / std::log2(64) + 1); @@ -621,8 +621,6 @@ struct bigint { return ret; } constexpr std::string ToString(int base = 10, bool upper = true, bool padding = false) const { - constexpr std::string_view list = "0123456789abcdefghijkmnlopqrstuvwxyz"; - assert((base >= 2 && base <= 36) && "Invalid base"); word_t word_digits = static_cast(WordBits / std::log2(base)); diff --git a/include/Cryptgraphy/common.h b/include/Cryptgraphy/common.h index cf25f4c..56951f2 100644 --- a/include/Cryptgraphy/common.h +++ b/include/Cryptgraphy/common.h @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include diff --git a/include/Packet.h b/include/Packet.h index bcda956..f95b37a 100644 --- a/include/Packet.h +++ b/include/Packet.h @@ -128,6 +128,12 @@ struct Packet { Packet& operator=(const Packet&) = default; Packet& operator=(Packet&&) = default; + static Packet FromBytes(const bytearray& src) { + Packet ret; + ret.m_buffer = src; + return ret; + } + Packet(uint32_t id, const void* src, uint32_t size) { Header head(id); head.Size = size; @@ -157,21 +163,21 @@ struct Packet { template Packet(uint32_t id, const T& data) requires (memcpyable && !cross_convertible) : Packet(id, std::addressof(data), sizeof(T)) {} template - Packet(enumT type, const T& data) requires (is_enum32&& memcpyable && !cross_convertible) : Packet(static_cast(type), std::addressof(data), sizeof(T)) {} + Packet(enumT type, const T& data) requires (is_enum32 && memcpyable && !cross_convertible) : Packet(static_cast(type), std::addressof(data), sizeof(T)) {} template explicit Packet(const T& data) requires (memcpyable && !cross_convertible) : Packet(Header::type_hash_code(), std::addressof(data), sizeof(T)) {} template Packet(uint32_t id, const std::vector& data) requires (memcpyable && !cross_convertible) : Packet(id, data.data(), data.size() * sizeof(T)) {} template - Packet(enumT type, const std::vector& data) requires (is_enum32&& memcpyable && !cross_convertible) : Packet(static_cast(type), data.data(), data.size() * sizeof(T)) {} + Packet(enumT type, const std::vector& data) requires (is_enum32 && memcpyable && !cross_convertible) : Packet(static_cast(type), data.data(), data.size() * sizeof(T)) {} template explicit Packet(const std::vector& data) requires (memcpyable && !cross_convertible) : Packet(Header::type_hash_code>(), data.data(), data.size() * sizeof(T)) {} template Packet(uint32_t id, const T& data) requires (cross_convertible) : Packet(id, Convert(data)) {}; template - Packet(enumT type, const T& data) requires (is_enum32&& cross_convertible) : Packet(static_cast(type), data) {} + Packet(enumT type, const T& data) requires (is_enum32 && cross_convertible) : Packet(static_cast(type), data) {} template explicit Packet(const T& data) requires (cross_convertible) : Packet(Header::type_hash_code(), data) {} @@ -186,7 +192,7 @@ struct Packet { *this = Packet(id, b.data(), b.size()); } template - Packet(enumT type, const std::vector& data) requires (is_enum32&& cross_convertible) : Packet(static_cast(type), data) {} + Packet(enumT type, const std::vector& data) requires (is_enum32 && cross_convertible) : Packet(static_cast(type), data) {} template explicit Packet(const std::vector& data) requires (cross_convertible) : Packet(Header::type_hash_code>(), data) {} @@ -199,7 +205,7 @@ struct Packet { std::istreambuf_iterator begin(ifs); std::istreambuf_iterator end; - std::string data(begin, end); + bytearray data(begin, end); *this = Packet(id, data); }