Skip to content

Instantly share code, notes, and snippets.

@BreadFish64
Created February 22, 2020 04:26
Show Gist options
  • Save BreadFish64/20514cc18c08f6d5c1d5bf0d439cb057 to your computer and use it in GitHub Desktop.
Save BreadFish64/20514cc18c08f6d5c1d5bf0d439cb057 to your computer and use it in GitHub Desktop.
class SHA256 {
public:
using Digest = std::array<u8, 32>;
SHA256() {
mbedtls_sha256_init(&ctx);
}
SHA256(const SHA256& original) {
mbedtls_sha256_clone(&ctx, &original.ctx);
}
~SHA256() {
mbedtls_sha256_free(&ctx);
}
void Start(bool is224 = false) {
mbedtls_sha256_starts_ret(&ctx, is224);
}
template <typename T, typename = std::enable_if<std::is_pointer_v<T>>>
void Update(const T data, std::size_t size) {
auto T = reinterpret_cast<const u8*>(data);
size *= sizeof(T);
mbedtls_sha256_update_ret(&ctx, data, size);
}
template <typename T>
void Update(const T& data) {
Update(reinterpret_cast<const u8*>(&data), sizeof(data));
}
[[nodiscard]] Digest Finish() {
Digest hash;
mbedtls_sha256_finish_ret(&ctx, hash.data());
return hash;
}
template <typename... T>
[[nodiscard]] static Digest CalculateDigest(T&&... data) {
SHA256 ctx;
ctx.Start()
ctx.Update(std::forward<T>(data)...);
return ctx.Finish();
};
private:
mbedtls_sha256_context ctx{};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment