code:
// Tencent is pleased to support the open source community by making RapidJSON available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
//
// Licensed under the MIT License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.

#include "rapidjson.h"

#ifndef RAPIDJSON_STREAM_H_
#define RAPIDJSON_STREAM_H_

#include "encodings.h"

RAPIDJSON_NAMESPACE_BEGIN

///////////////////////////////////////////////////////////////////////////////
//  Stream

/*! \class rapidjson::Stream
    \brief Concept for reading and writing characters.

    For read-only stream, no need to implement PutBegin(), Put(), Flush() and PutEnd().

    For write-only stream, only need to implement Put() and Flush().

\code
concept Stream {
    typename Ch;    //!< Character type of the stream.

    //! Read the current character from stream without moving the read cursor.
    Ch Peek() const;

    //! Read the current character from stream and moving the read cursor to next character.
    Ch Take();

    //! Get the current read cursor.
    //! \return Number of characters read from start.
    size_t Tell();

    //! Begin writing operation at the current read pointer.
    //! \return The begin writer pointer.
    Ch* PutBegin();

    //! Write a character.
    void Put(Ch c);

    //! Flush the buffer.
    void Flush();

    //! End the writing operation.
    //! \param begin The begin write pointer returned by PutBegin().
    //! \return Number of characters written.
    size_t PutEnd(Ch* begin);
}
\endcode
*/

//! Provides additional information for stream.
/*!
    By using traits pattern, this type provides a default configuration for stream.
    For custom stream, this type can be specialized for other configuration.
    See TEST(Reader, CustomStringStream) in readertest.cpp for example.
*/
template<typename Stream>
struct StreamTraits {
    //! Whether to make local copy of stream for optimization during parsing.
    /*!
        By default, for safety, streams do not use local copy optimization.
        Stream that can be copied fast should specialize this, like StreamTraits<StringStream>.
    */
    enum { copyOptimization = 0 };
};

//! Reserve n characters for writing to a stream.
template<typename Stream>
inline void PutReserve(Stream& stream, size_t count) {
    (void)stream;
    (void)count;
}

//! Write character to a stream, presuming buffer is reserved.
template<typename Stream>
inline void PutUnsafe(Stream& stream, typename Stream::Ch c) {
    stream.Put(c);
}

//! Put N copies of a character to a stream.
template<typename Stream, typename Ch>
inline void PutN(Stream& stream, Ch c, size_t n) {
    PutReserve(stream, n);
    for (size_t i = 0; i < n; i++)
        PutUnsafe(stream, c);
}

///////////////////////////////////////////////////////////////////////////////
// GenericStreamWrapper

//! A Stream Wrapper
/*! \tThis string stream is a wrapper for any stream by just forwarding any
    \treceived message to the origin stream.
    \note implements Stream concept
*/

#if defined(_MSC_VER) && _MSC_VER <= 1800
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(4702)  // unreachable code
RAPIDJSON_DIAG_OFF(4512)  // assignment operator could not be generated
#endif

template <typename InputStream, typename Encoding = UTF8<> >
class GenericStreamWrapper {
public:
    typedef typename Encoding::Ch Ch;
    GenericStreamWrapper(InputStream& is): is_(is) {}

    Ch Peek() const { return is_.Peek(); }
    Ch Take() { return is_.Take(); }
    size_t Tell() { return is_.Tell(); }
    Ch* PutBegin() { return is_.PutBegin(); }
    void Put(Ch ch) { is_.Put(ch); }
    void Flush() { is_.Flush(); }
    size_t PutEnd(Ch* ch) { return is_.PutEnd(ch); }

    // wrapper for MemoryStream
    const Ch* Peek4() const { return is_.Peek4(); }

    // wrapper for AutoUTFInputStream
    UTFType GetType() const { return is_.GetType(); }
    bool HasBOM() const { return is_.HasBOM(); }

protected:
    InputStream& is_;
};

#if defined(_MSC_VER) && _MSC_VER <= 1800
RAPIDJSON_DIAG_POP
#endif

///////////////////////////////////////////////////////////////////////////////
// StringStream

//! Read-only string stream.
/*! \note implements Stream concept
*/
template <typename Encoding>
struct GenericStringStream {
    typedef typename Encoding::Ch Ch;

    GenericStringStream(const Ch *src) : src_(src), head_(src) {}

    Ch Peek() const { return *src_; }
    Ch Take() { return *src_++; }
    size_t Tell() const { return static_cast<size_t>(src_ - head_); }

    Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
    void Put(Ch) { RAPIDJSON_ASSERT(false); }
    void Flush() { RAPIDJSON_ASSERT(false); }
    size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }

    const Ch* src_;     //!< Current read position.
    const Ch* head_;    //!< Original head of the string.
};

template <typename Encoding>
struct StreamTraits<GenericStringStream<Encoding> > {
    enum { copyOptimization = 1 };
};

//! String stream with UTF8 encoding.
typedef GenericStringStream<UTF8<> > StringStream;

///////////////////////////////////////////////////////////////////////////////
// InsituStringStream

//! A read-write string stream.
/*! This string stream is particularly designed for in-situ parsing.
    \note implements Stream concept
*/
template <typename Encoding>
struct GenericInsituStringStream {
    typedef typename Encoding::Ch Ch;

    GenericInsituStringStream(Ch *src) : src_(src), dst_(0), head_(src) {}

    // Read
    Ch Peek() { return *src_; }
    Ch Take() { return *src_++; }
    size_t Tell() { return static_cast<size_t>(src_ - head_); }

    // Write
    void Put(Ch c) { RAPIDJSON_ASSERT(dst_ != 0); *dst_++ = c; }

    Ch* PutBegin() { return dst_ = src_; }
    size_t PutEnd(Ch* begin) { return static_cast<size_t>(dst_ - begin); }
    void Flush() {}

    Ch* Push(size_t count) { Ch* begin = dst_; dst_ += count; return begin; }
    void Pop(size_t count) { dst_ -= count; }

    Ch* src_;
    Ch* dst_;
    Ch* head_;
};

template <typename Encoding>
struct StreamTraits<GenericInsituStringStream<Encoding> > {
    enum { copyOptimization = 1 };
};

//! Insitu string stream with UTF8 encoding.
typedef GenericInsituStringStream<UTF8<> > InsituStringStream;

RAPIDJSON_NAMESPACE_END

#endif // RAPIDJSON_STREAM_H_


code:
// Tencent is pleased to support the open source community by making RapidJSON available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
//
// Licensed under the MIT License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.

#ifndef RAPIDJSON_STRINGBUFFER_H_
#define RAPIDJSON_STRINGBUFFER_H_

#include "stream.h"
#include "internal/stack.h"

#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
#include <utility> // std::move
#endif

#include "internal/stack.h"

#if defined(__clang__)
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(c++98-compat)
#endif

RAPIDJSON_NAMESPACE_BEGIN

//! Represents an in-memory output stream.
/*!
    \tparam Encoding Encoding of the stream.
    \tparam Allocator type for allocating memory buffer.
    \note implements Stream concept
*/
template <typename Encoding, typename Allocator = CrtAllocator>
class GenericStringBuffer {
public:
    typedef typename Encoding::Ch Ch;

    GenericStringBuffer(Allocator* allocator = 0, size_t capacity = kDefaultCapacity) : stack_(allocator, capacity) {}

#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
    GenericStringBuffer(GenericStringBuffer&& rhs) : stack_(std::move(rhs.stack_)) {}
    GenericStringBuffer& operator=(GenericStringBuffer&& rhs) {
        if (&rhs != this)
            stack_ = std::move(rhs.stack_);
        return *this;
    }
#endif

    void Put(Ch c) { *stack_.template Push<Ch>() = c; }
    void PutUnsafe(Ch c) { *stack_.template PushUnsafe<Ch>() = c; }
    void Flush() {}

    void Clear() { stack_.Clear(); }
    void ShrinkToFit() {
        // Push and pop a null terminator. This is safe.
        *stack_.template Push<Ch>() = '\0';
        stack_.ShrinkToFit();
        stack_.template Pop<Ch>(1);
    }

    void Reserve(size_t count) { stack_.template Reserve<Ch>(count); }
    Ch* Push(size_t count) { return stack_.template Push<Ch>(count); }
    Ch* PushUnsafe(size_t count) { return stack_.template PushUnsafe<Ch>(count); }
    void Pop(size_t count) { stack_.template Pop<Ch>(count); }

    const Ch* GetString() const {
        // Push and pop a null terminator. This is safe.
        *stack_.template Push<Ch>() = '\0';
        stack_.template Pop<Ch>(1);

        return stack_.template Bottom<Ch>();
    }

    //! Get the size of string in bytes in the string buffer.
    size_t GetSize() const { return stack_.GetSize(); }

    //! Get the length of string in Ch in the string buffer.
    size_t GetLength() const { return stack_.GetSize() / sizeof(Ch); }

    static const size_t kDefaultCapacity = 256;
    mutable internal::Stack<Allocator> stack_;

private:
    // Prohibit copy constructor & assignment operator.
    GenericStringBuffer(const GenericStringBuffer&);
    GenericStringBuffer& operator=(const GenericStringBuffer&);
};

//! String buffer with UTF8 encoding
typedef GenericStringBuffer<UTF8<> > StringBuffer;

template<typename Encoding, typename Allocator>
inline void PutReserve(GenericStringBuffer<Encoding, Allocator>& stream, size_t count) {
    stream.Reserve(count);
}

template<typename Encoding, typename Allocator>
inline void PutUnsafe(GenericStringBuffer<Encoding, Allocator>& stream, typename Encoding::Ch c) {
    stream.PutUnsafe(c);
}

//! Implement specialized version of PutN() with memset() for better performance.
template<>
inline void PutN(GenericStringBuffer<UTF8<> >& stream, char c, size_t n) {
    std::memset(stream.stack_.Push<char>(n), c, n * sizeof(c));
}

RAPIDJSON_NAMESPACE_END

#if defined(__clang__)
RAPIDJSON_DIAG_POP
#endif

#endif // RAPIDJSON_STRINGBUFFER_H_

repo_name: xianyu/navicat

license: mit


code:
// Tencent is pleased to support the open source community by making RapidJSON available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
//
// Licensed under the MIT License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.

#ifndef RAPIDJSON_WRITER_H_
#define RAPIDJSON_WRITER_H_

#include "stream.h"
#include "internal/meta.h"
#include "internal/stack.h"
#include "internal/strfunc.h"
#include "internal/dtoa.h"
#include "internal/itoa.h"
#include "stringbuffer.h"
#include <new>      // placement new

#if defined(RAPIDJSON_SIMD) && defined(_MSC_VER)
#include <intrin.h>
#pragma intrinsic(_BitScanForward)
#endif
#ifdef RAPIDJSON_SSE42
#include <nmmintrin.h>
#elif defined(RAPIDJSON_SSE2)
#include <emmintrin.h>
#elif defined(RAPIDJSON_NEON)
#include <arm_neon.h>
#endif

#ifdef __clang__
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(padded)
RAPIDJSON_DIAG_OFF(unreachable-code)
RAPIDJSON_DIAG_OFF(c++98-compat)
#elif defined(_MSC_VER)
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant
#endif

RAPIDJSON_NAMESPACE_BEGIN

///////////////////////////////////////////////////////////////////////////////
// WriteFlag

/*! \def RAPIDJSON_WRITE_DEFAULT_FLAGS
    \ingroup RAPIDJSON_CONFIG
    \brief User-defined kWriteDefaultFlags definition.

    User can define this as any \c WriteFlag combinations.
*/
#ifndef RAPIDJSON_WRITE_DEFAULT_FLAGS
#define RAPIDJSON_WRITE_DEFAULT_FLAGS kWriteNoFlags
#endif

//! Combination of writeFlags
enum WriteFlag {
    kWriteNoFlags = 0,              //!< No flags are set.
    kWriteValidateEncodingFlag = 1, //!< Validate encoding of JSON strings.
    kWriteNanAndInfFlag = 2,        //!< Allow writing of Infinity, -Infinity and NaN.
    kWriteDefaultFlags = RAPIDJSON_WRITE_DEFAULT_FLAGS  //!< Default write flags. Can be customized by defining RAPIDJSON_WRITE_DEFAULT_FLAGS
};

//! JSON writer
/*! Writer implements the concept Handler.
    It generates JSON text by events to an output os.

    User may programmatically calls the functions of a writer to generate JSON text.

    On the other side, a writer can also be passed to objects that generates events,

    for example Reader::Parse() and Document::Accept().

    \tparam OutputStream Type of output stream.
    \tparam SourceEncoding Encoding of source string.
    \tparam TargetEncoding Encoding of output stream.
    \tparam StackAllocator Type of allocator for allocating memory of stack.
    \note implements Handler concept
*/
template<typename OutputStream, typename SourceEncoding = UTF8<>, typename TargetEncoding = UTF8<>, typename StackAllocator = CrtAllocator, unsigned writeFlags = kWriteDefaultFlags>
class Writer {
public:
    typedef typename SourceEncoding::Ch Ch;

    static const int kDefaultMaxDecimalPlaces = 324;

    //! Constructor
    /*! \param os Output stream.
        \param stackAllocator User supplied allocator. If it is null, it will create a private one.
        \param levelDepth Initial capacity of stack.
    */
    explicit
    Writer(OutputStream& os, StackAllocator* stackAllocator = 0, size_t levelDepth = kDefaultLevelDepth) :
        os_(&os), level_stack_(stackAllocator, levelDepth * sizeof(Level)), maxDecimalPlaces_(kDefaultMaxDecimalPlaces), hasRoot_(false) {}

    explicit
    Writer(StackAllocator* allocator = 0, size_t levelDepth = kDefaultLevelDepth) :
        os_(0), level_stack_(allocator, levelDepth * sizeof(Level)), maxDecimalPlaces_(kDefaultMaxDecimalPlaces), hasRoot_(false) {}

#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
    Writer(Writer&& rhs) :
        os_(rhs.os_), level_stack_(std::move(rhs.level_stack_)), maxDecimalPlaces_(rhs.maxDecimalPlaces_), hasRoot_(rhs.hasRoot_) {
        rhs.os_ = 0;
    }
#endif

    //! Reset the writer with a new stream.
    /*!
        This function reset the writer with a new stream and default settings,
        in order to make a Writer object reusable for output multiple JSONs.

        \param os New output stream.
        \code
        Writer<OutputStream> writer(os1);
        writer.StartObject();
        // ...
        writer.EndObject();

        writer.Reset(os2);
        writer.StartObject();
        // ...
        writer.EndObject();
        \endcode
    */
    void Reset(OutputStream& os) {
        os_ = &os;
        hasRoot_ = false;
        level_stack_.Clear();
    }

    //! Checks whether the output is a complete JSON.
    /*!
        A complete JSON has a complete root object or array.
    */
    bool IsComplete() const {
        return hasRoot_ && level_stack_.Empty();
    }

    int GetMaxDecimalPlaces() const {
        return maxDecimalPlaces_;
    }

    //! Sets the maximum number of decimal places for double output.
    /*!
        This setting truncates the output with specified number of decimal places.

        For example,

        \code
        writer.SetMaxDecimalPlaces(3);
        writer.StartArray();
        writer.Double(0.12345);                 // "0.123"
        writer.Double(0.0001);                  // "0.0"
        writer.Double(1.234567890123456e30);    // "1.234567890123456e30" (do not truncate significand for positive exponent)
        writer.Double(1.23e-4);                 // "0.0"                  (do truncate significand for negative exponent)
        writer.EndArray();
        \endcode

        The default setting does not truncate any decimal places. You can restore to this setting by calling
        \code
        writer.SetMaxDecimalPlaces(Writer::kDefaultMaxDecimalPlaces);
        \endcode
    */
    void SetMaxDecimalPlaces(int maxDecimalPlaces) {
        maxDecimalPlaces_ = maxDecimalPlaces;
    }

    /*!@name Implementation of Handler
        \see Handler
    */
    //@{

    bool Null()                 { Prefix(kNullType);   return EndValue(WriteNull()); }
    bool Bool(bool b)           { Prefix(b ? kTrueType : kFalseType); return EndValue(WriteBool(b)); }
    bool Int(int i)             { Prefix(kNumberType); return EndValue(WriteInt(i)); }
    bool Uint(unsigned u)       { Prefix(kNumberType); return EndValue(WriteUint(u)); }
    bool Int64(int64_t i64)     { Prefix(kNumberType); return EndValue(WriteInt64(i64)); }
    bool Uint64(uint64_t u64)   { Prefix(kNumberType); return EndValue(WriteUint64(u64)); }

    //! Writes the given \c double value to the stream
    /*!
        \param d The value to be written.
        \return Whether it is succeed.
    */
    bool Double(double d)       { Prefix(kNumberType); return EndValue(WriteDouble(d)); }

    bool RawNumber(const Ch* str, SizeType length, bool copy = false) {
        RAPIDJSON_ASSERT(str != 0);
        (void)copy;
        Prefix(kNumberType);
        return EndValue(WriteString(str, length));
    }

    bool String(const Ch* str, SizeType length, bool copy = false) {
        RAPIDJSON_ASSERT(str != 0);
        (void)copy;
        Prefix(kStringType);
        return EndValue(WriteString(str, length));
    }

#if RAPIDJSON_HAS_STDSTRING
    bool String(const std::basic_string<Ch>& str) {
        return String(str.data(), SizeType(str.size()));
    }
#endif

    bool StartObject() {
        Prefix(kObjectType);
        new (level_stack_.template Push<Level>()) Level(false);
        return WriteStartObject();
    }

    bool Key(const Ch* str, SizeType length, bool copy = false) { return String(str, length, copy); }

#if RAPIDJSON_HAS_STDSTRING
    bool Key(const std::basic_string<Ch>& str)
    {
      return Key(str.data(), SizeType(str.size()));
    }
#endif

    bool EndObject(SizeType memberCount = 0) {
        (void)memberCount;
        RAPIDJSON_ASSERT(level_stack_.GetSize() >= sizeof(Level)); // not inside an Object
        RAPIDJSON_ASSERT(!level_stack_.template Top<Level>()->inArray); // currently inside an Array, not Object
        RAPIDJSON_ASSERT(0 == level_stack_.template Top<Level>()->valueCount % 2); // Object has a Key without a Value
        level_stack_.template Pop<Level>(1);
        return EndValue(WriteEndObject());
    }

    bool StartArray() {
        Prefix(kArrayType);
        new (level_stack_.template Push<Level>()) Level(true);
        return WriteStartArray();
    }

    bool EndArray(SizeType elementCount = 0) {
        (void)elementCount;
        RAPIDJSON_ASSERT(level_stack_.GetSize() >= sizeof(Level));
        RAPIDJSON_ASSERT(level_stack_.template Top<Level>()->inArray);
        level_stack_.template Pop<Level>(1);
        return EndValue(WriteEndArray());
    }
    //@}

    /*! @name Convenience extensions */
    //@{

    //! Simpler but slower overload.
    bool String(const Ch* const& str) { return String(str, internal::StrLen(str)); }
    bool Key(const Ch* const& str) { return Key(str, internal::StrLen(str)); }

    //@}

    //! Write a raw JSON value.
    /*!
        For user to write a stringified JSON as a value.

        \param json A well-formed JSON value. It should not contain null character within [0, length - 1] range.
        \param length Length of the json.
        \param type Type of the root of json.
    */
    bool RawValue(const Ch* json, size_t length, Type type) {
        RAPIDJSON_ASSERT(json != 0);
        Prefix(type);
        return EndValue(WriteRawValue(json, length));
    }

    //! Flush the output stream.
    /*!
        Allows the user to flush the output stream immediately.
     */
    void Flush() {
        os_->Flush();
    }

protected:
    //! Information for each nested level
    struct Level {
        Level(bool inArray_) : valueCount(0), inArray(inArray_) {}
        size_t valueCount;  //!< number of values in this level
        bool inArray;       //!< true if in array, otherwise in object
    };

    static const size_t kDefaultLevelDepth = 32;

    bool WriteNull()  {
        PutReserve(*os_, 4);
        PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'u'); PutUnsafe(*os_, 'l'); PutUnsafe(*os_, 'l'); return true;
    }

    bool WriteBool(bool b)  {
        if (b) {
            PutReserve(*os_, 4);
            PutUnsafe(*os_, 't'); PutUnsafe(*os_, 'r'); PutUnsafe(*os_, 'u'); PutUnsafe(*os_, 'e');
        }
        else {
            PutReserve(*os_, 5);
            PutUnsafe(*os_, 'f'); PutUnsafe(*os_, 'a'); PutUnsafe(*os_, 'l'); PutUnsafe(*os_, 's'); PutUnsafe(*os_, 'e');
        }
        return true;
    }

    bool WriteInt(int i) {
        char buffer[11];
        const char* end = internal::i32toa(i, buffer);
        PutReserve(*os_, static_cast<size_t>(end - buffer));
        for (const char* p = buffer; p != end; ++p)
            PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(*p));
        return true;
    }

    bool WriteUint(unsigned u) {
        char buffer[10];
        const char* end = internal::u32toa(u, buffer);
        PutReserve(*os_, static_cast<size_t>(end - buffer));
        for (const char* p = buffer; p != end; ++p)
            PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(*p));
        return true;
    }

    bool WriteInt64(int64_t i64) {
        char buffer[21];
        const char* end = internal::i64toa(i64, buffer);
        PutReserve(*os_, static_cast<size_t>(end - buffer));
        for (const char* p = buffer; p != end; ++p)
            PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(*p));
        return true;
    }

    bool WriteUint64(uint64_t u64) {
        char buffer[20];
        char* end = internal::u64toa(u64, buffer);
        PutReserve(*os_, static_cast<size_t>(end - buffer));
        for (char* p = buffer; p != end; ++p)
            PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(*p));
        return true;
    }

    bool WriteDouble(double d) {
        if (internal::Double(d).IsNanOrInf()) {
            if (!(writeFlags & kWriteNanAndInfFlag))
                return false;
            if (internal::Double(d).IsNan()) {
                PutReserve(*os_, 3);
                PutUnsafe(*os_, 'N'); PutUnsafe(*os_, 'a'); PutUnsafe(*os_, 'N');
                return true;
            }
            if (internal::Double(d).Sign()) {
                PutReserve(*os_, 9);
                PutUnsafe(*os_, '-');
            }
            else
                PutReserve(*os_, 8);
            PutUnsafe(*os_, 'I'); PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'f');
            PutUnsafe(*os_, 'i'); PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'i'); PutUnsafe(*os_, 't'); PutUnsafe(*os_, 'y');
            return true;
        }

        char buffer[25];
        char* end = internal::dtoa(d, buffer, maxDecimalPlaces_);
        PutReserve(*os_, static_cast<size_t>(end - buffer));
        for (char* p = buffer; p != end; ++p)
            PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(*p));
        return true;
    }

    bool WriteString(const Ch* str, SizeType length)  {
        static const typename OutputStream::Ch hexDigits[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        static const char escape[256] = {
#define Z16 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
            //0    1    2    3    4    5    6    7    8    9    A    B    C    D    E    F
            'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'b', 't', 'n', 'u', 'f', 'r', 'u', 'u', // 00
            'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', // 10
              0,   0, '"',   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, // 20
            Z16, Z16,                                                                       // 30~4F
              0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,'\\',   0,   0,   0, // 50
            Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16                                // 60~FF
#undef Z16
        };

        if (TargetEncoding::supportUnicode)
            PutReserve(*os_, 2 + length * 6); // "\uxxxx..."
        else
            PutReserve(*os_, 2 + length * 12);  // "\uxxxx\uyyyy..."

        PutUnsafe(*os_, '\"');
        GenericStringStream<SourceEncoding> is(str);
        while (ScanWriteUnescapedString(is, length)) {
            const Ch c = is.Peek();
            if (!TargetEncoding::supportUnicode && static_cast<unsigned>(c) >= 0x80) {
                // Unicode escaping
                unsigned codepoint;
                if (RAPIDJSON_UNLIKELY(!SourceEncoding::Decode(is, &codepoint)))
                    return false;
                PutUnsafe(*os_, '\\');
                PutUnsafe(*os_, 'u');
                if (codepoint <= 0xD7FF || (codepoint >= 0xE000 && codepoint <= 0xFFFF)) {
                    PutUnsafe(*os_, hexDigits[(codepoint >> 12) & 15]);
                    PutUnsafe(*os_, hexDigits[(codepoint >>  8) & 15]);
                    PutUnsafe(*os_, hexDigits[(codepoint >>  4) & 15]);
                    PutUnsafe(*os_, hexDigits[(codepoint      ) & 15]);
                }
                else {
                    RAPIDJSON_ASSERT(codepoint >= 0x010000 && codepoint <= 0x10FFFF);
                    // Surrogate pair
                    unsigned s = codepoint - 0x010000;
                    unsigned lead = (s >> 10) + 0xD800;
                    unsigned trail = (s & 0x3FF) + 0xDC00;
                    PutUnsafe(*os_, hexDigits[(lead >> 12) & 15]);
                    PutUnsafe(*os_, hexDigits[(lead >>  8) & 15]);
                    PutUnsafe(*os_, hexDigits[(lead >>  4) & 15]);
                    PutUnsafe(*os_, hexDigits[(lead      ) & 15]);
                    PutUnsafe(*os_, '\\');
                    PutUnsafe(*os_, 'u');
                    PutUnsafe(*os_, hexDigits[(trail >> 12) & 15]);
                    PutUnsafe(*os_, hexDigits[(trail >>  8) & 15]);
                    PutUnsafe(*os_, hexDigits[(trail >>  4) & 15]);
                    PutUnsafe(*os_, hexDigits[(trail      ) & 15]);
                }
            }
            else if ((sizeof(Ch) == 1 || static_cast<unsigned>(c) < 256) && RAPIDJSON_UNLIKELY(escape[static_cast<unsigned char>(c)]))  {
                is.Take();
                PutUnsafe(*os_, '\\');
                PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(escape[static_cast<unsigned char>(c)]));
                if (escape[static_cast<unsigned char>(c)] == 'u') {
                    PutUnsafe(*os_, '0');
                    PutUnsafe(*os_, '0');
                    PutUnsafe(*os_, hexDigits[static_cast<unsigned char>(c) >> 4]);
                    PutUnsafe(*os_, hexDigits[static_cast<unsigned char>(c) & 0xF]);
                }
            }
            else if (RAPIDJSON_UNLIKELY(!(writeFlags & kWriteValidateEncodingFlag ?
                Transcoder<SourceEncoding, TargetEncoding>::Validate(is, *os_) :
                Transcoder<SourceEncoding, TargetEncoding>::TranscodeUnsafe(is, *os_))))
                return false;
        }
        PutUnsafe(*os_, '\"');
        return true;
    }

    bool ScanWriteUnescapedString(GenericStringStream<SourceEncoding>& is, size_t length) {
        return RAPIDJSON_LIKELY(is.Tell() < length);
    }

    bool WriteStartObject() { os_->Put('{'); return true; }
    bool WriteEndObject()   { os_->Put('}'); return true; }
    bool WriteStartArray()  { os_->Put('['); return true; }
    bool WriteEndArray()    { os_->Put(']'); return true; }

    bool WriteRawValue(const Ch* json, size_t length) {
        PutReserve(*os_, length);
        GenericStringStream<SourceEncoding> is(json);
        while (RAPIDJSON_LIKELY(is.Tell() < length)) {
            RAPIDJSON_ASSERT(is.Peek() != '\0');
            if (RAPIDJSON_UNLIKELY(!(writeFlags & kWriteValidateEncodingFlag ?
                Transcoder<SourceEncoding, TargetEncoding>::Validate(is, *os_) :
                Transcoder<SourceEncoding, TargetEncoding>::TranscodeUnsafe(is, *os_))))
                return false;
        }
        return true;
    }

    void Prefix(Type type) {
        (void)type;
        if (RAPIDJSON_LIKELY(level_stack_.GetSize() != 0)) { // this value is not at root
            Level* level = level_stack_.template Top<Level>();
            if (level->valueCount > 0) {
                if (level->inArray)
                    os_->Put(','); // add comma if it is not the first element in array
                else  // in object
                    os_->Put((level->valueCount % 2 == 0) ? ',' : ':');
            }
            if (!level->inArray && level->valueCount % 2 == 0)
                RAPIDJSON_ASSERT(type == kStringType);  // if it's in object, then even number should be a name
            level->valueCount++;
        }
        else {
            RAPIDJSON_ASSERT(!hasRoot_);    // Should only has one and only one root.
            hasRoot_ = true;
        }
    }

    // Flush the value if it is the top level one.
    bool EndValue(bool ret) {
        if (RAPIDJSON_UNLIKELY(level_stack_.Empty()))   // end of json text
            Flush();
        return ret;
    }

    OutputStream* os_;
    internal::Stack<StackAllocator> level_stack_;
    int maxDecimalPlaces_;
    bool hasRoot_;

private:
    // Prohibit copy constructor & assignment operator.
    Writer(const Writer&);
    Writer& operator=(const Writer&);
};

// Full specialization for StringStream to prevent memory copying

template<>
inline bool Writer<StringBuffer>::WriteInt(int i) {
    char *buffer = os_->Push(11);
    const char* end = internal::i32toa(i, buffer);
    os_->Pop(static_cast<size_t>(11 - (end - buffer)));
    return true;
}

template<>
inline bool Writer<StringBuffer>::WriteUint(unsigned u) {
    char *buffer = os_->Push(10);
    const char* end = internal::u32toa(u, buffer);
    os_->Pop(static_cast<size_t>(10 - (end - buffer)));
    return true;
}

template<>
inline bool Writer<StringBuffer>::WriteInt64(int64_t i64) {
    char *buffer = os_->Push(21);
    const char* end = internal::i64toa(i64, buffer);
    os_->Pop(static_cast<size_t>(21 - (end - buffer)));
    return true;
}

template<>
inline bool Writer<StringBuffer>::WriteUint64(uint64_t u) {
    char *buffer = os_->Push(20);
    const char* end = internal::u64toa(u, buffer);
    os_->Pop(static_cast<size_t>(20 - (end - buffer)));
    return true;
}

template<>
inline bool Writer<StringBuffer>::WriteDouble(double d) {
    if (internal::Double(d).IsNanOrInf()) {
        // Note: This code path can only be reached if (RAPIDJSON_WRITE_DEFAULT_FLAGS & kWriteNanAndInfFlag).
        if (!(kWriteDefaultFlags & kWriteNanAndInfFlag))
            return false;
        if (internal::Double(d).IsNan()) {
            PutReserve(*os_, 3);
            PutUnsafe(*os_, 'N'); PutUnsafe(*os_, 'a'); PutUnsafe(*os_, 'N');
            return true;
        }
        if (internal::Double(d).Sign()) {
            PutReserve(*os_, 9);
            PutUnsafe(*os_, '-');
        }
        else
            PutReserve(*os_, 8);
        PutUnsafe(*os_, 'I'); PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'f');
        PutUnsafe(*os_, 'i'); PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'i'); PutUnsafe(*os_, 't'); PutUnsafe(*os_, 'y');
        return true;
    }

    char *buffer = os_->Push(25);
    char* end = internal::dtoa(d, buffer, maxDecimalPlaces_);
    os_->Pop(static_cast<size_t>(25 - (end - buffer)));
    return true;
}

#if defined(RAPIDJSON_SSE2) || defined(RAPIDJSON_SSE42)
template<>
inline bool Writer<StringBuffer>::ScanWriteUnescapedString(StringStream& is, size_t length) {
    if (length < 16)
        return RAPIDJSON_LIKELY(is.Tell() < length);

    if (!RAPIDJSON_LIKELY(is.Tell() < length))
        return false;

    const char* p = is.src_;
    const char* end = is.head_ + length;
    const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15));
    const char* endAligned = reinterpret_cast<const char*>(reinterpret_cast<size_t>(end) & static_cast<size_t>(~15));
    if (nextAligned > end)
        return true;

    while (p != nextAligned)
        if (*p < 0x20 || *p == '\"' || *p == '\\') {
            is.src_ = p;
            return RAPIDJSON_LIKELY(is.Tell() < length);
        }
        else
            os_->PutUnsafe(*p++);

    // The rest of string using SIMD
    static const char dquote[16] = { '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"' };
    static const char bslash[16] = { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' };
    static const char space[16]  = { 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F };
    const __m128i dq = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&dquote[0]));
    const __m128i bs = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&bslash[0]));
    const __m128i sp = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&space[0]));

    for (; p != endAligned; p += 16) {
        const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(p));
        const __m128i t1 = _mm_cmpeq_epi8(s, dq);
        const __m128i t2 = _mm_cmpeq_epi8(s, bs);
        const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x1F) == 0x1F
        const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3);
        unsigned short r = static_cast<unsigned short>(_mm_movemask_epi8(x));
        if (RAPIDJSON_UNLIKELY(r != 0)) {   // some of characters is escaped
            SizeType len;
#ifdef _MSC_VER         // Find the index of first escaped
            unsigned long offset;
            _BitScanForward(&offset, r);
            len = offset;
#else
            len = static_cast<SizeType>(__builtin_ffs(r) - 1);
#endif
            char* q = reinterpret_cast<char*>(os_->PushUnsafe(len));
            for (size_t i = 0; i < len; i++)
                q[i] = p[i];

            p += len;
            break;
        }
        _mm_storeu_si128(reinterpret_cast<__m128i *>(os_->PushUnsafe(16)), s);
    }

    is.src_ = p;
    return RAPIDJSON_LIKELY(is.Tell() < length);
}
#elif defined(RAPIDJSON_NEON)
template<>
inline bool Writer<StringBuffer>::ScanWriteUnescapedString(StringStream& is, size_t length) {
    if (length < 16)
        return RAPIDJSON_LIKELY(is.Tell() < length);

    if (!RAPIDJSON_LIKELY(is.Tell() < length))
        return false;

    const char* p = is.src_;
    const char* end = is.head_ + length;
    const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15));
    const char* endAligned = reinterpret_cast<const char*>(reinterpret_cast<size_t>(end) & static_cast<size_t>(~15));
    if (nextAligned > end)
        return true;

    while (p != nextAligned)
        if (*p < 0x20 || *p == '\"' || *p == '\\') {
            is.src_ = p;
            return RAPIDJSON_LIKELY(is.Tell() < length);
        }
        else
            os_->PutUnsafe(*p++);

    // The rest of string using SIMD
    const uint8x16_t s0 = vmovq_n_u8('"');
    const uint8x16_t s1 = vmovq_n_u8('\\');
    const uint8x16_t s2 = vmovq_n_u8('\b');
    const uint8x16_t s3 = vmovq_n_u8(32);

    for (; p != endAligned; p += 16) {
        const uint8x16_t s = vld1q_u8(reinterpret_cast<const uint8_t *>(p));
        uint8x16_t x = vceqq_u8(s, s0);
        x = vorrq_u8(x, vceqq_u8(s, s1));
        x = vorrq_u8(x, vceqq_u8(s, s2));
        x = vorrq_u8(x, vcltq_u8(s, s3));

        x = vrev64q_u8(x);                     // Rev in 64
        uint64_t low = vgetq_lane_u64(reinterpret_cast<uint64x2_t>(x), 0);   // extract
        uint64_t high = vgetq_lane_u64(reinterpret_cast<uint64x2_t>(x), 1);  // extract

        SizeType len = 0;
        bool escaped = false;
        if (low == 0) {
            if (high != 0) {
                unsigned lz = (unsigned)__builtin_clzll(high);
                len = 8 + (lz >> 3);
                escaped = true;
            }
        } else {
            unsigned lz = (unsigned)__builtin_clzll(low);
            len = lz >> 3;
            escaped = true;
        }
        if (RAPIDJSON_UNLIKELY(escaped)) {   // some of characters is escaped
            char* q = reinterpret_cast<char*>(os_->PushUnsafe(len));
            for (size_t i = 0; i < len; i++)
                q[i] = p[i];

            p += len;
            break;
        }
        vst1q_u8(reinterpret_cast<uint8_t *>(os_->PushUnsafe(16)), s);
    }

    is.src_ = p;
    return RAPIDJSON_LIKELY(is.Tell() < length);
}
#endif // RAPIDJSON_NEON

RAPIDJSON_NAMESPACE_END

#if defined(_MSC_VER) || defined(__clang__)
RAPIDJSON_DIAG_POP
#endif

#endif // RAPIDJSON_RAPIDJSON_H_


code:
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.28307.421
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "navicat-keygen", "navicat-keygen\navicat-keygen.vcxproj", "{CB49F054-83AB-4C16-B73B-33D7DF696E16}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "navicat-patcher", "navicat-patcher\navicat-patcher.vcxproj", "{30BE8CAB-6137-4441-9F64-599D0A6EEA0C}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "common", "common\common.vcxitems", "{6AA392E2-B540-4AB5-9BFD-40AD964B209A}"
EndProject
Global
	GlobalSection(SharedMSBuildProjectFiles) = preSolution
		common\common.vcxitems*{30be8cab-6137-4441-9f64-599d0a6eea0c}*SharedItemsImports = 4
		common\common.vcxitems*{6aa392e2-b540-4ab5-9bfd-40ad964b209a}*SharedItemsImports = 9
		common\common.vcxitems*{cb49f054-83ab-4c16-b73b-33d7df696e16}*SharedItemsImports = 4
	EndGlobalSection
	GlobalSection(SolutionConfigurationPlatforms) = preSolution
		Debug|x64 = Debug|x64
		Debug|x86 = Debug|x86
		Release|x64 = Release|x64
		Release|x86 = Release|x86
	EndGlobalSection
	GlobalSection(ProjectConfigurationPlatforms) = postSolution
		{CB49F054-83AB-4C16-B73B-33D7DF696E16}.Debug|x64.ActiveCfg = Debug|x64
		{CB49F054-83AB-4C16-B73B-33D7DF696E16}.Debug|x64.Build.0 = Debug|x64
		{CB49F054-83AB-4C16-B73B-33D7DF696E16}.Debug|x86.ActiveCfg = Debug|Win32
		{CB49F054-83AB-4C16-B73B-33D7DF696E16}.Debug|x86.Build.0 = Debug|Win32
		{CB49F054-83AB-4C16-B73B-33D7DF696E16}.Release|x64.ActiveCfg = Release|x64
		{CB49F054-83AB-4C16-B73B-33D7DF696E16}.Release|x64.Build.0 = Release|x64
		{CB49F054-83AB-4C16-B73B-33D7DF696E16}.Release|x86.ActiveCfg = Release|Win32
		{CB49F054-83AB-4C16-B73B-33D7DF696E16}.Release|x86.Build.0 = Release|Win32
		{30BE8CAB-6137-4441-9F64-599D0A6EEA0C}.Debug|x64.ActiveCfg = Debug|x64
		{30BE8CAB-6137-4441-9F64-599D0A6EEA0C}.Debug|x64.Build.0 = Debug|x64
		{30BE8CAB-6137-4441-9F64-599D0A6EEA0C}.Debug|x86.ActiveCfg = Debug|Win32
		{30BE8CAB-6137-4441-9F64-599D0A6EEA0C}.Debug|x86.Build.0 = Debug|Win32
		{30BE8CAB-6137-4441-9F64-599D0A6EEA0C}.Release|x64.ActiveCfg = Release|x64
		{30BE8CAB-6137-4441-9F64-599D0A6EEA0C}.Release|x64.Build.0 = Release|x64
		{30BE8CAB-6137-4441-9F64-599D0A6EEA0C}.Release|x86.ActiveCfg = Release|Win32
		{30BE8CAB-6137-4441-9F64-599D0A6EEA0C}.Release|x86.Build.0 = Release|Win32
	EndGlobalSection
	GlobalSection(SolutionProperties) = preSolution
		HideSolutionNode = FALSE
	EndGlobalSection
	GlobalSection(ExtensibilityGlobals) = postSolution
		SolutionGuid = {8C8CB6CD-8F5F-4847-9EF4-095745EEFBDB}
	EndGlobalSection
EndGlobal


code:
#include "Helper.hpp"
#include "ExceptionSystem.hpp"
#include <iostream>

#undef __BASE_FILE__
#define __BASE_FILE__ TEXT("Helper.cpp")

namespace Helper {

    TString Base64Encode(const std::vector<uint8_t>& bytes) {
        TString RetValue;
        DWORD pcchString = 0;

        if (bytes.empty())
            return RetValue;

        if (!CryptBinaryToString(bytes.data(),
                                 static_cast<DWORD>(bytes.size()),
                                 CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF,
                                 NULL,
                                 &pcchString))
            throw SystemException(__BASE_FILE__, __LINE__, GetLastError(),
                                  TEXT("CryptBinaryToString failed."));

        RetValue.resize(pcchString);

        if (!CryptBinaryToString(bytes.data(),
                                 static_cast<DWORD>(bytes.size()),
                                 CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF,
                                 RetValue.data(),
                                 &pcchString))
            throw SystemException(__BASE_FILE__, __LINE__, GetLastError(),
                                  TEXT("CryptBinaryToString failed."));

        while (RetValue.back() == TEXT('\x00'))
            RetValue.pop_back();

        return RetValue;
    }

    std::vector<uint8_t> Base64Decode(const TString& Base64Str) {
        std::vector<uint8_t> RetValue;
        DWORD pcbBinary = 0;

        if (Base64Str.empty())
            return RetValue;

        if (!CryptStringToBinary(Base64Str.c_str(),
                                 NULL,
                                 CRYPT_STRING_BASE64,
                                 NULL,
                                 &pcbBinary,
                                 NULL,
                                 NULL))
            throw SystemException(__BASE_FILE__, __LINE__, GetLastError(),
                                  TEXT("CryptStringToBinary failed."),
                                  TEXT("Are you sure it is a Base64 string?"));

        RetValue.resize(pcbBinary);

        if (!CryptStringToBinary(Base64Str.c_str(),
                                 NULL,
                                 CRYPT_STRING_BASE64,
                                 RetValue.data(),
                                 &pcbBinary,
                                 NULL,
                                 NULL))
            throw SystemException(__BASE_FILE__, __LINE__, GetLastError(),
                                  TEXT("CryptStringToBinary failed."));

        return RetValue;
    }

    bool ReadInt(int& RefInt, int MinVal, int MaxVal, PCTSTR Prompt, PCTSTR ErrMsg) {
        int t;
        TString s;
        while (true) {
            _tprintf_s(TEXT("%s"), Prompt);
            if (!std::getline(std::_tcin, s))
                return false;

            if (s.empty())
                continue;

            try {
                t = std::stoi(s, nullptr, 0);
                if (MinVal <= t && t <= MaxVal) {
                    RefInt = t;
                    return true;
                } else {
                    throw std::invalid_argument("");
                }
            } catch (...) {
                _putts(ErrMsg);
            }
        }
    }
}


code:
#pragma once
#include "TString.hpp"
#include <vector>
#include <iostream>

#ifdef _UNICODE
#define _tcin wcin
#define _tcout wcout
#define _tcerr wcerr
#else
#define _tcin cin
#define _tcout cout
#define _tcerr cerr
#endif

namespace Helper {

    TString Base64Encode(const std::vector<uint8_t>& Bytes);

    std::vector<uint8_t> Base64Decode(const TString& Base64Str);

    bool ReadInt(int& RefInt, int MinVal, int MaxVal, PCTSTR Prompt, PCTSTR ErrMsg);

}


code:
#include <ctime>
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
#include "ExceptionSystem.hpp"
#include "NavicatKeygen.hpp"
#include "RSACipher.hpp"
#include "Helper.hpp"

struct FileHandleTraits {
    using HandleType = HANDLE;
    static inline const HandleType InvalidValue = INVALID_HANDLE_VALUE;
    static constexpr auto& Releasor = CloseHandle;
};

void AdvanceMode(RSACipher* pCipher, bool bGenerateText) {
    int n;
    int n1, n2;
    NavicatKeygen keygen;
    TString username;
    TString organization;
    std::string utf8username;
    std::string utf8organization;

    char ResponseInfo[256] = {};
    std::vector<uint8_t> ResponseCode;

    rapidjson::Document json;
    rapidjson::Value N_Key;
    rapidjson::Value N_Value;
    rapidjson::Value O_Key;
    rapidjson::Value O_Value;
    rapidjson::Value T_Key;
    rapidjson::Value T_Value;
    rapidjson::StringBuffer buffer;
    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);

    _putts(TEXT("[*] Navicat Product Signature:"));
    if (!Helper::ReadInt(n, 0, 255,
                         TEXT("(range: 0x00 ~ 0xFF)> "),
                         TEXT("Invalid number."))) {
        return;
    } else {
        keygen.SetProductSignature(n);
    }

    if ((_putts(TEXT("\n"
                     "[*] Navicat Language Signature 0:")),
         Helper::ReadInt(n1, 0, 255,
                         TEXT("(range: 0x00 ~ 0xFF)> "),
                         TEXT("Invalid number."))) &&
        (_putts(TEXT("\n"
                     "[*] Navicat Language Signature 1:")),
         Helper::ReadInt(n2, 0, 255,
                         TEXT("(range: 0x00 ~ 0xFF)> "),
                         TEXT("Invalid number.")))) {
        keygen.SetLanguageSignature(n1, n2);
    } else {
        return;
    }

    _putts(TEXT("\n"
                "[*] Input major version number:"));
    if (!Helper::ReadInt(n, 0, 16 - 1,
                         TEXT("(range: 0 ~ 15, default: 12)> "),
                         TEXT("Invalid number."))) {
        return;
    } else {
        keygen.SetVersion(n);
    }

    keygen.Generate();
    _tprintf_s(TEXT("\n"
                    "[*] Serial number:\n"
                    "%s\n"
                    "\n"),
               keygen.GetSerialNumber().c_str());

    _tprintf_s(TEXT("[*] Your name: "));
    if (!std::getline(std::_tcin, username))
        return;
    _tprintf_s(TEXT("[*] Your organization: "));
    if (!std::getline(std::_tcin, organization))
        return;

    utf8username = TStringEncode(username, CP_UTF8);
    utf8organization = TStringEncode(organization, CP_UTF8);

    if (bGenerateText) {
        TString b64RequestCode;
        std::vector<uint8_t> RequestCode;
        char RequestInfo[256] = {};
        TString b64ResponseCode;

        _putts(TEXT("[*] Input request code in Base64: (Input empty line to end)"));
        while (true) {
            TString temp;
            if (!std::getline(std::_tcin, temp))
                return;

            if (temp.empty())
                break;

            b64RequestCode += temp;
        }

        RequestCode = Helper::Base64Decode(b64RequestCode);
        pCipher->Decrypt(RequestCode.data(), RequestCode.size(), RequestInfo, RSA_PKCS1_PADDING);

        printf_s("[*]Request Info:\n"
                 "%s\n"
                 "\n",
                 RequestInfo);

        json.Parse(RequestInfo);

        //
        // Remove "Platform" info
        //
        json.RemoveMember("P");
        //
        // Set "Name" info
        //
        N_Key.SetString("N", 1);
        N_Value.SetString(utf8username.c_str(), utf8username.length());
        //
        // Set "Organization" info
        //
        O_Key.SetString("O", 1);
        O_Value.SetString(utf8organization.c_str(), utf8organization.length());
        //
        // Set "Time" info
        //
        T_Key.SetString("T", 1);
        T_Value.SetUint(std::time(nullptr));
        //
        // Add "Name", "Organization" and "Time"
        //
        json.AddMember(N_Key, N_Value, json.GetAllocator());
        json.AddMember(O_Key, O_Value, json.GetAllocator());
        json.AddMember(T_Key, T_Value, json.GetAllocator());

        json.Accept(writer);
        if (buffer.GetSize() > 240)
            throw Exception(__BASE_FILE__, __LINE__,
                            TEXT("Response info is too long."));

        memcpy(ResponseInfo, buffer.GetString(), buffer.GetSize());

        _tprintf_s(TEXT("[*] Response Info:\n"
                        "%s\n"
                        "\n"),
                   TStringBuilder(ResponseInfo, CP_UTF8).c_str());

        ResponseCode.resize(256);
        pCipher->Encrypt<RSAKeyType::PrivateKey>(ResponseInfo,
                                                 strlen(ResponseInfo),
                                                 ResponseCode.data(),
                                                 RSA_PKCS1_PADDING);
        b64ResponseCode = Helper::Base64Encode(ResponseCode);

        _tprintf_s(TEXT("[*] Activation Code:\n"
                        "%s\n"
                        "\n"),
                   b64ResponseCode.c_str());
    } else {    // Generate license_file
        ResourceObject<FileHandleTraits> hLicenseFile;
        rapidjson::Value K_Key;
        rapidjson::Value K_Value;
        std::string utf8SerialNumber = TStringEncode(keygen.GetSerialNumber(true), CP_UTF8);
        DWORD NumberOfBytesWritten;

        json.Parse("{}");

        K_Key.SetString("K", 1);
        K_Value.SetString(utf8SerialNumber.c_str(), utf8SerialNumber.length());
        N_Key.SetString("N", 1);
        N_Value.SetString(utf8username.c_str(), utf8username.length());
        O_Key.SetString("O", 1);
        O_Value.SetString(utf8organization.c_str(), utf8organization.length());
        T_Key.SetString("T", 1);
        T_Value.SetUint(std::time(nullptr));

        json.AddMember(K_Key, K_Value, json.GetAllocator());
        json.AddMember(N_Key, N_Value, json.GetAllocator());
        json.AddMember(O_Key, O_Value, json.GetAllocator());
        json.AddMember(T_Key, T_Value, json.GetAllocator());

        json.Accept(writer);
        if (buffer.GetSize() > 240)
            throw Exception(__BASE_FILE__, __LINE__,
                            TEXT("Response info is too long."));

        memcpy(ResponseInfo, buffer.GetString(), buffer.GetSize());

        _tprintf_s(TEXT("\n"
                        "[*] Response Info:\n"
                        "%s\n"
                        "\n"),
                   TStringBuilder(ResponseInfo, CP_UTF8).c_str());

        ResponseCode.resize(256);
        pCipher->Encrypt<RSAKeyType::PrivateKey>(ResponseInfo,
                                                 strlen(ResponseInfo),
                                                 ResponseCode.data(),
                                                 RSA_PKCS1_PADDING);

        hLicenseFile.TakeOver(CreateFile(TEXT("license_file"),
                                         GENERIC_READ | GENERIC_WRITE,
                                         NULL,
                                         NULL,
                                         CREATE_ALWAYS,
                                         FILE_ATTRIBUTE_NORMAL,
                                         NULL));
        if (hLicenseFile.IsValid() == false)
            throw SystemException(__BASE_FILE__, __LINE__, GetLastError(),
                                  TEXT("CreateFile failed."));

        if (!WriteFile(hLicenseFile, ResponseCode.data(), ResponseCode.size(), &NumberOfBytesWritten, NULL))
            throw SystemException(__BASE_FILE__, __LINE__, GetLastError(),
                                  TEXT("WriteFile failed."));

        _putts(TEXT("[*] license_file has been generated."));
    }
}


