From 2e615b1b1956135d822237808353caa9daa35c09 Mon Sep 17 00:00:00 2001 From: Danny Robson Date: Sun, 10 Feb 2019 13:12:05 +1100 Subject: [PATCH] hash/blake2: use aligned storage for u64 salt components --- hash/blake2.cpp | 11 ++++------- hash/blake2.hpp | 12 +++++++----- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/hash/blake2.cpp b/hash/blake2.cpp index c3bec52..7ae2e6d 100644 --- a/hash/blake2.cpp +++ b/hash/blake2.cpp @@ -135,8 +135,8 @@ blake2::blake2 (cruft::view key) if (key.size () > ::traits::max_key_bytes) throw std::invalid_argument ("key is too large"); - std::fill (m_salt.begin (), m_salt.end (), 0); - memcpy (m_salt.data (), key.data (), key.size ()); + std::fill (m_salt.val08.begin (), m_salt.val08.end (), 0); + memcpy (m_salt.val08.data (), key.data (), key.size ()); m_keylen = key.size (); } @@ -145,13 +145,11 @@ blake2::blake2 (cruft::view key) blake2::digest_t blake2::operator() (cruft::view data) const noexcept { -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wcast-align" auto h = ::traits::iv; h[0] ^= 0x01010000 ^ (m_keylen << 8) ^ sizeof (digest_t); if (m_keylen) - F (h, reinterpret_cast (m_salt.data ()), ::traits::block_bytes, data.empty ()); + F (h, m_salt.val64.data (), ::traits::block_bytes, data.empty ()); // special case for the empty key and empty data if (!m_keylen && data.empty ()) { @@ -164,7 +162,7 @@ blake2::operator() (cruft::view data) const noexcept auto cursor = data.begin (); while (cursor + ::traits::block_bytes < data.end ()) { counter += ::traits::block_bytes; - F (h, reinterpret_cast (cursor), counter, false); + F (h, cruft::cast::alignment (cursor), counter, false); cursor += ::traits::block_bytes; } @@ -178,5 +176,4 @@ blake2::operator() (cruft::view data) const noexcept digest_t d; memcpy (&d, h.data (), sizeof (d)); return d; -#pragma GCC diagnostic pop } diff --git a/hash/blake2.hpp b/hash/blake2.hpp index 51d145c..954f02c 100644 --- a/hash/blake2.hpp +++ b/hash/blake2.hpp @@ -6,9 +6,9 @@ * Copyright 2018 Danny Robson */ -#ifndef CRUFT_CRYPTO_HASH_BLAKE2_HPP -#define CRUFT_CRYPTO_HASH_BLAKE2_HPP +#pragma once +#include #include #include @@ -34,9 +34,11 @@ namespace cruft::crypto::hash { // updates, not because it's a functional requirement. either way we // need to copy at least 64 bytes, so the user shouldn't be copying // these too much regardless. - std::array m_salt; + union { + std::array val08; + std::array val64; + } m_salt; + uint64_t m_keylen; }; }; - -#endif