1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-26 23:17:46 +00:00

LibCrypto: Add a Hash::Manager that can act as any one of the hashes

This commit is contained in:
AnotherTest 2020-04-25 05:06:33 +04:30 committed by Andreas Kling
parent e997661e26
commit 43a49f5fff
6 changed files with 338 additions and 17 deletions

View file

@ -44,8 +44,8 @@ class HMAC {
public:
using HashType = HashT;
using TagType = typename HashType::DigestType;
static constexpr size_t BlockSize = HashType::BlockSize;
static constexpr size_t DigestSize = HashType::DigestSize;
size_t digest_size() const { return m_inner_hasher.digest_size(); }
template<typename KeyBufferType, typename... Args>
HMAC(KeyBufferType key, Args... args)
@ -75,7 +75,7 @@ public:
TagType digest()
{
m_outer_hasher.update(m_inner_hasher.digest().data, m_inner_hasher.DigestSize);
m_outer_hasher.update(m_inner_hasher.digest().immutable_data(), m_inner_hasher.digest_size());
auto result = m_outer_hasher.digest();
reset();
return result;
@ -85,8 +85,8 @@ public:
{
m_inner_hasher.reset();
m_outer_hasher.reset();
m_inner_hasher.update(m_key_data, BlockSize);
m_outer_hasher.update(m_key_data + BlockSize, BlockSize);
m_inner_hasher.update(m_key_data, m_inner_hasher.block_size());
m_outer_hasher.update(m_key_data + m_inner_hasher.block_size(), m_outer_hasher.block_size());
}
String class_name() const
@ -100,25 +100,26 @@ public:
private:
void derive_key(const u8* key, size_t length)
{
u8 v_key[BlockSize];
__builtin_memset(v_key, 0, BlockSize);
ByteBuffer key_buffer = ByteBuffer::wrap(v_key, BlockSize);
auto block_size = m_inner_hasher.block_size();
u8 v_key[block_size];
__builtin_memset(v_key, 0, block_size);
ByteBuffer key_buffer = ByteBuffer::wrap(v_key, block_size);
// m_key_data is zero'd, so copying the data in
// the first few bytes leaves the rest zero, which
// is exactly what we want (zero padding)
if (length > BlockSize) {
if (length > block_size) {
m_inner_hasher.update(key, length);
auto digest = m_inner_hasher.digest();
// FIXME: should we check if the hash function creates more data than its block size?
key_buffer.overwrite(0, digest.data, sizeof(TagType));
key_buffer.overwrite(0, digest.immutable_data(), m_inner_hasher.digest_size());
} else {
key_buffer.overwrite(0, key, length);
}
// fill out the inner and outer padded keys
auto* i_key = m_key_data;
auto* o_key = m_key_data + BlockSize;
for (size_t i = 0; i < BlockSize; ++i) {
auto* o_key = m_key_data + block_size;
for (size_t i = 0; i < block_size; ++i) {
auto key_byte = key_buffer[i];
i_key[i] = key_byte ^ IPAD;
o_key[i] = key_byte ^ OPAD;
@ -129,7 +130,7 @@ private:
void derive_key(const StringView& key) { derive_key((const u8*)key.characters_without_null_termination(), key.length()); }
HashType m_inner_hasher, m_outer_hasher;
u8 m_key_data[BlockSize * 2];
u8 m_key_data[2048];
};
}