commit c681457f2b0968180c05421588397a4ec45abd15
parent db203e9508242bfe3272e2e6989934d9b56979c9
Author: cfillion <cfillion@users.noreply.github.com>
Date: Fri, 7 Dec 2018 21:50:11 -0500
implement simple hash algorithm detection from string
Diffstat:
3 files changed, 40 insertions(+), 0 deletions(-)
diff --git a/src/hash.cpp b/src/hash.cpp
@@ -173,3 +173,21 @@ const std::string &Hash::digest()
return m_value;
}
+
+bool Hash::getAlgorithm(const std::string &hash, Algorithm *out)
+{
+ unsigned int algo, size;
+ if(sscanf(hash.c_str(), "%2x%2x", &algo, &size) != 2)
+ return false;
+
+ if(hash.size() != size + 4)
+ return false;
+
+ switch(algo) {
+ case SHA256:
+ *out = static_cast<Algorithm>(algo);
+ return true;
+ default:
+ return false;
+ };
+}
diff --git a/src/hash.hpp b/src/hash.hpp
@@ -10,7 +10,11 @@ public:
SHA256 = 0x12,
};
+ static bool getAlgorithm(const std::string &hash, Algorithm *out);
+
Hash(Algorithm);
+ Hash(const Hash &) = delete;
+
void write(const char *data, size_t len);
const std::string &digest();
diff --git a/test/hash.cpp b/test/hash.cpp
@@ -33,3 +33,21 @@ TEST_CASE("invalid algorithm", M) {
hash.write("foo bar", 7);
REQUIRE(hash.digest() == "");
}
+
+TEST_CASE("get hash algorithm", M) {
+ Hash::Algorithm algo;
+
+ SECTION("empty string")
+ REQUIRE_FALSE(Hash::getAlgorithm("", &algo));
+
+ SECTION("only sha-256 ID")
+ REQUIRE_FALSE(Hash::getAlgorithm("12", &algo));
+
+ SECTION("unexpected size")
+ REQUIRE_FALSE(Hash::getAlgorithm("1204ab", &algo));
+
+ SECTION("seemingly good (but not actually) sha-256") {
+ REQUIRE(Hash::getAlgorithm("1204abcd", &algo));
+ REQUIRE(algo == Hash::SHA256);
+ }
+}