code:
#include <ctime>
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
#include "ExceptionSystem.hpp"
#include "NavicatKeygen.hpp"
#include "RSACipher.hpp"
#include "Helper.hpp"

struct FileHandleTraits {
    using HandleType = HANDLE;
    static inline const HandleType InvalidValue = INVALID_HANDLE_VALUE;
    static constexpr auto& Releasor = CloseHandle;
};

void NormalMode(RSACipher* pCipher, bool bGenerateText) {
    int n;
    NavicatKeygen keygen;
    TString username;
    TString organization;
    std::string utf8username;
    std::string utf8organization;

    char ResponseInfo[256] = {};
    std::vector<uint8_t> ResponseCode;

    rapidjson::Document json;
    rapidjson::Value N_Key;
    rapidjson::Value N_Value;
    rapidjson::Value O_Key;
    rapidjson::Value O_Value;
    rapidjson::Value T_Key;
    rapidjson::Value T_Value;
    rapidjson::StringBuffer buffer;
    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);

    _putts(TEXT("[*] Select Navicat product:"));
    _putts(TEXT(" 0. DataModeler"));
    _putts(TEXT(" 1. Premium"));
    _putts(TEXT(" 2. MySQL"));
    _putts(TEXT(" 3. PostgreSQL"));
    _putts(TEXT(" 4. Oracle"));
    _putts(TEXT(" 5. SQLServer"));
    _putts(TEXT(" 6. SQLite"));
    _putts(TEXT(" 7. MariaDB"));
    _putts(TEXT(" 8. MongoDB"));
    _putts(TEXT(" 9. ReportViewer"));
    _putts(TEXT(""));

    if (Helper::ReadInt(n, 0, 9, TEXT("(Input index)> "), TEXT("Invalid index.")) == false) {
        return;
    } else {
        keygen.SetProductSignature(static_cast<NavicatKeygen::Product>(n));
    }

    _putts(TEXT("\n"
                "[*] Select product language:"));
    _putts(TEXT(" 0. English"));
    _putts(TEXT(" 1. Simplified Chinese"));
    _putts(TEXT(" 2. Traditional Chinese"));
    _putts(TEXT(" 3. Japanese"));
    _putts(TEXT(" 4. Polish"));
    _putts(TEXT(" 5. Spanish"));
    _putts(TEXT(" 6. French"));
    _putts(TEXT(" 7. German"));
    _putts(TEXT(" 8. Korean"));
    _putts(TEXT(" 9. Russian"));
    _putts(TEXT(" 10. Portuguese"));
    _putts(TEXT(""));

    if (Helper::ReadInt(n, 0, 10, TEXT("(Input index)> "), TEXT("Invalid index.")) == false) {
        return;
    } else {
        keygen.SetLanguageSignature(static_cast<NavicatKeygen::Language>(n));
    }

    _putts(TEXT("\n"
                "[*] Input major version number:"));
    if (!Helper::ReadInt(n, 0, 16 - 1,
                         TEXT("(range: 0 ~ 15, default: 12)> "),
                         TEXT("Invalid number."))) {
        return;
    } else {
        keygen.SetVersion(n);
    }

    keygen.Generate();
    _tprintf_s(TEXT("\n"
                    "[*] Serial number:\n"
                    "%s\n"
                    "\n"),
               keygen.GetSerialNumber().c_str());

    _tprintf_s(TEXT("[*] Your name: "));
    if (!std::getline(std::_tcin, username))
        return;
    _tprintf_s(TEXT("[*] Your organization: "));
    if (!std::getline(std::_tcin, organization))
        return;

    utf8username = TStringEncode(username, CP_UTF8);
    utf8organization = TStringEncode(organization, CP_UTF8);

    if (bGenerateText) {
        TString b64RequestCode;
        std::vector<uint8_t> RequestCode;
        char RequestInfo[256] = {};
        TString b64ResponseCode;

        _putts(TEXT("[*] Input request code in Base64: (Input empty line to end)"));
        while (true) {
            TString temp;
            if (!std::getline(std::_tcin, temp))
                return;

            if (temp.empty())
                break;

            b64RequestCode += temp;
        }

        RequestCode = Helper::Base64Decode(b64RequestCode);
        pCipher->Decrypt(RequestCode.data(), RequestCode.size(), RequestInfo, RSA_PKCS1_PADDING);

        printf_s("[*] Request Info:\n"
                 "%s\n"
                 "\n",
                 RequestInfo);

        json.Parse(RequestInfo);

        //
        // Remove "Platform" info
        //
        json.RemoveMember("P");
        //
        // Set "Name" info
        //
        N_Key.SetString("N", 1);
        N_Value.SetString(utf8username.c_str(), utf8username.length());
        //
        // Set "Organization" info
        //
        O_Key.SetString("O", 1);
        O_Value.SetString(utf8organization.c_str(), utf8organization.length());
        //
        // Set "Time" info
        //
        T_Key.SetString("T", 1);
        T_Value.SetUint(std::time(nullptr));
        //
        // Add "Name", "Organization" and "Time"
        //
        json.AddMember(N_Key, N_Value, json.GetAllocator());
        json.AddMember(O_Key, O_Value, json.GetAllocator());
        json.AddMember(T_Key, T_Value, json.GetAllocator());

        json.Accept(writer);
        if (buffer.GetSize() > 240)
            throw Exception(__BASE_FILE__, __LINE__,
                            TEXT("Response info is too long."));

        memcpy(ResponseInfo, buffer.GetString(), buffer.GetSize());

        _tprintf_s(TEXT("[*] Response Info:\n"
                        "%s\n"
                        "\n"),
                   TStringBuilder(ResponseInfo, CP_UTF8).c_str());

        ResponseCode.resize(256);
        pCipher->Encrypt<RSAKeyType::PrivateKey>(ResponseInfo,
                                                 strlen(ResponseInfo),
                                                 ResponseCode.data(),
                                                 RSA_PKCS1_PADDING);
        b64ResponseCode = Helper::Base64Encode(ResponseCode);

        _tprintf_s(TEXT("[*] Activation Code:\n"
                        "%s\n"
                        "\n"),
                   b64ResponseCode.c_str());
    } else {    // Generate license_file
        ResourceObject<FileHandleTraits> hLicenseFile;
        rapidjson::Value K_Key;
        rapidjson::Value K_Value;
        std::string utf8SerialNumber = TStringEncode(keygen.GetSerialNumber(true), CP_UTF8);
        DWORD NumberOfBytesWritten;

        json.Parse("{}");

        K_Key.SetString("K", 1);
        K_Value.SetString(utf8SerialNumber.c_str(), utf8SerialNumber.length());
        N_Key.SetString("N", 1);
        N_Value.SetString(utf8username.c_str(), utf8username.length());
        O_Key.SetString("O", 1);
        O_Value.SetString(utf8organization.c_str(), utf8organization.length());
        T_Key.SetString("T", 1);
        T_Value.SetUint(std::time(nullptr));

        json.AddMember(K_Key, K_Value, json.GetAllocator());
        json.AddMember(N_Key, N_Value, json.GetAllocator());
        json.AddMember(O_Key, O_Value, json.GetAllocator());
        json.AddMember(T_Key, T_Value, json.GetAllocator());

        json.Accept(writer);
        if (buffer.GetSize() > 240)
            throw Exception(__BASE_FILE__, __LINE__,
                            TEXT("Response info is too long."));

        memcpy(ResponseInfo, buffer.GetString(), buffer.GetSize());

        _tprintf_s(TEXT("\n"
                        "[*] Response Info:\n"
                        "%s\n"
                        "\n"),
                   TStringBuilder(ResponseInfo, CP_UTF8).c_str());

        ResponseCode.resize(256);
        pCipher->Encrypt<RSAKeyType::PrivateKey>(ResponseInfo,
                                                 strlen(ResponseInfo),
                                                 ResponseCode.data(),
                                                 RSA_PKCS1_PADDING);

        hLicenseFile.TakeOver(CreateFile(TEXT("license_file"),
                                         GENERIC_READ | GENERIC_WRITE,
                                         NULL,
                                         NULL,
                                         CREATE_ALWAYS,
                                         FILE_ATTRIBUTE_NORMAL,
                                         NULL));
        if (hLicenseFile.IsValid() == false)
            throw SystemException(__BASE_FILE__, __LINE__, GetLastError(),
                                  TEXT("CreateFile failed."));

        if (!WriteFile(hLicenseFile, ResponseCode.data(), ResponseCode.size(), &NumberOfBytesWritten, NULL))
            throw SystemException(__BASE_FILE__, __LINE__, GetLastError(),
                                  TEXT("WriteFile failed."));

        _putts(TEXT("[*] license_file has been generated."));
    }
}


code:
#include "NavicatKeygen.hpp"

void NavicatKeygen::DoEncrypt() noexcept {
    const_DES_cblock key = { 0x64, 0xAD, 0xF3, 0x2F, 0xAE, 0xF2, 0x1A, 0x27 };
    DES_key_schedule schedule;
    DES_set_key_unchecked(&key, &schedule);
    DES_ecb_encrypt(reinterpret_cast<const_DES_cblock*>(_data + 2),
                    reinterpret_cast<const_DES_cblock*>(_data + 2),
                    &schedule,
                    DES_ENCRYPT);
}

NavicatKeygen::NavicatKeygen() :
    _rand_eng(_rand_dev()),
    _rand(0, UINT8_MAX),
    _data{ 0x68 , 0x2A } {}

