71 lines
2.0 KiB
C++
71 lines
2.0 KiB
C++
#include <openssl/sha.h>
|
|
#include <fstream>
|
|
#include <iostream>
|
|
#include <iomanip>
|
|
#include <sstream>
|
|
#include <vector>
|
|
|
|
std::string to_hex_string(const unsigned char* hash, size_t length) {
|
|
std::ostringstream oss;
|
|
for (size_t i = 0; i < length; ++i) {
|
|
oss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(hash[i]);
|
|
}
|
|
return oss.str();
|
|
}
|
|
|
|
std::string sha256_string(const std::string& input) {
|
|
unsigned char hash[SHA256_DIGEST_LENGTH];
|
|
SHA256(reinterpret_cast<const unsigned char*>(input.c_str()), input.size(), hash);
|
|
return to_hex_string(hash, SHA256_DIGEST_LENGTH);
|
|
}
|
|
|
|
std::string sha256_file(const std::string& filename) {
|
|
std::ifstream file(filename, std::ios::binary);
|
|
if (!file) {
|
|
throw std::runtime_error("Cannot open file: " + filename);
|
|
}
|
|
|
|
SHA256_CTX ctx;
|
|
SHA256_Init(&ctx);
|
|
|
|
std::vector<char> buffer(8192);
|
|
while (file.good()) {
|
|
file.read(buffer.data(), buffer.size());
|
|
SHA256_Update(&ctx, buffer.data(), file.gcount());
|
|
}
|
|
|
|
unsigned char hash[SHA256_DIGEST_LENGTH];
|
|
SHA256_Final(hash, &ctx);
|
|
|
|
return to_hex_string(hash, SHA256_DIGEST_LENGTH);
|
|
}
|
|
|
|
int main(int argc, char* argv[]) {
|
|
if (argc != 3) {
|
|
std::cerr << "Usage: " << argv[0] << " <mode> <input>" << std::endl;
|
|
std::cerr << "Modes:" << std::endl;
|
|
std::cerr << " -s : Calculate SHA-256 for a string" << std::endl;
|
|
std::cerr << " -f : Calculate SHA-256 for a file" << std::endl;
|
|
return 1;
|
|
}
|
|
|
|
std::string mode = argv[1];
|
|
std::string input = argv[2];
|
|
|
|
try {
|
|
if (mode == "-s") {
|
|
std::cout << "SHA-256(string): " << sha256_string(input) << std::endl;
|
|
} else if (mode == "-f") {
|
|
std::cout << "SHA-256(file): " << sha256_file(input) << std::endl;
|
|
} else {
|
|
std::cerr << "Invalid mode: " << mode << std::endl;
|
|
return 1;
|
|
}
|
|
} catch (const std::exception& e) {
|
|
std::cerr << "Error: " << e.what() << std::endl;
|
|
return 1;
|
|
}
|
|
|
|
return 0;
|
|
}
|