![[Image: header4.gif]](https://i.ibb.co/C33BJJJg/header4.gif)
Encryption is crucial for ensuring data privacy and protecting sensitive information from unauthorized access. It plays a vital role in maintaining personal security by safeguarding digital communications and stored data. Robust encryption practices help prevent data breaches and cyberattacks, ensuring that personal and confidential information remains confidential. In an increasingly digital world, the importance of encryption for data privacy and personal security cannot be overstated.
This simple program can take any type of file, encrypt it with AES-256 using Windows, and bcrypt functions. It is a simple CLI program that takes the parameters for your file, password, and lock/unlock commands.
This code share is meant to guide you so you can create your own encryption related programs.
Source Code
Spoiler (Click to View)Code
#ifndef MSAES256FE_SECURE_H
#define MSAES256FE_SECURE_H
#include <windows.h>
#include <bcrypt.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <stdexcept>
#include <iomanip>
#pragma comment(lib, "bcrypt.lib")
#define MSAES256FE_SUCCESS(Status) ((NTSTATUS)(Status) >= 0)
class MSAES256_FileEncryption {
public:
MSAES256_FileEncryption(const wchar_t* file, const std::wstring& key, const std::wstring& operation) :
file(file), key(key), operation(operation) {}
void Execute() {
try {
if (operation == L"lock") {
LockFile();
}
else if (operation == L"unlock") {
UnlockFile();
}
else {
std::wcerr << L"ERR: Invalid operation. Please use 'lock' or 'unlock'." << std::endl;
}
}
catch (const std::exception& ex) {
std::cerr << "ERR: An error occurred: " << ex.what() << std::endl;
}
}
private:
const wchar_t* file;
std::wstring key;
std::wstring operation;
void ShowError(const wchar_t* msg, NTSTATUS status) {
std::wcerr << L"ERR: " << msg << L" (Code: 0x" << std::hex << status << L")" << std::endl;
}
void ValidateStatus(const wchar_t* msg, NTSTATUS status) {
if (!MSAES256FE_SUCCESS(status)) {
ShowError(msg, status);
throw std::runtime_error("ERR: The operation has failed.");
}
}
void AnnounceOperation(const wchar_t* operation) {
std::wcout << L"MSG: Executing the following operation: " << operation << std::endl;
}
void DisplayHex(const void* data, size_t size) {
const uint8_t* byteData = static_cast<const uint8_t*>(data);
for (size_t i = 0; i < size; ++i) {
std::wcout << std::hex << std::setw(2) << std::setfill(L'0') << static_cast<int>(byteData[i]) << L" ";
if ((i + 1) % 16 == 0) {
std::wcout << std::endl;
}
}
if (size % 16 != 0) {
std::wcout << std::endl;
}
}
void GenerateRandomData(std::vector<BYTE>& buffer) {
AnnounceOperation(L"Generating random data.");
BCRYPT_ALG_HANDLE randAlgHandle;
ValidateStatus(L"ERR: The function BCryptOpenAlgorithmProvider has failed.", BCryptOpenAlgorithmProvider(&randAlgHandle, BCRYPT_RNG_ALGORITHM, NULL, 0));
if (!buffer.empty()) {
ValidateStatus(L"ERR: The function BCryptGenRandom has failed.", BCryptGenRandom(randAlgHandle, buffer.data(), static_cast<ULONG>(buffer.size()), 0));
}
BCryptCloseAlgorithmProvider(randAlgHandle, 0);
std::wcout << L"MSG: Random data has been generated:" << std::endl;
DisplayHex(buffer.data(), buffer.size());
}
std::vector<BYTE> CreateKey() {
AnnounceOperation(L"Creating the encryption key.");
BCRYPT_ALG_HANDLE algHandle;
ValidateStatus(L"ERR: The function BCryptOpenAlgorithmProvider has failed.", BCryptOpenAlgorithmProvider(&algHandle, BCRYPT_SHA256_ALGORITHM, NULL, 0));
BCRYPT_HASH_HANDLE hashHandle;
ValidateStatus(L"ERR: The function BCryptCreateHash has failed.", BCryptCreateHash(algHandle, &hashHandle, NULL, 0, NULL, 0, 0));
ValidateStatus(L"ERR: The function BCryptHashData has failed.", BCryptHashData(hashHandle, reinterpret_cast<PUCHAR>(const_cast<wchar_t*>(key.c_str())), static_cast<ULONG>(key.size() * sizeof(wchar_t)), 0));
std::vector<BYTE> keyBuffer(32);
ValidateStatus(L"ERR: The function BCryptFinishHash has failed.", BCryptFinishHash(hashHandle, keyBuffer.data(), static_cast<ULONG>(keyBuffer.size()), 0));
BCryptDestroyHash(hashHandle);
BCryptCloseAlgorithmProvider(algHandle, 0);
std::wcout << L"MSG: The encryption key is:" << std::endl;
DisplayHex(keyBuffer.data(), keyBuffer.size());
return keyBuffer;
}
std::vector<BYTE> ReadFileContent() {
std::ifstream fileStream(file, std::ios::binary);
if (!fileStream.is_open()) {
throw std::runtime_error("ERR: Unable to open the file for reading.");
}
std::vector<BYTE> content((std::istreambuf_iterator<char>(fileStream)), std::istreambuf_iterator<char>());
return content;
}
void WriteFileContent(const std::vector<BYTE>& content, const wchar_t* outputFileName) {
std::ofstream fileStream(outputFileName, std::ios::binary);
if (!fileStream.is_open()) {
throw std::runtime_error("ERR: Unable to open the file for writing.");
}
fileStream.write(reinterpret_cast<const char*>(content.data()), content.size());
}
void LockFile() {
AnnounceOperation(L"Locking the file.");
std::vector<BYTE> fileContent = ReadFileContent();
std::vector<BYTE> key = CreateKey();
std::vector<BYTE> iv(16);
GenerateRandomData(iv);
std::vector<BYTE> originalIV = iv;
BCRYPT_ALG_HANDLE encAlgHandle;
ValidateStatus(L"ERR: The function BCryptOpenAlgorithmProvider has failed.", BCryptOpenAlgorithmProvider(&encAlgHandle, BCRYPT_AES_ALGORITHM, NULL, 0));
ValidateStatus(L"ERR: The function BCryptSetProperty has failed.", BCryptSetProperty(encAlgHandle, BCRYPT_CHAINING_MODE, (PBYTE)BCRYPT_CHAIN_MODE_CBC, sizeof(BCRYPT_CHAIN_MODE_CBC), 0));
BCRYPT_KEY_HANDLE keyHandle;
ValidateStatus(L"ERR: The function BCryptGenerateSymmetricKey has failed.", BCryptGenerateSymmetricKey(encAlgHandle, &keyHandle, NULL, 0, key.data(), static_cast<ULONG>(key.size()), 0));
DWORD cbCipherText = 0;
ValidateStatus(L"ERR: The function BCryptEncrypt (determine size) has failed.", BCryptEncrypt(
keyHandle,
fileContent.data(),
static_cast<ULONG>(fileContent.size()),
NULL,
iv.data(),
static_cast<ULONG>(iv.size()),
NULL,
0,
&cbCipherText,
BCRYPT_BLOCK_PADDING
));
std::vector<BYTE> cipherText(cbCipherText);
ValidateStatus(L"ERR: The function BCryptEncrypt has failed.", BCryptEncrypt(
keyHandle,
fileContent.data(),
static_cast<ULONG>(fileContent.size()),
NULL,
iv.data(),
static_cast<ULONG>(iv.size()),
cipherText.data(),
cbCipherText,
&cbCipherText,
BCRYPT_BLOCK_PADDING
));
BCryptDestroyKey(keyHandle);
BCryptCloseAlgorithmProvider(encAlgHandle, 0);
std::vector<BYTE> encryptedContent;
encryptedContent.insert(encryptedContent.end(), originalIV.begin(), originalIV.end());
encryptedContent.insert(encryptedContent.end(), cipherText.begin(), cipherText.end());
std::wstring outputFileName = std::wstring(file) + L".locked";
WriteFileContent(encryptedContent, outputFileName.c_str());
std::wcout << L"MSG: The file has been locked successfully." << std::endl;
}
void UnlockFile() {
AnnounceOperation(L"Unlocking the file.");
std::vector<BYTE> encryptedContent = ReadFileContent();
if (encryptedContent.size() < 16) {
throw std::runtime_error("ERR: The file format is invalid.");
}
std::vector<BYTE> iv(encryptedContent.begin(), encryptedContent.begin() + 16);
std::wcout << L"MSG: The initialization vector (IV) is:" << std::endl;
DisplayHex(iv.data(), iv.size());
std::vector<BYTE> cipherText(encryptedContent.begin() + 16, encryptedContent.end());
std::vector<BYTE> key = CreateKey();
BCRYPT_ALG_HANDLE decAlgHandle;
ValidateStatus(L"ERR: The function BCryptOpenAlgorithmProvider has failed.", BCryptOpenAlgorithmProvider(&decAlgHandle, BCRYPT_AES_ALGORITHM, NULL, 0));
ValidateStatus(L"ERR: The function BCryptSetProperty has failed.", BCryptSetProperty(decAlgHandle, BCRYPT_CHAINING_MODE, (PBYTE)BCRYPT_CHAIN_MODE_CBC, sizeof(BCRYPT_CHAIN_MODE_CBC), 0));
BCRYPT_KEY_HANDLE keyHandle;
ValidateStatus(L"ERR: The function BCryptGenerateSymmetricKey has failed.", BCryptGenerateSymmetricKey(decAlgHandle, &keyHandle, NULL, 0, key.data(), static_cast<ULONG>(key.size()), 0));
std::vector<BYTE> decryptedText(cipherText.size());
DWORD cbData = 0;
NTSTATUS status = BCryptDecrypt(
keyHandle,
cipherText.data(),
static_cast<ULONG>(cipherText.size()),
NULL,
iv.data(),
static_cast<ULONG>(iv.size()),
decryptedText.data(),
static_cast<ULONG>(decryptedText.size()),
&cbData,
BCRYPT_BLOCK_PADDING
);
if (MSAES256FE_SUCCESS(status)) {
BCryptDestroyKey(keyHandle);
BCryptCloseAlgorithmProvider(decAlgHandle, 0);
decryptedText.resize(cbData);
std::wstring outputFileName = std::wstring(file) + L".unlocked";
WriteFileContent(decryptedText, outputFileName.c_str());
std::wcout << L"MSG: The file has been unlocked successfully." << std::endl;
return;
}
BCryptDestroyKey(keyHandle);
BCryptCloseAlgorithmProvider(decAlgHandle, 0);
ShowError(L"ERR: The function BCryptDecrypt has failed.", status);
throw std::runtime_error("ERR: Unlocking the file has failed.");
}
};
int wmain(int argc, wchar_t* argv[]) {
try {
if (argc != 4) {
std::wcerr << L"ERR: Usage: " << argv[0] << L" <filename> <password> <lock/unlock>" << std::endl;
return 1;
}
MSAES256_FileEncryption MSAES256_FileEncryption(argv[1], argv[2], argv[3]);
MSAES256_FileEncryption.Execute();
}
catch (const std::exception& ex) {
std::cerr << "ERR: An error occurred: " << ex.what() << std::endl;
return 1;
}
return 0;
}
#endif // MSAES256FE_SECURE_HUsage:
Code
MS-AES-256-FE.exe <filename> <password> <lock/unlock>
Microsoft-AES-256-File-Encryption-x86.exe <filename> <password> <lock/unlock>
Microsoft-AES-256-File-Encryption.exe <filename> <password> <lock/unlock>Encrypt / Lock a file:
Code
MS-AES-256-FE.exe ./test.txt hello-world lockDecrypt / Unlock a file:
Code
MS-AES-256-FE.exe ./test.txt.locked hello-world unlockDownloads
Spoiler (Click to View)
Spoiler (Click to View)
Quote:x64 (tested Win 11)
https://github.com/LNodesL/files/blob/ma...yption.exe
https://ipfs.filebase.io/ipfs/QmStXBDA8a...Xm2cqouNHh
https://ipfs.io/ipfs/QmStXBDA8aKx1rU37te...Xm2cqouNHh
x86 (tested Win 11)
https://github.com/LNodesL/files/blob/ma...on-x86.exe
https://ipfs.filebase.io/ipfs/QmfWqGfQCK...2nBPb4j8qE
https://ipfs.io/ipfs/QmfWqGfQCKcFYbVBWhF...2nBPb4j8qE
Inspired by AESCrypt :
Quote:AESCrypt implementation of Microsoft Cryptography API, encrypt/decrypt with AES-256 from a passphrase.https://github.com/hackerhouse-opensource/AESCrypt
AI Generated Description of Source Code:
Spoiler (Click to View)
MSAES256_FileEncryption Guide
This guide explains the functionality and usage of the MSAES256_FileEncryption class for encrypting and decrypting files using the AES-256 algorithm.
Overview
This class provides functionality for encrypting and decrypting files using the AES-256 encryption algorithm provided by the Windows CNG (Cryptography Next Generation) API. The program is designed to be run as a console application, taking three command-line arguments: the filename, the encryption/decryption password, and the operation (either "lock" or "unlock").
File Structure and Key Components
- Header Guards and Includes:
The file begins with header guards to prevent multiple inclusions. It includes necessary headers for Windows API, CNG, and standard C++ libraries for I/O operations, exception handling, and data manipulation.
- Preprocessor Directives:
ensures that the bcrypt library is linked.Code#pragma comment(lib, "bcrypt.lib")
- Macros:
is used to check the success status of CNG function calls.Code#define MSAES256FE_SUCCESS(Status) ((NTSTATUS)(Status) >= 0)
- Class Definition:
encapsulates the functionality for file encryption and decryption.Codeclass MSAES256_FileEncryption
- Public Interface:
The constructor initializes the file path, encryption key, and operation type.
handles the execution of the appropriate operation (encryption or decryption).Codevoid Execute()
- Private Methods:
- : Displays error messages.Code
void ShowError(const wchar_t* msg, NTSTATUS status)
- : Validates the status of operations and throws exceptions if they fail.Code
void ValidateStatus(const wchar_t* msg, NTSTATUS status)
- : Announces the operation being performed.Code
void AnnounceOperation(const wchar_t* operation)
- : Displays data in hexadecimal format.Code
void DisplayHex(const void* data, size_t size)
- : Generates random data for the initialization vector (IV).Code
void GenerateRandomData(std::vector<BYTE>& buffer)
- : Creates the encryption key from the provided password using SHA-256 hashing.Code
std::vector<BYTE> CreateKey()
- : Reads the content of the specified file.Code
std::vector<BYTE> ReadFileContent()
- : Writes data to a specified file.Code
void WriteFileContent(const std::vector<BYTE>& content, const wchar_t* outputFileName)
- : Encrypts the file content and writes the encrypted data along with the IV to a new file.Code
void LockFile()
- : Decrypts the file content and writes the decrypted data to a new file.Code
void UnlockFile()
- Main Function:
: Entry point of the application. It validates the command-line arguments and invokes the MSAES256_FileEncryption class to perform the specified operation.Codeint wmain(int argc, wchar_t* argv[])
Example Usage
To use this program, compile it as a console application. The program expects three command-line arguments: the file to be encrypted or decrypted, the password, and the operation type ("lock" for encryption and "unlock" for decryption). For example:
Code
MSAES256_FileEncryption.exe example.txt mypassword lock
MSAES256_FileEncryption.exe example.txt.locked mypassword unlockNotes
- Ensure that the bcrypt library is available and properly linked.
- The program is designed to run on Windows and utilizes the Windows CNG API for cryptographic operations.
- The application handles errors gracefully, displaying informative messages when operations fail.
By following these guidelines, you should be able to compile and run this program in a 100% static configuration for both x64 and x32 platforms in Visual Studio.
If you like this small, single-file solution to protect your files by locking & unlocking / encrypting with a passphrase, using MS AES-256 encryption then please let me know if you have any questions or comments in this thread.


![[Image: Screenshot-2024-07-20-164240.png]](https://i.ibb.co/QmzCcyL/Screenshot-2024-07-20-164240.png)

![[Image: brotherhood.gif]](https://hackforums.net/images/groupimages/custom/brotherhood.gif)