void NavicatKeygen::SetLanguageSignature(Language Value) noexcept {
    switch (Value) {
        case Language::English:
            _data[5] = 0xAC;       // Must be 0xAC for English version.
            _data[6] = 0x88;       // Must be 0x88 for English version.
            break;
        case Language::SimplifiedChinese:
            _data[5] = 0xCE;       // Must be 0xCE for Simplified Chinese version.
            _data[6] = 0x32;       // Must be 0x32 for Simplified Chinese version.
            break;
        case Language::TraditionalChinese:
            _data[5] = 0xAA;       // Must be 0xAA for Traditional Chinese version.
            _data[6] = 0x99;       // Must be 0x99 for Traditional Chinese version.
            break;
        case Language::Japanese:
            _data[5] = 0xAD;       // Must be 0xAD for Japanese version. Discoverer: @dragonflylee
            _data[6] = 0x82;       // Must be 0x82 for Japanese version. Discoverer: @dragonflylee
            break;
        case Language::Polish:
            _data[5] = 0xBB;       // Must be 0xBB for Polish version. Discoverer: @dragonflylee
            _data[6] = 0x55;       // Must be 0x55 for Polish version. Discoverer: @dragonflylee
            break;
        case Language::Spanish:
            _data[5] = 0xAE;       // Must be 0xAE for Spanish version. Discoverer: @dragonflylee
            _data[6] = 0x10;       // Must be 0x10 for Spanish version. Discoverer: @dragonflylee
            break;
        case Language::French:
            _data[5] = 0xFA;       // Must be 0xFA for French version. Discoverer: @Deltafox79
            _data[6] = 0x20;       // Must be 0x20 for French version. Discoverer: @Deltafox79
            break;
        case Language::German:
            _data[5] = 0xB1;       // Must be 0xB1 for German version. Discoverer: @dragonflylee
            _data[6] = 0x60;       // Must be 0x60 for German version. Discoverer: @dragonflylee
            break;
        case Language::Korean:
            _data[5] = 0xB5;       // Must be 0xB5 for Korean version. Discoverer: @dragonflylee
            _data[6] = 0x60;       // Must be 0x60 for Korean version. Discoverer: @dragonflylee
            break;
        case Language::Russian:
            _data[5] = 0xEE;       // Must be 0xB5 for Russian version. Discoverer: @dragonflylee
            _data[6] = 0x16;       // Must be 0x60 for Russian version. Discoverer: @dragonflylee
            break;
        case Language::Portuguese:
            _data[5] = 0xCD;       // Must be 0xCD for Portuguese version. Discoverer: @dragonflylee
            _data[6] = 0x49;       // Must be 0x49 for Portuguese version. Discoverer: @dragonflylee
            break;
        default:
            break;
    }
}

void NavicatKeygen::SetLanguageSignature(uint8_t Value0, uint8_t Value1) noexcept {
    _data[5] = Value0;
    _data[6] = Value1;
}

void NavicatKeygen::SetProductSignature(Product Value) noexcept {
    switch (Value) {
        case Product::DataModeler:
            _data[7] = 0x47;
            break;
        case Product::Premium:
            _data[7] = 0x65;
            break;
        case Product::MySQL:
            _data[7] = 0x68;
            break;
        case Product::PostgreSQL:
            _data[7] = 0x6C;
            break;
        case Product::Oracle:
            _data[7] = 0x70;
            break;
        case Product::SQLServer:
            _data[7] = 0x74;
            break;
        case Product::SQLite:
            _data[7] = 0x78;
            break;
        case Product::MariaDB:
            _data[7] = 0x7C;
            break;
        case Product::MongoDB:
            _data[7] = 0x80;
            break;
        case Product::ReportViewer:
            _data[7] = 0xb;
        default:
            break;
    }
}

void NavicatKeygen::SetProductSignature(uint8_t Value) noexcept {
    _data[7] = Value;
}

void NavicatKeygen::SetVersion(uint8_t VersionNumber) noexcept {
    _data[8] = VersionNumber << 4;
}

void NavicatKeygen::Generate() noexcept {
    _data[2] = _rand(_rand_eng);
    _data[3] = _rand(_rand_eng);
    _data[4] = _rand(_rand_eng);
    _data[9] = 0x32;
    DoEncrypt();
}

TString NavicatKeygen::GetSerialNumber(bool NoDash) const {
    static const TCHAR EncodeTable[] = TEXT("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567");

    TString SerialNumber;
    SerialNumber.resize(16);

    SerialNumber[0] = EncodeTable[_data[0] >> 3];
    SerialNumber[1] = EncodeTable[(_data[0] & 0x07) << 2 | _data[1] >> 6];
    SerialNumber[2] = EncodeTable[_data[1] >> 1 & 0x1F];
    SerialNumber[3] = EncodeTable[(_data[1] & 0x1) << 4 | _data[2] >> 4];
    SerialNumber[4] = EncodeTable[(_data[2] & 0xF) << 1 | _data[3] >> 7];
    SerialNumber[5] = EncodeTable[_data[3] >> 2 & 0x1F];
    SerialNumber[6] = EncodeTable[_data[3] << 3 & 0x1F | _data[4] >> 5];
    SerialNumber[7] = EncodeTable[_data[4] & 0x1F];

    SerialNumber[8] = EncodeTable[_data[5] >> 3];
    SerialNumber[9] = EncodeTable[(_data[5] & 0x07) << 2 | _data[6] >> 6];
    SerialNumber[10] = EncodeTable[_data[6] >> 1 & 0x1F];
    SerialNumber[11] = EncodeTable[(_data[6] & 0x1) << 4 | _data[7] >> 4];
    SerialNumber[12] = EncodeTable[(_data[7] & 0xF) << 1 | _data[8] >> 7];
    SerialNumber[13] = EncodeTable[_data[8] >> 2 & 0x1F];
    SerialNumber[14] = EncodeTable[_data[8] << 3 & 0x1F | _data[9] >> 5];
    SerialNumber[15] = EncodeTable[_data[9] & 0x1F];

    if (NoDash) {
        return SerialNumber;
    } else {
        return TStringFormat(TEXT("%.4s-%.4s-%.4s-%.4s"),
                             SerialNumber.c_str(),
                             SerialNumber.c_str() + 4,
                             SerialNumber.c_str() + 8,
                             SerialNumber.c_str() + 12);
    }
}


code:
#pragma once
#include <openssl/des.h>
#include <random>
#include "TString.hpp"

class NavicatKeygen {
public:
    enum class Language {
        English,
        SimplifiedChinese,
        TraditionalChinese,
        Japanese,
        Polish,
        Spanish,
        French,
        German,
        Korean,
        Russian,
        Portuguese
    };

    enum class Product {
        DataModeler,
        Premium,
        MySQL,
        PostgreSQL,
        Oracle,
        SQLServer,
        SQLite,
        MariaDB,
        MongoDB,
        ReportViewer
    };
private:
    std::random_device _rand_dev;
    std::default_random_engine _rand_eng;
    std::uniform_int_distribution<int> _rand;
    uint8_t _data[10];

    void DoEncrypt() noexcept;
public:

    NavicatKeygen();

    void SetLanguageSignature(Language Value) noexcept;
    void SetLanguageSignature(uint8_t Value0, uint8_t Value1) noexcept;
    void SetProductSignature(Product Value) noexcept;
    void SetProductSignature(uint8_t Value) noexcept;
    void SetVersion(uint8_t VersionNumber) noexcept;
    void Generate() noexcept;
    TString GetSerialNumber(bool NoDash = false) const;
};


code:
#include <tchar.h>
#include <windows.h>
#include "ResourceObject.hpp"
#include "RSACipher.hpp"

void NormalMode(RSACipher* pCipher, bool bGenerateText);
void AdvanceMode(RSACipher* pCipher, bool bGenerateText);

static void Welcome() {
    _putts(TEXT("***************************************************"));
    _putts(TEXT("*       Navicat Keygen by @DoubleLabyrinth        *"));
    _putts(TEXT("*                   Version: 3.2                  *"));
    _putts(TEXT("***************************************************"));
    _putts(TEXT(""));
}

static void Help() {
    _putts(TEXT("Usage:"));
    _putts(TEXT("    navicat-keygen.exe <-bin|-text> [-adv] <RSA-2048 Private Key File>"));
    _putts(TEXT(""));
    _putts(TEXT("    <-bin|-text>       Specify \"-bin\" to generate \"license_file\" used by Navicat 11."));
    _putts(TEXT("                       Specify \"-text\" to generate base64-encoded activation code."));
    _putts(TEXT("                       This parameter must be specified."));
    _putts(TEXT(""));
    _putts(TEXT("    [-adv]             Enable advance mode."));
    _putts(TEXT("                       This parameter is optional."));
    _putts(TEXT(""));
    _putts(TEXT("    <RSA-2048 Private Key File>    A path to an RSA-2048 private key file."));
    _putts(TEXT("                                   This parameter must be specified."));
    _putts(TEXT(""));
    _putts(TEXT("Example:"));
    _putts(TEXT("    navicat-keygen.exe -text .\\RegPrivateKey.pem"));
}

int _tmain(int argc, PTSTR argv[]) {
    if (argc != 3 && argc != 4) {
        Help();
        return 0;
    }

    Welcome();

    bool bGenerateText;
    bool bAdvanceMode;
    ResourceObject<CppObjectTraits<RSACipher>> pCipher;

    if (_tcsicmp(argv[1], TEXT("-bin")) == 0) {
        bGenerateText = false;
    } else if (_tcsicmp(argv[1], TEXT("-text")) == 0) {
        bGenerateText = true;
    } else {
        Help();
        return 0;
    }

    if (argc == 4) {
        if (_tcsicmp(argv[2], TEXT("-adv")) == 0) {
            bAdvanceMode = true;
        } else {
            Help();
            return 0;
        }
    } else {
        bAdvanceMode = false;
    }

    pCipher.TakeOver(new RSACipher());

    try {
        pCipher->ImportKeyFromFile<RSAKeyType::PrivateKey, RSAKeyFormat::PEM>(TStringEncode(argv[argc - 1], CP_ACP));
        if (bAdvanceMode) {
            AdvanceMode(pCipher, bGenerateText);
        } else {
            NormalMode(pCipher, bGenerateText);
        }
    } catch (Exception& e) {
        _tprintf_s(TEXT("[*] ERROR: %s\n"), e.Message().c_str());
        _tprintf_s(TEXT(" | - File: %s\n"), e.File().c_str());
        _tprintf_s(TEXT(" | - Line: %zu\n"), e.Line());
        if (e.HasErrorCode()) {
            _tprintf_s(TEXT(" | - ErrorCode: 0x%.8zx\n"), e.ErrorCode());
            _tprintf_s(TEXT(" | - ErrorString: %s\n"), e.ErrorString().c_str());
        }

        if (e.Hints().size() != 0) {
            _putts(TEXT(" | - Hints:"));
            for (auto& Hint : e.Hints())
                _tprintf_s(TEXT(" |   %s\n"), Hint.c_str());
        }

        _putts(TEXT(""));
    }
    return 0;
}


