stringClass
A class for managing and manipulating encrypted strings. More...
Public Functions
Type | Name |
---|---|
string (const const_string< const_key, Hash, const_size > &src) noexcept | |
string (const char *src) noexcept | |
string (const wchar_t *src) noexcept | |
string (const char32_t *src) noexcept | |
string (const ::std::string &src) noexcept | |
string (const ::std::wstring &src) noexcept | |
string (const ::std::u32string &src) noexcept | |
string (const string &src)=default | |
string (const string &&src) noexcept | |
string & | operator= (const string &other) |
string & | operator= (string &&other) noexcept |
char32_t | operator[] (const size_t index) const noexcept |
size_t | size () const |
bool | empty () const noexcept |
void | append (const string &cs) |
size_t | get_hash () const |
~string () noexcept |
Private Properties
Type | Name |
---|---|
size_t | key_ |
size_t | hash_ |
Friends
Type | Name |
---|---|
bool | operator== (const string &lhs, const string &rhs) noexcept |
bool | operator!= (const string &lhs, const string &rhs) noexcept |
bool | operator< (const string &lhs, const string &rhs) noexcept |
bool | operator<= (const string &lhs, const string &rhs) noexcept |
bool | operator> (const string &lhs, const string &rhs) noexcept |
bool | operator>= (const string &lhs, const string &rhs) noexcept |
Detailed Description
The string
class extends std::vector<char32_t>
to provide additional functionality for securely storing and handling encrypted strings. This class is designed to protect sensitive string data by encrypting it during storage and decrypting it on access, ensuring that the data remains secure throughout its lifecycle.
Inheritance:
The string
class inherits from std::vector<char32_t>
, leveraging the dynamic array capabilities of std::vector
to manage the encrypted string data. This provides automatic memory management, resizing, and access operations, while the string
class adds layers of encryption and security on top of these functionalities.
Key Features:
Encryption and Decryption :
The
string
class encrypts the string data upon storage and decrypts it when accessed.It uses a secure encryption key (
key_
) to ensure that the data is protected from unauthorized access or tampering.The decryption process is automatically handled when the string is accessed via conversion operators or index operations.
Hashing :
The class computes and stores a hash value (
hash_
) for the string, which can be used for quick comparisons, integrity checks, or as a unique identifier for the string.The hash is calculated based on the string's content, ensuring that even small changes in the string result in a different hash.
Conversion Operators :
The class provides conversion operators to
std::string
,std::wstring
, andstd::u32string
, allowing easy integration with standard C++ string types.These operators automatically decrypt the string before converting it, ensuring that the decrypted data is returned in the appropriate format.
Safe Destruction :
- The destructor securely erases the encryption key and string data from memory, preventing any residual data from being recovered after the string object is destroyed.
Example Usage:
int
In this example, encryptedString
is stored in an encrypted form, and when accessed, it is automatically decrypted and converted to the desired string format.
Notes:
Performance Considerations :
The encryption and decryption processes introduce some overhead compared to using plain
std::vector<char32_t>
or standard strings. However, this is a necessary trade-off for the added security.The class is designed to be used in scenarios where string data needs to be protected from unauthorized access, such as in secure communications, storage, or logging.
Security Considerations :
The
string
class provides a high level of security for sensitive data by ensuring that the string is never stored in plaintext in memory.The encryption key is generated randomly for each instance, and the hash value ensures data integrity and uniqueness.
While the class offers strong protection, it should be used as part of a broader security strategy, including other measures such as secure key management and data access control.
Public Functions
string (const const_string< const_key, Hash, const_size > &src) noexcept
Constructs a string
object from a const_string
.
Definition
libantispy::string::string
Detailed Description
This constructor initializes a string
object by decrypting and copying the contents of a const_string
object. The const_string
is a compile-time encrypted string, and this constructor allows the string
to be instantiated with the encrypted data while preserving the security measures provided by the const_string
.
Template Parameters
const_key
: The encryption key used by theconst_string
. This key is used to decrypt the contents of theconst_string
during the construction of thestring
object.const_size
: The size of the encrypted string stored in theconst_string
. This size determines the number ofchar32_t
characters that will be copied to thestring
.Hash
: The hash value associated with theconst_string
. This hash is used to verify the integrity of the data and ensure that the contents of thestring
match those of the originalconst_string
.
Parameters
src
: The sourceconst_string
object containing the encrypted string data. The constructor decrypts this data and stores it securely in thestring
object, using the same encryption key and maintaining the associated hash.
Details:
Encryption Key : The constructor initializes the
key_
member withconst_key
, which is the encryption key used by theconst_string
. This ensures that thestring
object can properly decrypt the data when accessed.Hash Value : The
hash_
member is initialized with the hash value retrieved from theconst_string
using the get_hash() method. This hash is crucial for maintaining data integrity and ensuring that thestring
accurately represents the original encrypted data.Data Copying : The constructor creates a temporary
std::vector<char32_t>
that is initialized with the decrypted data from theconst_string
. Theswap()
method is then used to efficiently move this data into thestring
object, ensuring that the data is securely stored without unnecessary copying or exposure.
Example Usage:
int
In this example, secure_string
is initialized with the encrypted data from encrypted_const_string
, and the data remains secure within the string
object.
Security Considerations:
The constructor ensures that the encryption key and hash are properly transferred from the
const_string
to thestring
, preserving the security and integrity of the data.By using
swap()
to move the data, the constructor minimizes the risk of exposing the decrypted content and ensures efficient memory management.
string (const char *src) noexcept
Constructs a string
object from a C-style string.
Definition
libantispy::string::string
Detailed Description
This constructor initializes a string
object using a C-style string ( const char*
). The constructor serves as a convenience wrapper that converts the input C-string into a std::string
, and then delegates the actual initialization process to the constructor that handles std::string
objects. This ensures that the C-string is correctly encoded and stored within the string
object, while also applying the necessary encryption and security measures.
Parameters
src
: The source C-style string to be used for initializing thestring
object. The string is expected to be null-terminated and encoded in UTF-8 format.
Details:
**Conversion to
std::string
** :- The constructor converts the provided C-string into a
std::string
. This step is necessary to ensure that the string is managed properly within the C++ standard library, which provides additional functionalities and safety compared to raw C-style strings.
- The constructor converts the provided C-string into a
Delegation :
After converting the C-string to a
std::string
, the constructor delegates the initialization to another constructor that acceptsstd::string
as an argument.This delegation ensures that all necessary encryption and encoding steps are handled consistently, regardless of whether the input was a
const char*
orstd::string
.
Example Usage:
int
In this example, secure_string
is initialized with the contents of the C-string plaintext
. The data is first converted to a std::string
, and then securely stored within the string
object.
Security Considerations:
The constructor ensures that the transition from a raw C-string to a secure
string
object is handled safely and efficiently, with minimal risk of exposing sensitive data.By delegating the actual storage and encryption process to the
std::string
constructor, this approach ensures that all security measures implemented in thestd::string
constructor are applied consistently, regardless of the input format.
string (const wchar_t *src) noexcept
Constructs a string
object from a wide C-style string.
Definition
libantispy::string::string
Detailed Description
This constructor initializes a string
object using a wide C-style string ( const wchar_t*
). It serves as a convenience wrapper that converts the input wide C-string into a std::wstring
, then delegates the actual initialization process to the constructor that handles std::wstring
objects. This ensures that the wide C-string is correctly encoded and securely stored within the string
object, while applying the necessary encryption and security measures.
Parameters
src
: The source wide C-style string to be used for initializing thestring
object. The string is expected to be null-terminated and encoded in a wide character format.
Details:
**Conversion to
std::wstring
** :- The constructor converts the provided wide C-string into a
std::wstring
. This step is crucial to manage the wide string properly within the C++ standard library, which offers enhanced functionalities and safety compared to raw wide C-style strings.
- The constructor converts the provided wide C-string into a
Delegation :
After converting the wide C-string to a
std::wstring
, the constructor delegates the initialization to another constructor that acceptsstd::wstring
as an argument.This delegation ensures that all necessary encryption and encoding steps are handled consistently, regardless of whether the input was a
const wchar_t*
orstd::wstring
.
Example Usage:
int
In this example, secure_wstring
is initialized with the contents of the wide C-string wide_text
. The data is first converted to a std::wstring
, and then securely stored within the string
object.
Security Considerations:
The constructor ensures that the transition from a raw wide C-string to a secure
string
object is handled safely and efficiently, with minimal risk of exposing sensitive data.By delegating the actual storage and encryption process to the
std::wstring
constructor, this approach ensures that all security measures implemented in thestd::wstring
constructor are applied consistently, regardless of the input format.
string (const char32_t *src) noexcept
Constructs a string
object from a UTF-32 C-style string.
Definition
libantispy::string::string
Detailed Description
This constructor initializes a string
object using a UTF-32 C-style string ( const char32_t*
). It provides a convenient interface to create a secure string object directly from a UTF-32 encoded C-style string. The constructor converts the input UTF-32 C-string into a std::u32string
and then delegates the initialization process to another constructor that handles std::u32string
objects. This ensures that the UTF-32 string is properly managed and securely stored with all necessary encryption and security measures applied.
Parameters
src
: The source UTF-32 C-style string to be used for initializing thestring
object. The string is expected to be null-terminated and encoded in UTF-32 format.
Details:
**Conversion to
std::u32string
** :- The constructor converts the provided UTF-32 C-string into a
std::u32string
, which is the standard C++ container for handling UTF-32 encoded strings. This conversion is essential for leveraging the safety and features provided by the C++ standard library.
- The constructor converts the provided UTF-32 C-string into a
Delegation :
Once the UTF-32 C-string is converted into a
std::u32string
, the constructor delegates the actual initialization process to thestd::u32string
constructor of thestring
class.This ensures that the string data is encrypted and stored securely, following the same procedures as if it were initialized from a
std::u32string
.
Example Usage:
int
In this example, secure_utf32string
is initialized with the contents of the UTF-32 C-string utf32_text
. The data is first converted to a std::u32string
, and then securely stored within the string
object.
Security Considerations:
The constructor ensures that the UTF-32 C-string is securely transitioned to a
string
object, minimizing the risk of exposing sensitive data during the conversion process.By delegating to the
std::u32string
constructor, the security features and encryption mechanisms implemented there are consistently applied, regardless of the input string format.
string (const ::std::string &src) noexcept
Constructs a string
object from a std::string
.
Definition
libantispy::string::string
Detailed Description
This constructor initializes a string
object using a standard std::string
. It provides a convenient interface to create a secure string object from a UTF-8 encoded std::string
. The constructor converts the input UTF-8 encoded std::string
into a std::u32string
(UTF-32) and then delegates the initialization process to the constructor that handles std::u32string
objects. This ensures that the string data is securely managed and stored with all necessary encryption and security measures applied.
Parameters
src
: The sourcestd::string
to be used for initializing thestring
object. This string is expected to be encoded in UTF-8 format.
Details:
Conversion to UTF-32 :
The constructor converts the provided UTF-8 encoded
std::string
into astd::u32string
using thedetail::char32_converter
. This conversion is necessary because thestring
class is designed to operate with UTF-32 encoded data internally.The conversion from UTF-8 to UTF-32 ensures that the string is represented in a format that allows for more consistent handling of characters, especially when dealing with complex scripts or characters that require more than one byte in UTF-8.
The
WIN_SUPRESS_4996
macro is used to suppress specific warnings related to deprecated functions, ensuring that the code compiles without warnings in certain environments.
Delegation :
After converting the
std::string
to astd::u32string
, the constructor delegates the actual initialization process to the constructor that handlesstd::u32string
objects.This delegation ensures that the string data is encrypted and stored securely, following the same procedures as if it were initialized directly from a
std::u32string
.
Example Usage:
int
In this example, secure_string
is initialized with the contents of the UTF-8 encoded std::string
utf8_text
. The data is first converted to a std::u32string
and then securely stored within the string
object.
Security Considerations:
The constructor ensures that the UTF-8 encoded
std::string
is securely transitioned to astring
object, minimizing the risk of exposing sensitive data during the conversion process.By delegating to the
std::u32string
constructor, the security features and encryption mechanisms implemented there are consistently applied, regardless of the input string format.
string (const ::std::wstring &src) noexcept
Constructs a string
object from a std::wstring
.
Definition
libantispy::string::string
Detailed Description
This constructor initializes a string
object using a wide-character std::wstring
. It provides a way to securely store and manage wide-character strings by converting them into a std::u32string
(UTF-32) format and then delegating the initialization process to the constructor that handles std::u32string
objects. The conversion from std::wstring
to std::u32string
involves two steps: first converting the wide-character string to a UTF-8 encoded string, and then converting that UTF-8 string into UTF-32. This ensures that the string is securely managed and stored with the necessary encryption and security measures applied.
Parameters
src
: The sourcestd::wstring
to be used for initializing thestring
object. This string is expected to be encoded in wide-character format, typically UTF-16 or UTF-32 depending on the platform.
Details:
Conversion Process :
The constructor first converts the provided
std::wstring
to a UTF-8 encodedstd::string
using thedetail::wchar_converter
. This conversion is necessary because the wide-character string (std::wstring
) needs to be represented in a more universally compatible format (UTF-8) before being further converted.After converting the
std::wstring
to astd::string
in UTF-8 format, the constructor then converts this UTF-8 encoded string into astd::u32string
usingdetail::char32_converter
.The resulting
std::u32string
represents the original wide-character string in a UTF-32 format, which is the internal representation used by thestring
class for secure storage and management.The
WIN_SUPRESS_4996
macro is used to suppress specific warnings related to deprecated functions, ensuring compatibility across different environments.
Delegation :
After converting the
std::wstring
to astd::u32string
, the constructor delegates the actual initialization process to the constructor that handlesstd::u32string
objects.This delegation ensures that the string data is encrypted and stored securely, applying the same security measures as if it were initialized directly from a
std::u32string
.
Example Usage:
int
In this example, secure_string
is initialized with the contents of the wide-character std::wstring
wide_text
. The data is first converted to a std::u32string
and then securely stored within the string
object.
Security Considerations:
The constructor ensures that the wide-character
std::wstring
is securely transitioned to astring
object, minimizing the risk of exposing sensitive data during the conversion process.By delegating to the
std::u32string
constructor, the security features and encryption mechanisms implemented there are consistently applied, regardless of the input string format.
string (const ::std::u32string &src) noexcept
Constructs a string
object from a std::u32string
.
Definition
libantispy::string::string
Detailed Description
This constructor initializes a string
object using a std::u32string
, which is a UTF-32 encoded string. The constructor encrypts the string's content using a randomly generated key and stores the encrypted data securely.
Parameters
src
: The sourcestd::u32string
that contains the UTF-32 encoded characters to be encrypted and stored in thestring
object.
Details:
Encryption Key Generation :
- The constructor generates a random encryption key using
detail::key<size_t>::make_non_zero_random()
. This function ensures that the generated key is non-zero, enhancing security by avoiding trivial encryption (e.g., XOR with zero would have no effect).
- The constructor generates a random encryption key using
Hash Calculation :
- The constructor computes a hash value for the string using the
fnv1a
hashing algorithm provided byantispy SDK
. The hash is calculated over the entirestd::u32string
, including the null terminator. This hash is stored in thehash_
member and can be used later for integrity checks or comparisons.
- The constructor computes a hash value for the string using the
String Encryption :
The actual encryption of the
std::u32string
content is performed by thedetail::string::encode
function. This function encrypts each character of the string using the generated encryption key and the index of the character.The
WIN_SUPRESS_4244
macro is used to suppress specific compiler warnings related to potential data loss during the encryption process, particularly in type conversions.
Storage :
Example Usage:
int
In this example, secure_string
is initialized with the contents of the UTF-32 encoded std::u32string
utf32_text
. The data is encrypted and securely stored within the string
object.
Security Considerations:
The constructor ensures that the UTF-32 encoded string is securely encrypted before being stored, protecting the data from unauthorized access.
The random encryption key and computed hash value provide additional security features, such as preventing predictable encryption patterns and allowing integrity checks.
string (const string &src)=default
Default copy constructor for the string
class.
Definition
libantispy::string::string
Detailed Description
This constructor creates a new string
object by copying the contents of an existing string
object. It performs a shallow copy, meaning that all members of the source string
object are copied into the new object, including the encrypted data, the encryption key, and the hash value.
Parameters
src
: The sourcestring
object to copy from. The contents ofsrc
, including its encryption key and hash, will be duplicated in the newly constructedstring
object.
Details:
Shallow Copy :
The default copy constructor performs a shallow copy of the
src
object. This means that thekey_
andhash_
members, as well as the encrypted data stored in thestd::vector<char32_t>
base class, are copied directly fromsrc
to the newstring
object.The copy constructor is marked as
default
, indicating that the compiler-generated copy constructor is used. This is sufficient for thestring
class because its members (likestd::vector<char32_t>
) manage their own memory.
Use Case :
The copy constructor is typically invoked when a
string
object is passed by value, returned by value, or explicitly copied using syntax likestring new_str = existing_str;
.It ensures that the new
string
object is a distinct instance with its own copy of the data, allowing it to be modified independently of the original object.
Security Considerations :
The encryption key and hash are copied along with the encrypted data, ensuring that the new
string
object can correctly encrypt and decrypt its contents without relying on the originalstring
object.The copy operation preserves the integrity and security of the data, as the copied
string
object retains the same encryption and hashing mechanisms as the original.
Example Usage:
int
In this example, copied_str
is created as a copy of original_str
. Both string
objects will have their own copies of the encrypted data, encryption key, and hash, allowing them to function independently.
Performance:
The copy constructor is generally efficient, but the performance depends on the size of the encrypted data being copied.
Since
std::vector<char32_t>
is used to store the encrypted data, the copy operation involves duplicating the vector's contents, which may include allocating new memory and copying the data.
string (const string &&src) noexcept
Move constructor for the string
class.
Definition
libantispy::string::string
Detailed Description
This constructor initializes a new string
object by transferring the resources from an existing string
object. The move constructor efficiently transfers ownership of the encrypted data, encryption key, and hash value from the source string
object to the newly created one, leaving the source object in a valid but unspecified state.
Parameters
src
: The sourcestring
object to move from. After the move operation,src
is left in a valid but unspecified state, typically empty or reset to default values.
Details:
Move Semantics :
The move constructor is designed to take over the resources of
src
without performing a deep copy. This involves transferring the encrypted data stored in thestd::vector<char32_t>
base class, as well as the encryption key (key_
) and hash (hash_
).The constructor swaps the current
string
object's internal data with an emptystd::vector<char32_t>
, effectively clearing the new object's internal storage before transferring the data fromsrc
.The line
static_cast<::std::vector<char32_t>>(src).swap(*this);
efficiently transfers the vector's contents fromsrc
to the new object by swapping their internal data, a method that is both fast and safe.
Noexcept Guarantee :
- The constructor is marked
noexcept
, indicating that it guarantees not to throw exceptions during the move operation. This is crucial for ensuring that thestring
class can be used in performance-critical applications or in containers likestd::vector
, which require move operations to be noexcept.
- The constructor is marked
State of the Source Object :
After the move operation, the source
string
object (src
) is left in a valid but unspecified state. This usually means thatsrc
no longer owns the resources it previously held, and it may be reset to a default or empty state.The encryption key (
key_
) and hash (hash_
) are copied fromsrc
, but the data stored in thestd::vector<char32_t>
is moved, meaning thesrc
object will have an empty vector after the move.
Performance :
- The move constructor is highly efficient because it avoids the overhead of copying large amounts of data. Instead of duplicating the contents of the
std::vector<char32_t>
, it simply swaps pointers between thesrc
object and the newstring
object, which is a constant-time operation.
- The move constructor is highly efficient because it avoids the overhead of copying large amounts of data. Instead of duplicating the contents of the
Example Usage:
int
In this example, moved_str
takes ownership of the resources previously held by original_str
. After the move, original_str
should not be used except to assign a new value or to destroy it.
Security Considerations:
- The encryption key and hash are transferred along with the encrypted data, ensuring that the new
string
object can correctly handle decryption. The integrity and confidentiality of the data are maintained throughout the move operation.
string & operator= (const string &other)
Copy assignment operator for the string
class.
Definition
string &
Detailed Description
This operator allows for the assignment of one string
object to another, effectively copying the content and internal state from the other
string into the current object. This is essential when you need to duplicate the state of one string object into another.
Parameters
other
: The sourcestring
object from which to copy the data and internal state.
Returns
A reference to the current string
object ( *this
), now containing the copied data and state.
Details:
Self-Assignment Check :
- The first action taken by the operator is to check if the current object (
this
) is the same as theother
object. This is done using a pointer comparison (this == &other
). If they are the same, the function immediately returns*this
without performing any further operations. This avoids unnecessary work and potential issues that could arise from attempting to copy an object to itself.
- The first action taken by the operator is to check if the current object (
Copying Data :
- If the objects are different, the operator creates a temporary
std::vector<char32_t>
from the data range of theother
string (other.begin(), other.end()
). This temporary vector is then swapped with the current object's internal vector using theswap
function. This ensures that the current object takes on the content of theother
string, while the previous content of the current object is released.
- If the objects are different, the operator creates a temporary
Copying the Encryption Key :
- The
key_
member, which holds the encryption key used for the data in the string, is copied from theother
string to the current object. This ensures that the current object uses the same encryption key as theother
string, maintaining consistency in how the string data is stored and accessed.
- The
Efficiency :
- The use of
swap
for the internal vector means that the operation is efficient and exception-safe. Swapping vectors is typically a constant-time operation, as it only involves exchanging pointers to the underlying data, rather than copying the data itself.
- The use of
Usage:
This operator is used when an existing
string
object needs to be replaced with the contents of anotherstring
object, effectively making a deep copy of theother
string.It is particularly useful in scenarios where the contents of a string need to be duplicated or when managing multiple instances of a string that should contain the same data.
Example:
int
In this example, the contents of str2
are copied into str1
, replacing any data that was previously stored in str1
. After the assignment, str1
contains the same data as str2
, and the encryption key used by str2
is also copied to str1
.
string & operator= (string &&other) noexcept
Move assignment operator for the string
class.
Definition
string &
Detailed Description
This operator allows for the efficient transfer of resources from one string
object to another, utilizing move semantics. It effectively transfers the content, encryption key, and internal state from the other
string into the current object, leaving the other
string in a valid but unspecified state.
Parameters
other
: The sourcestring
object to move from. After the move,other
is left in a valid but unspecified state.
Returns
A reference to the current string
object ( *this
), now containing the moved data and state.
Details:
Self-Assignment Check :
- The first action taken by the operator is to check if the current object (
this
) is the same as theother
object. This is done using a pointer comparison (this == &other
). If they are the same, the function immediately returns*this
without performing any further operations. This avoids unnecessary work and potential issues that could arise from attempting to move an object to itself.
- The first action taken by the operator is to check if the current object (
Clearing Current Content :
- Before performing the move, the current contents of the object are cleared by swapping the internal vector with an empty vector. This ensures that the current object's resources are properly released, and the internal state is reset.
Transferring Content :
- The operator then swaps the internal vector of the
other
string with the current object's vector usingother.swap(*this)
. This operation transfers ownership of theother
string's resources to the current object, making the current object now hold the data that was originally in theother
string.
- The operator then swaps the internal vector of the
Copying the Encryption Key :
- The encryption key (
key_
) is transferred from theother
string to the current object. This ensures that the current object uses the same encryption key as theother
string, maintaining consistency in how the string data is stored and accessed.
- The encryption key (
Efficiency :
- The use of move semantics and
swap
makes this operation efficient, as it avoids unnecessary copies of data and instead transfers ownership of resources. This is particularly important for large strings or when performance is critical.
- The use of move semantics and
Usage:
- This operator is used when an existing
string
object needs to take ownership of the resources of anotherstring
object that is about to be destroyed or is no longer needed. It is particularly useful in scenarios where performance is critical, and you want to avoid the overhead of copying data.
Example:
int
In this example, the contents of str1
are moved into str2
, leaving str1
in a valid but unspecified state. After the move, str2
contains the data that was originally in str1
, and the encryption key used by str1
is also transferred to str2
.
char32_t operator[] (const size_t index) const noexcept
Index operator to access elements of the encrypted string.
Definition
char32_t
Detailed Description
This operator allows for safe and secure access to the individual elements (characters) of the encrypted string stored in the string
object. It decrypts the requested character at the given index, ensuring that the data remains protected while allowing for selective access to its contents.
Parameters
index
: The position of the character within the string to be accessed. It should be a valid index within the range of the string, otherwise, undefined behavior may occur.
Returns
The decrypted char32_t
character located at the specified index
within the string.
Details:
Decryption Process :
The operator first retrieves the encrypted character from the underlying vector of the
string
object using thestd::vector<char32_t>::operator[]
function. This character is still in its encrypted form.The retrieved character is then decrypted using the
encryptor<char32_t>::decrypt
function, which applies the stored encryption key (key_
) and the index (index
) to produce the original, decrypted character.
Encryption Key :
- The decryption relies on the encryption key (
key_
) that was used to encrypt the string initially. This key is crucial for correctly reversing the encryption process and obtaining the original data.
- The decryption relies on the encryption key (
Indexing :
The
index
parameter specifies the position of the character within the string that you wish to access. The indexing is zero-based, meaning thatindex = 0
corresponds to the first character of the string.Care must be taken to ensure that the provided
index
is within the valid range of the string. Accessing an index outside this range could lead to undefined behavior.
Noexcept :
- This function is marked
noexcept
, indicating that it guarantees not to throw exceptions. This is particularly important for performance-critical applications where exception handling can introduce overhead.
- This function is marked
Usage :
- The
operator[]
is used when there is a need to access or process individual characters within an encrypted string. The returned character is decrypted on-the-fly, providing both security and convenience.
- The
Performance :
- The decryption process introduces some computational overhead compared to accessing an unencrypted character, but this trade-off is necessary to maintain data security.
Example:
int
In this example, the first character of the encrypted string encrypted_str
is accessed and decrypted. The operator allows for convenient access to specific characters within the encrypted string while ensuring that the data remains secure.
size_t size () const
Retrieves the size of the encrypted string.
Definition
size_t
Detailed Description
This function returns the number of characters in the encrypted string, excluding the null terminator. It effectively provides the length of the string as stored in the string
object.
Returns
The size of the string as a size_t
value, representing the number of characters in the string excluding the null terminator.
Details:
Logic :
The function calls the
size()
method of the base classstd::vector<char32_t>
, which returns the total number of elements in the vector, including the null terminator.To get the actual size of the string (i.e., the number of meaningful characters), the function subtracts 1 from this value, thereby excluding the null terminator from the count.
This adjusted size is then returned as the length of the string.
Performance :
- The
size()
function operates in constant time (O(1)) as it merely retrieves and adjusts a stored size value from the underlying vector.
- The
Usage :
This function is useful when you need to determine the length of the string, such as when iterating over the characters, performing size-related checks, or allocating resources based on the string's length.
It is especially relevant in contexts where the precise length of the string, excluding the null terminator, is needed for further processing or validation.
Example:
int
In this example, size()
returns the length of the string "Hello, World!", which is 13 characters long. This value excludes the null terminator that is automatically added when the string is stored.
bool empty () const noexcept
Checks whether the encrypted string is empty.
Definition
bool
Detailed Description
This function determines if the string managed by the string
class is empty, meaning it contains no characters. An empty string is defined as one that has a size of 0, excluding the null terminator.
Returns
true
if the string is empty, false
otherwise.
Details:
Logic :
The function calls the
size()
method to retrieve the number of characters in the string, excluding the null terminator.It then compares this size to 0. If the size is 0, it indicates that the string is empty, and the function returns
true
.If the size is greater than 0, the function returns
false
, indicating that the string contains one or more characters.
Performance :
The
empty()
function operates in constant time (O(1)) as it simply checks the size of the string, which is an efficient operation.The function is marked as
noexcept
, guaranteeing that it does not throw exceptions, making it safe to use in all contexts, including those that require exception safety.
Usage :
This function is particularly useful when you need to verify whether a string has any content before performing operations that assume the string is not empty, such as accessing elements or processing the string.
It can be used in conditions, loops, or any logic that depends on whether the string contains characters.
Example:
int
In this example, myString.empty()
returns true
because the string is initialized as empty. The condition can then trigger specific logic to handle the empty state.
void append (const string &cs)
Appends another encrypted string to the current string.
Definition
void
Detailed Description
This function appends the contents of another string
object to the current string
object, effectively concatenating the two encrypted strings. The result is a new string
object that contains the combined content of both strings.
Parameters
cs
: Thestring
object to append to the current string. This string will be concatenated to the end of the current string.
Details:
Process :
The function begins by converting the current
string
object and the string to be appended (cs
) into their decryptedstd::u32string
representations.It then performs a standard string append operation on these
std::u32string
objects, concatenating the contents ofcs
to the end of the current string.The resulting
std::u32string
is then used to reconstruct the currentstring
object. This is done in place, using the placementnew
operator to reinitialize the current object with the newly concatenated string.This ensures that the
string
object now holds the combined content of both the original string and the appended string, all within an encrypted format.
Performance :
The function involves converting the encrypted data to a
std::u32string
, appending the strings, and then re-encrypting the result. While this operation ensures that the string remains secure, it may introduce some overhead due to the multiple conversions and re-encryption steps.The use of placement
new
to reconstruct the object ensures that the operation is performed in place, avoiding the overhead of creating a new object and then assigning it.
Usage :
This function is particularly useful in scenarios where multiple encrypted strings need to be combined into a single string. It maintains the security of the string content while allowing for dynamic concatenation.
It can be used in any context where string concatenation is needed, such as building up strings incrementally or combining results from different encrypted sources.
Example:
int
In this example, str2
is appended to str1
, resulting in the concatenated string "Hello, world!". The final string is stored in str1
, which is then converted back to a std::u32string
for further use.
size_t get_hash () const
Retrieves the hash value of the encrypted string.
Definition
size_t
Detailed Description
This function returns the hash value associated with the current string
object. The hash is a unique identifier for the string's content, computed when the string is initialized. It is used primarily for quick comparisons and integrity checks without needing to compare the entire encrypted string.
Returns
The hash value of the string as a size_t
.
Details:
Hash Purpose :
The hash value is a compact representation of the string's content. It is particularly useful in scenarios where you need to compare two strings quickly without decrypting and comparing the entire string content.
This hash is computed during the construction of the
string
object, ensuring that every string has a corresponding hash that can be used for various operations like equality checks, sorting, or indexing.
Usage :
The hash value can be used in hashed data structures such as hash maps or hash sets, where the string serves as a key. It enables efficient retrieval and comparison of string-based keys.
It can also be used for verifying the integrity of the string, ensuring that it has not been altered since its hash was computed.
The function is marked as
ANTISPY_INLINE
, which suggests that the compiler should attempt to inline the function, reducing function call overhead.
Performance :
The
get_hash
function is a constant-time operation, O(1), since it simply returns the precomputed hash value stored in thehash_
member variable. This makes it highly efficient and suitable for performance-critical applications.The function is also marked as
const
, ensuring that it does not modify the state of the object, andnoexcept
, indicating that it guarantees not to throw any exceptions, which is essential for reliability in secure environments.
Example:
int
In this example, the get_hash
function is used to retrieve the hash value of the string "Example String". This hash can be used for quick comparisons or as a key in a hash-based data structure.
~string () noexcept
Destructor for the string
class.
Definition
Detailed Description
This destructor is responsible for securely cleaning up and deallocating the resources associated with the string
object. It ensures that all sensitive data is securely erased before the object is destroyed, preventing any potential data leakage or unauthorized access.
Functionality:
Secure Erasure of Encryption Key and Hash :
- The
key_
andhash_
member variables, which are used for encrypting and identifying the string content, are securely erased by XORing their values with themselves. This operation effectively sets their values to zero, ensuring that these sensitive pieces of information are not left in memory.
- The
Clearing the Encrypted String Data :
The
memset
function is used to clear the memory occupied by the encrypted string data. This operation sets all bytes in the data buffer to zero, ensuring that the encrypted content cannot be recovered from memory after the object is destroyed.The range cleared by
memset
spans from the beginning of the data buffer (data()
) to the end (end()
), ensuring complete erasure of the string's content.
Memory Deallocation :
- The destructor uses
std::vector<char32_t>().swap(*this)
to deallocate the memory associated with the vector holding the string's characters. Swapping the vector with an empty one ensures that the allocated memory is released back to the system, preventing memory leaks.
- The destructor uses
Exception Safety:
- The destructor is marked as
noexcept
, indicating that it guarantees not to throw any exceptions during its execution. This is critical in ensuring that the cleanup process is reliable and cannot be interrupted by exceptions, which is particularly important in secure environments where data must be thoroughly erased.
Example:
int
In this example, the secure_str
object is automatically destroyed when it goes out of scope. The destructor securely erases the key, hash, and encrypted string data, ensuring that no sensitive information remains in memory after the object is destroyed.
Private Properties
size_t key_
Encryption key used for securing the string's content.
Definition
size_t
Detailed Description
The key_
member variable stores the encryption key used by the string
class to encrypt and decrypt its content. This key is an essential part of the security mechanism, ensuring that the data stored within the string
is securely obfuscated and protected from unauthorized access.
Details:
Type :
size_t
Purpose :
The
key_
is used in conjunction with encryption and decryption algorithms to transform the string's data into a secure format when stored, and to restore it to its original form when accessed.This key is generated when the
string
object is constructed, ensuring that each instance of thestring
class has a unique key.
Initialization :
In the constructor that accepts a
std::u32string
or any other string type,key_
is initialized with a random non-zero value generated by thedetail::key<size_t>::make_non_zero_random()
function. This randomization enhances security by ensuring that the key is not predictable.When a
const_string
is used to initialize astring
object,key_
is copied from theconst_string
to maintain consistency between the encrypted and decrypted forms.
Usage :
The
key_
is applied in theencryptor<char32_t>::encrypt
andencryptor<char32_t>::decrypt
functions to encrypt and decrypt each character in the string.It plays a crucial role in the security of the
string
class, as the same key is required to both encrypt and decrypt the data.The key is also XORed with itself during the destruction of the
string
object to securely erase its value and prevent it from being accessible after the object is destroyed.
Security Considerations :
The
key_
is never directly exposed or accessible outside thestring
class. It is always used in conjunction with the encryption and decryption routines, ensuring that it remains protected.By securely erasing the
key_
in the destructor, the class ensures that no sensitive information remains in memory once thestring
object is destroyed.
Example:
int
In the example above, when the encrypted_str
object is created, the key_
is generated and used to encrypt the string "Sensitive Information". This key is crucial for later decrypting the string when it is accessed.
size_t hash_
Hash value representing the content of the string.
Definition
size_t
Detailed Description
The hash_
member variable stores a hash value that uniquely represents the content of the string
. This hash is used for quick comparisons, ensuring the integrity of the data, and uniquely identifying the string's content.
Details:
Type :
size_t
Purpose :
The
hash_
provides a way to quickly and efficiently compare twostring
objects without needing to decrypt and compare their entire contents. This is particularly useful in scenarios where multiple encrypted strings need to be compared for equality or when performing lookups in hash-based data structures.The hash is also used for verifying the integrity of the string, ensuring that the content has not been altered or corrupted.
Initialization :
The
hash_
is typically calculated at the time of thestring
object's construction. It is computed based on the original, unencrypted content of the string using a hashing algorithm such as FNV-1a.When a
const_string
is used to initialize astring
object, thehash_
is directly copied from theconst_string
to ensure consistency between the two.
Usage :
The
hash_
is used in various comparison operators (e.g.,operator==
,operator!=
,operator<
, etc.) to determine whether two strings are equivalent or to establish an order between them.It can be used to verify that the string content has not been modified by comparing the stored hash with a freshly computed hash of the current string content.
The hash value is also helpful in optimizing search operations, allowing the
string
objects to be used as keys in hash-based containers likestd::unordered_map
.
Security Considerations :
The
hash_
value is stored alongside the encrypted data but does not directly expose the content of the string. It serves as a fingerprint for the data, which is useful for efficient operations without compromising security.During the destruction of the
string
object, thehash_
is securely erased by XORing it with itself, ensuring that the hash value cannot be recovered after the object is destroyed.
Example:
int
In the example above, the get_hash() function retrieves the hash_
of each string, which can then be compared to check if the two strings are likely identical, without needing to decrypt and compare the full contents.
Friends
bool operator== (const string &lhs, const string &rhs) noexcept
Equality operator for comparing two string
objects.
Definition
bool
Detailed Description
This operator compares two string
objects to determine if they are equal. The comparison is based on the hash values of the strings, which were computed during the creation or modification of the string
objects. If the hash values of the two strings match, the operator assumes that the strings are equal, and returns true
. Otherwise, it returns false
.
Parameters
lhs
: The left-hand sidestring
object in the comparison.rhs
: The right-hand sidestring
object in the comparison.
Returns
true
if the hash values of the two string
objects are equal, indicating that the strings are identical in content; false
otherwise.
Details:
Hash-Based Comparison :
The comparison is performed by directly comparing the
hash_
members of thelhs
andrhs
string
objects. Thehash_
value is a size_t representing a hashed version of the string's content.Hashing provides a quick and efficient way to compare strings without needing to compare each character. Since a hash value uniquely represents the content of a string, if two strings have the same hash value, it is highly likely that they are identical.
Efficiency :
This method is efficient because comparing two
size_t
hash values is much faster than comparing the entire contents of two strings, especially when the strings are large.It leverages the precomputed hash values, avoiding the need to repeatedly compute the hash during comparisons.
Usage :
The
operator==
is typically used in conditions where you need to check if two encrypted strings are identical.It can be used in control flow statements, data structure operations (like searching or sorting), and anywhere string equality needs to be determined.
Noexcept :
- The operator is marked
noexcept
, indicating that it guarantees not to throw any exceptions. This is important for performance-critical code and ensures that the comparison is safe to use in exception-sensitive contexts.
- The operator is marked
Example:
int
In this example, the operator==
checks if str1
and str2
are equal by comparing their hash values. If the hash values are identical, the operator returns true
, confirming that the two strings are equal in content.
bool operator!= (const string &lhs, const string &rhs) noexcept
Inequality operator for comparing two string
objects.
Definition
bool
Detailed Description
This operator checks whether two string
objects are not equal. It leverages the equality operator ( operator==
) to determine inequality. If the two string
objects are not equal, the operator returns true
; otherwise, it returns false
.
Parameters
lhs
: The left-hand sidestring
object in the comparison.rhs
: The right-hand sidestring
object in the comparison.
Returns
true
if the lhs
and rhs
string
objects are not equal; false
if they are equal.
Details:
Logic :
The function simply negates the result of the equality comparison (
!(lhs == rhs)
), which means it will returntrue
if the strings are not equal andfalse
if they are.By relying on the
operator==
, theoperator!=
benefits from the same efficiency and correctness as the equality operator.
Efficiency :
The operator is efficient because it only involves a single call to the equality operator, which itself is optimized by comparing hash values rather than the full string content.
This makes it a fast way to check for inequality, especially when dealing with large strings.
Usage :
The
operator!=
is typically used in control flow statements where you need to execute different code paths based on whether two strings are not the same.It is also useful in loops and conditionals, where operations should be performed only if strings differ.
Noexcept :
- The operator is marked
noexcept
, indicating that it will not throw any exceptions. This ensures that the operator is safe to use in any context, including those where exception safety is critical.
- The operator is marked
Example:
int
In this example, the operator!=
checks if str1
and str2
are not equal. Since the strings contain different content, the operator returns true
, indicating that the strings are not the same.
bool operator< (const string &lhs, const string &rhs) noexcept
Less-than operator for comparing two string
objects.
Definition
bool
Detailed Description
This operator checks if one string
object is lexicographically less than another string
object. It first checks if the two strings are not equal using the operator!=
, and if they are not equal, it compares their decrypted contents by converting them to std::u32string
objects.
Parameters
lhs
: The left-hand sidestring
object in the comparison.rhs
: The right-hand sidestring
object in the comparison.
Returns
true
if the lhs
string
is less than the rhs
string
; false
otherwise.
Details:
Logic :
The function first checks if the
lhs
andrhs
strings are not equal using theoperator!=
.If the strings are not equal, the function converts both
lhs
andrhs
tostd::u32string
objects, which represent their decrypted contents.It then performs a lexicographical comparison on these decrypted strings using the
<
operator forstd::u32string
, returningtrue
if thelhs
string is lexicographically less than therhs
string, andfalse
otherwise.
Efficiency :
The initial inequality check using the
operator!=
is efficient because it typically involves comparing precomputed hash values of the strings.The subsequent comparison of the decrypted
std::u32string
objects, while more computationally intensive, is necessary for determining the lexicographical order of the strings. This step involves decrypting the contents of both strings and comparing them character by character.
Usage :
The
operator<
is commonly used in sorting algorithms, ordered containers (e.g.,std::set
,std::map
), and other contexts where ordering of strings is required.It allows for a natural lexicographical ordering of encrypted
string
objects, making it useful for implementing data structures and algorithms that depend on order.
Noexcept :
- The operator is marked
noexcept
, indicating that it will not throw any exceptions. This makes it safe to use in contexts where exception safety is critical.
- The operator is marked
Example:
int
In this example, the operator<
checks if str1
is lexicographically less than str2
. Since "Apple" is indeed less than "Banana", the operator returns true
.
bool operator<= (const string &lhs, const string &rhs) noexcept
Less-than-or-equal-to operator for comparing two string
objects.
Definition
bool
Detailed Description
This operator checks if one string
object is lexicographically less than or equal to another string
object. It first checks if the two strings are equal using the operator==
. If they are not equal, it compares their decrypted contents by converting them to std::u32string
objects and checking if the left-hand side ( lhs
) is lexicographically less than the right-hand side ( rhs
).
Parameters
lhs
: The left-hand sidestring
object in the comparison.rhs
: The right-hand sidestring
object in the comparison.
Returns
true
if the lhs
string
is less than or equal to the rhs
string
; false
otherwise.
Details:
Logic :
The function first checks if the
lhs
andrhs
strings are equal using theoperator==
.If the strings are equal, it returns
true
because a string is always equal to itself.If the strings are not equal, it converts both
lhs
andrhs
tostd::u32string
objects, which represent their decrypted contents.It then performs a lexicographical comparison on these decrypted strings using the
<
operator forstd::u32string
, returningtrue
if thelhs
string is lexicographically less than therhs
string, andfalse
otherwise.
Efficiency :
The initial equality check using the
operator==
is efficient because it typically involves comparing precomputed hash values of the strings.The subsequent comparison of the decrypted
std::u32string
objects, while more computationally intensive, is necessary for determining the lexicographical order of the strings. This step involves decrypting the contents of both strings and comparing them character by character.
Usage :
The
operator<=
is commonly used in sorting algorithms, ordered containers (e.g.,std::set
,std::map
), and other contexts where ordering of strings is required.It allows for a natural lexicographical ordering of encrypted
string
objects, making it useful for implementing data structures and algorithms that depend on order.
Noexcept :
- The operator is marked
noexcept
, indicating that it will not throw any exceptions. This makes it safe to use in contexts where exception safety is critical.
- The operator is marked
Example:
int
In this example, the operator<=
checks if str1
is lexicographically less than or equal to str2
. Since "Apple" is indeed less than "Banana", the operator returns true
.
bool operator> (const string &lhs, const string &rhs) noexcept
Greater-than operator for comparing two string
objects.
Definition
bool
Detailed Description
This operator checks if one string
object is lexicographically greater than another string
object. It first verifies that the two strings are not equal using the operator!=
. If they are not equal, it compares their decrypted contents by converting them to std::u32string
objects and checking if the left-hand side ( lhs
) is lexicographically greater than the right-hand side ( rhs
).
Parameters
lhs
: The left-hand sidestring
object in the comparison.rhs
: The right-hand sidestring
object in the comparison.
Returns
true
if the lhs
string
is lexicographically greater than the rhs
string
; false
otherwise.
Details:
Logic :
The function begins by checking if the
lhs
andrhs
strings are not equal using theoperator!=
.If the strings are equal, the operator immediately returns
false
since one string cannot be greater than itself.If the strings are not equal, it converts both
lhs
andrhs
tostd::u32string
objects, which represent their decrypted contents.It then performs a lexicographical comparison on these decrypted strings using the
>
operator forstd::u32string
, returningtrue
if thelhs
string is lexicographically greater than therhs
string, andfalse
otherwise.
Efficiency :
The initial inequality check using the
operator!=
is efficient because it typically involves comparing precomputed hash values of the strings.The subsequent comparison of the decrypted
std::u32string
objects is more computationally intensive because it involves decrypting the contents of both strings and comparing them character by character.
Usage :
The
operator>
is commonly used in sorting algorithms, ordered containers (e.g.,std::set
,std::map
), and other contexts where ordering of strings is required.It allows for a natural lexicographical ordering of encrypted
string
objects, making it useful for implementing data structures and algorithms that depend on order.
Noexcept :
- The operator is marked
noexcept
, indicating that it will not throw any exceptions. This ensures safe use in contexts where exception safety is important.
- The operator is marked
Example:
int
In this example, the operator>
checks if str1
is lexicographically greater than str2
. Since "Banana" is indeed greater than "Apple", the operator returns true
.
bool operator>= (const string &lhs, const string &rhs) noexcept
Greater-than-or-equal-to operator for comparing two string
objects.
Definition
bool
Detailed Description
This operator checks if one string
object is lexicographically greater than or equal to another string
object. It first checks if the two strings are equal using the operator==
. If they are equal, the operator immediately returns true
. If they are not equal, it compares their decrypted contents by converting them to std::u32string
objects and checks if the left-hand side ( lhs
) is lexicographically greater than the right-hand side ( rhs
).
Parameters
lhs
: The left-hand sidestring
object in the comparison.rhs
: The right-hand sidestring
object in the comparison.
Returns
true
if the lhs
string
is lexicographically greater than or equal to the rhs
string
; false
otherwise.
Details:
Logic :
The function begins by checking if the
lhs
andrhs
strings are equal using theoperator==
.If the strings are equal, the operator returns
true
, since one string is always greater than or equal to itself.If the strings are not equal, it converts both
lhs
andrhs
tostd::u32string
objects, which represent their decrypted contents.The function then performs a lexicographical comparison on these decrypted strings using the
>
operator forstd::u32string
, returningtrue
if thelhs
string is greater than therhs
string, andfalse
otherwise.
Efficiency :
The initial equality check using the
operator==
is efficient because it typically involves comparing precomputed hash values of the strings.If the strings are not equal, the operator proceeds with the more computationally intensive step of decrypting and comparing the strings character by character.
Usage :
The
operator>=
is commonly used in sorting algorithms, ordered containers (e.g.,std::set
,std::map
), and other contexts where ordering of strings is required.It allows for a natural lexicographical ordering of encrypted
string
objects, making it useful for implementing data structures and algorithms that depend on order.
Noexcept :
- The operator is marked
noexcept
, indicating that it will not throw any exceptions. This ensures safe use in contexts where exception safety is important.
- The operator is marked
Example:
int
In this example, the operator>=
checks if str1
is lexicographically greater than or equal to str2
. Since "Banana" is greater than "Apple", the operator returns true
.