Certainly! Here's the modified C++ code that implements your requirements:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <filesystem>
#include <algorithm>
#include <cryptopp/keccak.h>
#include <cryptopp/hex.h>
#include <cryptopp/files.h>
#include <conio.h> // For getch()
#ifdef _WIN32
#include <windows.h> // For coloring in Windows
#else
#include <unistd.h> // For sleep()
#endif
namespace fs = std::filesystem;
// Function to calculate Keccak-512 hash of a file
std::string calculateKeccak512(const std::string& filePath) {
CryptoPP::Keccak_512 hash;
std::string digest;
CryptoPP::FileSource(filePath.c_str(), true,
new CryptoPP::HashFilter(hash,
new CryptoPP::HexEncoder(
new CryptoPP::StringSink(digest), true)));
return digest;
}
// Function to set console text color
void setConsoleColor(int color) {
#ifdef _WIN32
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
#else
// ANSI escape codes for Unix/Linux terminals
std::cout << "\033[" << color << "m";
#endif
}
// Function to reset console text color
void resetConsoleColor() {
#ifdef _WIN32
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7); // Default color
#else
std::cout << "\033[0m";
#endif
}
// Function to clear console screen
void clearScreen() {
#ifdef _WIN32
system("cls");
#else
system("clear");
#endif
}
// Function to display the progress bar
void displayProgressBar(float progress) {
int barWidth = 50;
std::cout << "\r[";
int pos = static_cast<int>(barWidth * progress);
for (int i = 0; i < barWidth; ++i) {
if (i < pos) std::cout << "=";
else if (i == pos) std::cout << ">";
else std::cout << " ";
}
std::cout << "] " << int(progress * 100.0) << "%";
std::cout.flush();
}
int main() {
// Step 1: Ask for the directory path
std::string directoryPath;
std::cout << "Digite o caminho da pasta que deve ser verificada: ";
std::getline(std::cin, directoryPath);
// Check if the directory exists
if (!fs::exists(directoryPath) || !fs::is_directory(directoryPath)) {
std::cerr << "Diretório inválido!" << std::endl;
return 1;
}
// Step 2: Collect files with specified extensions
std::vector<std::string> extensions = { ".exe", ".dll", ".asi" };
std::vector<std::pair<std::string, bool>> files; // Pair of filename and selection status
for (const auto& entry : fs::directory_iterator(directoryPath)) {
if (entry.is_regular_file()) {
std::string extension = entry.path().extension().string();
if (std::find(extensions.begin(), extensions.end(), extension) != extensions.end()) {
files.push_back({ entry.path().filename().string(), true }); // Default to selected (true)
}
}
}
// Step 3: Display files and allow selection/deselection
int currentIndex = 0;
char key;
while (true) {
clearScreen();
std::cout << "Use as setas para cima/baixo para navegar e ESPAÇO para selecionar/deselecionar arquivos." << std::endl;
std::cout << "Arquivos:" << std::endl << std::endl;
for (size_t i = 0; i < files.size(); ++i) {
if (i == currentIndex) {
// Highlight the current selection
setConsoleColor(112); // Bright background
std::cout << "> ";
}
else {
std::cout << " ";
}
if (files[i].second) {
setConsoleColor(10); // Green text
}
else {
setConsoleColor(12); // Red text
}
std::cout << files[i].first << std::endl;
resetConsoleColor();
}
std::cout << std::endl;
std::cout << "Pressione ENTER para gerar o arquivo." << std::endl;
key = _getch(); // Get character without waiting for Enter
if (key == '\r') { // ENTER key
break;
}
else if (key == -32 || key == 224) { // Arrow keys on Windows
key = _getch();
if (key == 72) { // Up arrow
if (currentIndex > 0) currentIndex--;
}
else if (key == 80) { // Down arrow
if (currentIndex < files.size() - 1) currentIndex++;
}
}
else if (key == ' ') {
// Toggle selection
files[currentIndex].second = !files[currentIndex].second;
}
}
// Step 4: Compute hashes and display progress bar
std::cout << "\nCalculando hashes..." << std::endl;
size_t totalFiles = std::count_if(files.begin(), files.end(), [](auto &f) { return f.second; });
size_t processedFiles = 0;
std::ofstream outputFile("rTales.ini");
if (!outputFile.is_open()) {
std::cerr << "Erro ao abrir o arquivo de saída!" << std::endl;
return 1;
}
for (auto& file : files) {
if (file.second) { // If the file is selected
std::string filePath = fs::path(directoryPath) / file.first;
std::string hash = calculateKeccak512(filePath);
outputFile << "\"" << file.first << "\" : " << hash << std::endl;
processedFiles++;
float progress = (float)processedFiles / totalFiles;
displayProgressBar(progress);
}
}
std::cout << std::endl;
outputFile.close();
std::cout << "Hashes calculados e salvos em rTales.ini" << std::endl;
return 0;
}
Explanation:
-
Directory Input: The program now asks for the directory path where it should search for files.
std::cout << "Digite o caminho da pasta que deve ser verificada: ";
std::getline(std::cin, directoryPath);
-
File Collection: It collects all files with the specified extensions (.exe, .dll, .asi) in the given directory.
std::vector<std::pair<std::string, bool>> files; // Pair of filename and selection status
for (const auto& entry : fs::directory_iterator(directoryPath)) {
if (entry.is_regular_file()) {
std::string extension = entry.path().extension().string();
if (std::find(extensions.begin(), extensions.end(), extension) != extensions.end()) {
files.push_back({ entry.path().filename().string(), true }); // Default to selected (true)
}
}
}
-
User Interaction for Selection/Deselection: The program displays the list of files, with the ability to navigate using the up/down arrow keys and toggle selection using the spacebar.
- Color Coding: Selected files are displayed in green, and unselected files are displayed in red.
- Navigation: Uses
_getch() to capture key presses without waiting for Enter.
- Arrow Keys: Handles arrow key input for navigation.
while (true) {
// ... [Display code omitted for brevity]
key = _getch(); // Get character without waiting for Enter
if (key == '\r') { // ENTER key
break;
}
else if (key == -32 || key == 224) { // Arrow keys on Windows
key = _getch();
if (key == 72) { // Up arrow
if (currentIndex > 0) currentIndex--;
}
else if (key == 80) { // Down arrow
if (currentIndex < files.size() - 1) currentIndex++;
}
}
else if (key == ' ') {
// Toggle selection
files[currentIndex].second = !files[currentIndex].second;
}
}
-
Progress Bar During Hash Calculation: When calculating the hashes, the program displays a progress bar to show the progress.
size_t totalFiles = std::count_if(files.begin(), files.end(), [](auto &f) { return f.second; });
size_t processedFiles = 0;
for (auto& file : files) {
if (file.second) { // If the file is selected
// ... [Hash calculation code]
processedFiles++;
float progress = (float)processedFiles / totalFiles;
displayProgressBar(progress);
}
}
-
Output File Naming: The output file is now named , and it contains only the hashes of the selected files.
Notes:
- Platform Compatibility: The code uses
_getch() and Windows-specific console functions, which are available on Windows. For Unix/Linux systems, you might need to adjust the code to use getch() from ncurses and handle ANSI escape codes for coloring.
- Arrow Key Handling: The handling of arrow keys is platform-specific. On Windows, arrow keys return a sequence of characters starting with
-32 or 224. On Unix/Linux, they might start with an escape character \033.
- Console Colors: The color codes may vary between systems. For more accurate coloring, you might need to map the colors appropriately or use a cross-platform library.
- Error Handling: The code includes basic error handling for invalid directories and file operations.
- Dependencies: Make sure to have the Crypto++ library installed and properly linked with your project to handle the Keccak-512 hashing.
Compiling the Code:
To compile this code, you might use a command like:
g++ -o hash_program main.cpp -lcryptopp
Or on Windows with Visual Studio:
cl /EHsc main.cpp cryptlib.lib
Conclusion:
This code meets your requirements by:
- Prompting for the directory path.
- Changing the output file name to
rTales.ini.
- Displaying a progress bar during hash calculation.
- Allowing you to select/deselect files with a colored console interface.
- Generating an output file with only the selected hashes.
Please ensure that your environment supports the required libraries and adjust any platform-specific code as needed.