code:
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup Label="ProjectConfigurations">
    <ProjectConfiguration Include="Debug|Win32">
      <Configuration>Debug</Configuration>
      <Platform>Win32</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Release|Win32">
      <Configuration>Release</Configuration>
      <Platform>Win32</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Debug|x64">
      <Configuration>Debug</Configuration>
      <Platform>x64</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Release|x64">
      <Configuration>Release</Configuration>
      <Platform>x64</Platform>
    </ProjectConfiguration>
  </ItemGroup>
  <PropertyGroup Label="Globals">
    <ProjectGuid>{CB49F054-83AB-4C16-B73B-33D7DF696E16}</ProjectGuid>
    <Keyword>Win32Proj</Keyword>
    <RootNamespace>navicatkeygen</RootNamespace>
    <WindowsTargetPlatformVersion>8.1</WindowsTargetPlatformVersion>
  </PropertyGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
    <ConfigurationType>Application</ConfigurationType>
    <UseDebugLibraries>true</UseDebugLibraries>
    <PlatformToolset>v141</PlatformToolset>
    <CharacterSet>Unicode</CharacterSet>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
    <ConfigurationType>Application</ConfigurationType>
    <UseDebugLibraries>false</UseDebugLibraries>
    <PlatformToolset>v141</PlatformToolset>
    <WholeProgramOptimization>true</WholeProgramOptimization>
    <CharacterSet>Unicode</CharacterSet>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
    <ConfigurationType>Application</ConfigurationType>
    <UseDebugLibraries>true</UseDebugLibraries>
    <PlatformToolset>v141</PlatformToolset>
    <CharacterSet>Unicode</CharacterSet>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
    <ConfigurationType>Application</ConfigurationType>
    <UseDebugLibraries>false</UseDebugLibraries>
    <PlatformToolset>v141</PlatformToolset>
    <WholeProgramOptimization>true</WholeProgramOptimization>
    <CharacterSet>Unicode</CharacterSet>
  </PropertyGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
  <ImportGroup Label="ExtensionSettings">
  </ImportGroup>
  <ImportGroup Label="Shared">
    <Import Project="..\common\common.vcxitems" Label="Shared" />
  </ImportGroup>
  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
  </ImportGroup>
  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
  </ImportGroup>
  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
  </ImportGroup>
  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
  </ImportGroup>
  <PropertyGroup Label="UserMacros" />
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
    <LinkIncremental>true</LinkIncremental>
    <IncludePath>$(SolutionDir)libraries\rapidjson\include;$(SolutionDir)libraries\openssl\include;$(IncludePath)</IncludePath>
    <LibraryPath>$(SolutionDir)libraries\openssl\lib;$(LibraryPath)</LibraryPath>
    <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
    <IntDir>$(Platform)\$(Configuration)\</IntDir>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
    <LinkIncremental>true</LinkIncremental>
    <IncludePath>$(SolutionDir)libraries\rapidjson\include;$(SolutionDir)libraries\openssl\include64;$(IncludePath)</IncludePath>
    <LibraryPath>$(SolutionDir)libraries\openssl\lib64;$(LibraryPath)</LibraryPath>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
    <LinkIncremental>false</LinkIncremental>
    <IncludePath>$(SolutionDir)libraries\rapidjson\include;$(SolutionDir)libraries\openssl\include;$(IncludePath)</IncludePath>
    <LibraryPath>$(SolutionDir)libraries\openssl\lib;$(LibraryPath)</LibraryPath>
    <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
    <IntDir>$(Platform)\$(Configuration)\</IntDir>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
    <LinkIncremental>false</LinkIncremental>
    <IncludePath>$(SolutionDir)libraries\rapidjson\include;$(SolutionDir)libraries\openssl\include64;$(IncludePath)</IncludePath>
    <LibraryPath>$(SolutionDir)libraries\openssl\lib64;$(LibraryPath)</LibraryPath>
  </PropertyGroup>
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
    <ClCompile>
      <PrecompiledHeader>
      </PrecompiledHeader>
      <WarningLevel>Level3</WarningLevel>
      <Optimization>Disabled</Optimization>
      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
      <SDLCheck>true</SDLCheck>
      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
      <AdditionalOptions>/std:c++latest</AdditionalOptions>
    </ClCompile>
    <Link>
      <SubSystem>Console</SubSystem>
      <GenerateDebugInformation>true</GenerateDebugInformation>
    </Link>
  </ItemDefinitionGroup>
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
    <ClCompile>
      <PrecompiledHeader>
      </PrecompiledHeader>
      <WarningLevel>Level3</WarningLevel>
      <Optimization>Disabled</Optimization>
      <PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
      <SDLCheck>true</SDLCheck>
      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
      <AdditionalOptions>/std:c++latest</AdditionalOptions>
    </ClCompile>
    <Link>
      <SubSystem>Console</SubSystem>
      <GenerateDebugInformation>true</GenerateDebugInformation>
    </Link>
  </ItemDefinitionGroup>
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
    <ClCompile>
      <WarningLevel>Level3</WarningLevel>
      <PrecompiledHeader>
      </PrecompiledHeader>
      <Optimization>MaxSpeed</Optimization>
      <FunctionLevelLinking>true</FunctionLevelLinking>
      <IntrinsicFunctions>true</IntrinsicFunctions>
      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
      <SDLCheck>true</SDLCheck>
      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
      <AdditionalOptions>/std:c++latest</AdditionalOptions>
    </ClCompile>
    <Link>
      <SubSystem>Console</SubSystem>
      <EnableCOMDATFolding>true</EnableCOMDATFolding>
      <OptimizeReferences>true</OptimizeReferences>
      <GenerateDebugInformation>true</GenerateDebugInformation>
    </Link>
  </ItemDefinitionGroup>
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
    <ClCompile>
      <WarningLevel>Level3</WarningLevel>
      <PrecompiledHeader>
      </PrecompiledHeader>
      <Optimization>MaxSpeed</Optimization>
      <FunctionLevelLinking>true</FunctionLevelLinking>
      <IntrinsicFunctions>true</IntrinsicFunctions>
      <PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
      <SDLCheck>true</SDLCheck>
      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
      <AdditionalOptions>/std:c++latest</AdditionalOptions>
    </ClCompile>
    <Link>
      <SubSystem>Console</SubSystem>
      <EnableCOMDATFolding>true</EnableCOMDATFolding>
      <OptimizeReferences>true</OptimizeReferences>
      <GenerateDebugInformation>true</GenerateDebugInformation>
    </Link>
  </ItemDefinitionGroup>
  <ItemGroup>
    <ClCompile Include="ModeAdvance.cpp" />
    <ClCompile Include="Helper.cpp" />
    <ClCompile Include="ModeNormal.cpp" />
    <ClCompile Include="NavicatKeygen.cpp" />
    <ClCompile Include="_tmain.cpp" />
  </ItemGroup>
  <ItemGroup>
    <ClInclude Include="Helper.hpp" />
    <ClInclude Include="NavicatKeygen.hpp" />
  </ItemGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
  <ImportGroup Label="ExtensionTargets">
  </ImportGroup>
</Project>


code:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup>
    <Filter Include="源文件">
      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
    </Filter>
    <Filter Include="头文件">
      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
      <Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
    </Filter>
    <Filter Include="资源文件">
      <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
    </Filter>
  </ItemGroup>
  <ItemGroup>
    <ClCompile Include="Helper.cpp">
      <Filter>源文件</Filter>
    </ClCompile>
    <ClCompile Include="_tmain.cpp">
      <Filter>源文件</Filter>
    </ClCompile>
    <ClCompile Include="ModeAdvance.cpp">
      <Filter>源文件</Filter>
    </ClCompile>
    <ClCompile Include="ModeNormal.cpp">
      <Filter>源文件</Filter>
    </ClCompile>
    <ClCompile Include="NavicatKeygen.cpp">
      <Filter>源文件</Filter>
    </ClCompile>
  </ItemGroup>
  <ItemGroup>
    <ClInclude Include="NavicatKeygen.hpp">
      <Filter>头文件</Filter>
    </ClInclude>
    <ClInclude Include="Helper.hpp">
      <Filter>头文件</Filter>
    </ClInclude>
  </ItemGroup>
</Project>


code:
#include "CapstoneDisassembler.hpp"
#include <memory.h>

// libs required by capstone
#pragma comment(lib, "legacy_stdio_definitions.lib")
#if defined(_M_AMD64)
#pragma comment(lib, "capstone_static.lib")
#else
#pragma comment(lib, "capstone.lib")
#endif

// ----------- avoid link error caused by capstone_static.lib
#define stdin  (__acrt_iob_func(0))
#define stdout (__acrt_iob_func(1))
#define stderr (__acrt_iob_func(2))

FILE _iob[] = { *stdin, *stdout, *stderr };

extern "C" FILE* __cdecl __iob_func(void) {
    return _iob;
}
// ------------

#undef __BASE_FILE__
#define __BASE_FILE__ TEXT("CapstoneDisassembler.cpp")

bool CapstoneDisassembler::Context::operator==(const CapstoneDisassembler::Context& Other) const noexcept {
    return memcmp(this, &Other, sizeof(Context)) == 0;
}

bool CapstoneDisassembler::Context::operator!=(const CapstoneDisassembler::Context& Other) const noexcept {
    return memcmp(this, &Other, sizeof(Context)) != 0;
}

CapstoneDisassembler::CapstoneDisassembler(const CapstoneEngine& Engine) :
    _EngineRef(Engine),
    _Context(InvalidContext),
    _InsnPtr(nullptr)
{
    cs_insn* insn;
    insn = cs_malloc(_EngineRef);
    if (insn == nullptr)
        throw CapstoneException(__BASE_FILE__, __LINE__, cs_errno(_EngineRef),
                                TEXT("cs_malloc failed."));
    else
        _InsnObj.TakeOver(insn);
}

void CapstoneDisassembler::SetContext(const uint8_t* Opcodes, size_t Size, uint64_t Address) noexcept {
    _Context.Opcode.ConstPtr = Opcodes;
    _Context.OpcodesSize = Size;
    _Context.Address = Address;
    _InsnPtr = nullptr;
}

void CapstoneDisassembler::SetContext(const CapstoneDisassembler::Context& Context) noexcept {
    _Context = Context;
    _InsnPtr = nullptr;
}

const CapstoneDisassembler::Context& CapstoneDisassembler::GetContext() const noexcept {
    return _Context;
}

bool CapstoneDisassembler::Next() noexcept {
    bool bOk = cs_disasm_iter(_EngineRef,
                              &_Context.Opcode.ConstPtr,
                              &_Context.OpcodesSize,
                              &_Context.Address,
                              _InsnObj);
    if (bOk) {
        if (_InsnPtr == nullptr)
            _InsnPtr = _InsnObj;
    } else {
        _InsnPtr = nullptr;
    }
    return bOk;
}

cs_insn* CapstoneDisassembler::Instruction() const noexcept {
    return _InsnPtr;
}

CapstoneDisassembler::Context CapstoneDisassembler::InstructionContext() const noexcept {
    Context ContextOfInsn;
    ContextOfInsn.Opcode.Ptr = _Context.Opcode.Ptr - _InsnPtr->size;
    ContextOfInsn.OpcodesSize = _Context.OpcodesSize + _InsnPtr->size;
    ContextOfInsn.Address = _Context.Address - _InsnPtr->size;
    return ContextOfInsn;
}

CapstoneEngine::CapstoneEngine(cs_arch ArchType, cs_mode Mode) {
    cs_err status;
    csh handle;

    status = cs_open(ArchType, Mode, &handle);
    if (status != CS_ERR_OK)
        throw CapstoneException(__BASE_FILE__, __LINE__, status,
                                TEXT("cs_open failed."));
    else
        _EngineObj.TakeOver(handle);
}

CapstoneEngine::operator csh() const noexcept {
    return _EngineObj.Get();
}

void CapstoneEngine::Option(cs_opt_type Type, size_t Value) {
    cs_err status;
    status = cs_option(_EngineObj, Type, Value);
    if (status != CS_ERR_OK)
        throw CapstoneException(__BASE_FILE__, __LINE__, status,
                                TEXT("cs_open failed."));
}

CapstoneDisassembler CapstoneEngine::CreateDisassembler() const {
    return CapstoneDisassembler(*this);
}


code:
#pragma once
#include <capstone/capstone.h>
#include "ExceptionCapstone.hpp"
#include "ResourceObject.hpp"

struct CapstoneHandleTraits {
    using HandleType = csh;
    static inline const HandleType InvalidValue = 0;
    static inline void Releasor(HandleType Handle) {
        cs_close(&Handle);
    }
};

template<typename __Type>
struct CapstoneMallocTraits {
    using HandleType = __Type*;
    static inline const HandleType InvalidValue = nullptr;
    static inline void Releasor(HandleType Handle) {
        cs_free(Handle, 1);
    }
};

class CapstoneDisassembler {
    friend class CapstoneEngine;
public:

    struct Context {
        union {
            const uint8_t* ConstPtr;
            uint8_t* Ptr;
        } Opcode;
        size_t OpcodesSize;
        uint64_t Address;

        bool operator==(const Context& Other) const noexcept;
        bool operator!=(const Context& Other) const noexcept;
    };

    static inline Context InvalidContext = {};

private:
    const CapstoneEngine& _EngineRef;
    Context _Context;
    ResourceObject<CapstoneMallocTraits<cs_insn>> _InsnObj;
    cs_insn* _InsnPtr;

    explicit CapstoneDisassembler(const CapstoneEngine& Engine);
public:

    void SetContext(const uint8_t* Opcodes, size_t Size, uint64_t Address = 0) noexcept;
    void SetContext(const Context& Context) noexcept;

    const Context& GetContext() const noexcept;

    bool Next() noexcept;

    cs_insn* Instruction() const noexcept;

    Context InstructionContext() const noexcept;
};

class CapstoneEngine {
private:
    ResourceObject<CapstoneHandleTraits> _EngineObj;
public:

    CapstoneEngine(cs_arch ArchType, cs_mode Mode);

    operator csh() const noexcept;

    void Option(cs_opt_type Type, size_t Value);

    CapstoneDisassembler CreateDisassembler() const;
};


code:
#pragma once
#include "Exception.hpp"
#include <capstone/capstone.h>

class CapstoneException : public Exception {
private:
    cs_err _ErrorCode;
    TString _ErrorString;
public:

    template<typename... __Ts>
    CapstoneException(const TString& FileName,
                      size_t LineNumber,
                      cs_err ErrCode,
                      const TString& CustomMsg, __Ts&&... SomeHints) noexcept :
        Exception(FileName, LineNumber, CustomMsg, std::forward<__Ts>(SomeHints)...),
        _ErrorCode(ErrCode),
        _ErrorString(TStringBuilder(cs_strerror(ErrCode))) {}

    virtual bool HasErrorCode() const noexcept override {
        return true;
    }

    virtual uintptr_t ErrorCode() const noexcept override {
        return _ErrorCode;
    }

    virtual const TString& ErrorString() const noexcept override {
        return _ErrorString;
    }
};


code:
#pragma once
#include <windows.h>
#include "ExceptionSystem.hpp"
#include "ResourceObject.hpp"

#undef __BASE_FILE__
#define __BASE_FILE__ TEXT("FileManipulation.hpp")

struct GenericHandleTraits {
    using HandleType = HANDLE;
    static inline const HandleType InvalidValue = NULL;
    static constexpr auto& Releasor = CloseHandle;
};

struct FileHandleTraits {
    using HandleType = HANDLE;
    static inline const HandleType InvalidValue = INVALID_HANDLE_VALUE;
    static constexpr auto& Releasor = CloseHandle;
};

struct MapViewTraits {
    using HandleType = PVOID;
    static inline const HandleType InvalidValue = NULL;
    static constexpr auto& Releasor = UnmapViewOfFile;
};

class FileObject {
private:
    ResourceObject<FileHandleTraits> _Obj;

    explicit FileObject(HANDLE Handle) noexcept:
        _Obj(Handle) {}
public:

    static bool IsExist(const TString& FileName) {
        DWORD dwAttributes = GetFileAttributes(FileName.c_str());
        if (dwAttributes == INVALID_FILE_ATTRIBUTES) {
            if (GetLastError() == ERROR_FILE_NOT_FOUND)
                return false;
            else
                throw SystemException(__BASE_FILE__, __LINE__, GetLastError(),
                                      TEXT("GetFileAttributes failed."));
        } else {
            return (dwAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0;
        }
    }

    template<typename __ReturnType>
    static __ReturnType Create(const TString& FileName, DWORD DesireAccess, DWORD ShareMode) {
        static_assert(std::is_same<__ReturnType, FileObject>::value ||
                      std::is_same<__ReturnType, FileObject*>::value);
        HANDLE Handle = ::CreateFile(FileName.c_str(),
                                     DesireAccess,
                                     ShareMode,
                                     NULL,
                                     CREATE_ALWAYS,
                                     FILE_ATTRIBUTE_NORMAL,
                                     NULL);
        if (Handle == INVALID_HANDLE_VALUE) {
            throw SystemException(__BASE_FILE__, __LINE__, GetLastError(),
                                  TEXT("CreateFile failed."));
        }

        if constexpr (std::is_same<__ReturnType, FileObject>::value)
            return FileObject(Handle);
        else
            return new FileObject(Handle);
    }

    template<typename __ReturnType>
    static __ReturnType Open(const TString& FileName, DWORD DesireAccess, DWORD ShareMode) {
        static_assert(std::is_same<__ReturnType, FileObject>::value ||
                      std::is_same<__ReturnType, FileObject*>::value);
        HANDLE FileHandle = ::CreateFile(FileName.c_str(),
                                         DesireAccess,
                                         ShareMode,
                                         NULL,
                                         OPEN_EXISTING,
                                         FILE_ATTRIBUTE_NORMAL,
                                         NULL);
        if (FileHandle == INVALID_HANDLE_VALUE) {
            throw SystemException(__BASE_FILE__, __LINE__, GetLastError(),
                                  TEXT("CreateFile failed."));
        }

        if constexpr (std::is_same<__ReturnType, FileObject>::value)
            return FileObject(FileHandle);
        else
            return new FileObject(FileHandle);
    }

    HANDLE GetHandle() const noexcept {
        return _Obj.Get();
    }

    UINT64 GetSize() const {
        LARGE_INTEGER Val;
        if (GetFileSizeEx(_Obj, &Val)) {
            return Val.QuadPart;
        } else {
            throw SystemException(__BASE_FILE__, __LINE__, GetLastError(),
                                  TEXT("GetFileSizeEx failed."));
        }
    }

    void Destroy() {
        _Obj.Release();
    }
};

class FileMapViewObject {
private:
    ResourceObject<GenericHandleTraits> _MapObj;
    ResourceObject<MapViewTraits> _ViewObj;

    explicit FileMapViewObject(HANDLE MapHandle) noexcept :
        _MapObj(MapHandle) {}
public:

    template<typename __ReturnType>
    static __ReturnType Create(HANDLE FileHandle, DWORD ProtectAttributes) {
        static_assert(std::is_same<__ReturnType, FileMapViewObject>::value ||
                      std::is_same<__ReturnType, FileMapViewObject*>::value);
        HANDLE MapHandle = CreateFileMapping(FileHandle,
                                             NULL,
                                             ProtectAttributes,
                                             0,
                                             0,
                                             NULL);
        if (MapHandle == NULL) {
            throw SystemException(__BASE_FILE__, __LINE__, GetLastError(),
                                  TEXT("CreateFileMapping failed."));
        }

        if constexpr (std::is_same<__ReturnType, FileMapViewObject>::value)
            return FileMapViewObject(MapHandle);
        else
            return new FileMapViewObject(MapHandle);
    }

    void Map(DWORD DesiredAccess, UINT64 Offset = 0, SIZE_T Size = 0) {
        PVOID pView = MapViewOfFile(_MapObj,
                                    DesiredAccess,
                                    static_cast<DWORD>(Offset >> 32),
                                    static_cast<DWORD>(Offset),
                                    Size);
        if (pView == NULL) {
            throw SystemException(__BASE_FILE__, __LINE__, GetLastError(),
                                  TEXT("MapViewOfFile failed."));
        } else {
            _ViewObj.TakeOver(pView);
        }
    }

    void Unmap() {
        _ViewObj.Release();
    }

    void Destory() {
        Unmap();
        _MapObj.Release();
    }

    template<typename __Type>
    __Type* View() const noexcept {
        return reinterpret_cast<__Type*>(_ViewObj.Get());
    }

    template<typename __Type>
    const __Type* ConstView() const noexcept {
        return reinterpret_cast<__Type*>(_ViewObj.Get());
    }
};


code:
#include "Helper.hpp"
#include <tchar.h>
#include <windows.h>

namespace Helper {

    Navicat11Crypto NavicatCipher("23970790", 8);

    //
    //  read byte(s) at address `p` as _Type to `out`
    //  succeed if return true, otherwise return false
    //
    template<typename _Type>
    static __forceinline bool ProbeForRead(const void* p, void* out) {
        __try {
            *reinterpret_cast<_Type*>(out) = *reinterpret_cast<const _Type*>(p);
            return true;
        } __except (EXCEPTION_EXECUTE_HANDLER) {
            return false;
        }
    }

    void PrintMemory(const void* from, const void* to, const void* base) {
        const uint8_t* start = reinterpret_cast<const uint8_t*>(from);
        const uint8_t* end = reinterpret_cast<const uint8_t*>(to);
        const uint8_t* base_ptr = reinterpret_cast<const uint8_t*>(base);

        if (start >= end)
            return;

        while (reinterpret_cast<uintptr_t>(start) % 16)
            start--;

        while (reinterpret_cast<uintptr_t>(start) % 16)
            end++;

        while (start < end) {
            uint16_t value[16] = {};

            if (base_ptr) {
                uintptr_t d = start >= base ? start - base_ptr : base_ptr - start;
                if (start >= base) {
                    if constexpr (sizeof(void*) == 4) {
                        _tprintf(TEXT("+0x%.8zx  "), d);
                    }
                    if constexpr (sizeof(void*) == 8) {
                        _tprintf(TEXT("+0x%.16zx  "), d);
                    }
                } else {
                    if constexpr (sizeof(void*) == 4) {
                        _tprintf(TEXT("-0x%.8zx  "), d);
                    }
                    if constexpr (sizeof(void*) == 8) {
                        _tprintf(TEXT("-0x%.16zx  "), d);
                    }
                }
            } else {
                _tprintf(TEXT("0x%p  "), start);
            }

            for (int i = 0; i < 16; ++i) {
                if (ProbeForRead<uint8_t>(start + i, value + i)) {
                    _tprintf(TEXT("%.2x "), value[i]);
                } else {
                    value[i] = -1;
                    _tprintf(TEXT("?? "));
                }
            }

            _tprintf(TEXT(" "));

            for (int i = 0; i < 16; ++i) {
                if (value[i] < 0x20) {
                    _tprintf(TEXT("."));
                } else if (value[i] > 0x7e) {
                    _tprintf(TEXT("."));
                } else {
                    _tprintf(TEXT("%c"), value[i]);
                }
            }

            _tprintf(TEXT("\n"));

            start += 0x10;
        }
    }

    void PrintBytes(const void* p, size_t s) {
        const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(p);

        if (s == 0)
            return;

        if (s == 1) {
            _tprintf_s(TEXT("%.2X"), byte_ptr[0]);
            return;
        }

        s -= 1;
        for (size_t i = 0; i < s; ++i)
            _tprintf_s(TEXT("%.2X "), byte_ptr[i]);

        _tprintf_s(TEXT("%.2X"), byte_ptr[s]);
    }

    bool IsPrintable(const uint8_t* p, size_t s) {
        for (size_t i = 0; i < s; ++i)
            if (isprint(p[i]) == false)
                return false;
        return true;
    }
}


code:
#pragma once
#include <sys/types.h>
#include "NavicatCrypto.hpp"

namespace Helper {

    extern Navicat11Crypto NavicatCipher;

    template<typename _Type, bool _Ascending = true>
    void QuickSort(_Type* pArray, off_t begin, off_t end) {
        if (end - begin <= 1)
            return;

        off_t i = begin;
        off_t j = end - 1;
        _Type seperator = static_cast<_Type&&>(pArray[begin]);

        while (i < j) {
            if (_Ascending) {
                while (i < j && seperator <= pArray[j])
                    --j;

                if (i < j)
                    pArray[i++] = static_cast<_Type&&>(pArray[j]);

                while (i < j && pArray[i] <= seperator)
                    ++i;

                if (i < j)
                    pArray[j--] = static_cast<_Type&&>(pArray[i]);
            } else {
                while (i < j && seperator >= pArray[j])
                    --j;

                if (i < j)
                    pArray[i++] = static_cast<_Type&&>(pArray[j]);

                while (i < j && pArray[i] >= seperator)
                    ++i;

                if (i < j)
                    pArray[j--] = static_cast<_Type&&>(pArray[i]);
            }
        }

        pArray[i] = static_cast<_Type&&>(seperator);
        QuickSort<_Type, _Ascending>(pArray, begin, i);
        QuickSort<_Type, _Ascending>(pArray, i + 1, end);
    }

    //
    //  Print memory data in [from, to) at least
    //  If `base` is not nullptr, print address as offset. Otherwise, as absolute address.
    //  NOTICE:
    //      `base` must <= `from`
    //
    void PrintMemory(const void* from, const void* to, const void* base = nullptr);
    void PrintBytes(const void* p, size_t s);
    bool IsPrintable(const uint8_t* p, size_t s);

    template<typename __string_t>
    void StringReplace(__string_t& Str, const __string_t& OldSubStr, const __string_t& NewSubStr) {
        typename __string_t::size_type pos = 0;
        auto srclen = OldSubStr.size();
        auto dstlen = NewSubStr.size();

        while ((pos = Str.find(OldSubStr, pos)) != __string_t::npos) {
            Str.replace(pos, srclen, NewSubStr);
            pos += dstlen;
        }
    }

    template<typename __string_t>
    void StringRemove(__string_t& Str, const __string_t& SubStr) {
        typename __string_t::size_type pos = 0;
        while ((pos = Str.find(SubStr, pos)) != __string_t::npos) {
            Str.erase(pos, SubStr.length());
        }
    }
}