From dc888d597beb75242eef28b4adb0c0b18be5e3b3 Mon Sep 17 00:00:00 2001 From: Justin W Smith <103147162+justsmth@users.noreply.github.com> Date: Fri, 20 Oct 2023 14:08:36 -0400 Subject: [PATCH] Fix SipHash for big-endian (#1251) --- crypto/siphash/siphash.c | 17 ++++++++++++----- crypto/siphash/siphash_test.cc | 10 +++++----- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/crypto/siphash/siphash.c b/crypto/siphash/siphash.c index 0921eac2b4..beab101d14 100644 --- a/crypto/siphash/siphash.c +++ b/crypto/siphash/siphash.c @@ -41,11 +41,18 @@ uint64_t SIPHASH_24(const uint64_t key[2], const uint8_t *input, size_t input_len) { const size_t orig_input_len = input_len; - uint64_t v[4]; - v[0] = key[0] ^ UINT64_C(0x736f6d6570736575); - v[1] = key[1] ^ UINT64_C(0x646f72616e646f6d); - v[2] = key[0] ^ UINT64_C(0x6c7967656e657261); - v[3] = key[1] ^ UINT64_C(0x7465646279746573); + uint64_t v[4], k0, k1; +#ifdef OPENSSL_BIG_ENDIAN + k0 = CRYPTO_bswap8(key[0]); + k1 = CRYPTO_bswap8(key[1]); +#else + k0 = key[0]; + k1 = key[1]; +#endif + v[0] = k0 ^ UINT64_C(0x736f6d6570736575); + v[1] = k1 ^ UINT64_C(0x646f72616e646f6d); + v[2] = k0 ^ UINT64_C(0x6c7967656e657261); + v[3] = k1 ^ UINT64_C(0x7465646279746573); while (input_len >= sizeof(uint64_t)) { uint64_t m = CRYPTO_load_u64_le(input); diff --git a/crypto/siphash/siphash_test.cc b/crypto/siphash/siphash_test.cc index 6407e0da56..9f2c24324b 100644 --- a/crypto/siphash/siphash_test.cc +++ b/crypto/siphash/siphash_test.cc @@ -41,17 +41,17 @@ TEST(SipHash, Basic) { TEST(SipHash, Vectors) { FileTestGTest("crypto/siphash/siphash_tests.txt", [](FileTest *t) { - std::vector key, msg, hash; + std::vector key, msg, hash_bytes; ASSERT_TRUE(t->GetBytes(&key, "KEY")); ASSERT_TRUE(t->GetBytes(&msg, "IN")); - ASSERT_TRUE(t->GetBytes(&hash, "HASH")); + ASSERT_TRUE(t->GetBytes(&hash_bytes, "HASH")); ASSERT_EQ(16u, key.size()); - ASSERT_EQ(8u, hash.size()); + ASSERT_EQ(8u, hash_bytes.size()); + uint64_t hash = CRYPTO_load_u64_le(hash_bytes.data()); uint64_t key_words[2]; memcpy(key_words, key.data(), key.size()); uint64_t result = SIPHASH_24(key_words, msg.data(), msg.size()); - EXPECT_EQ(Bytes(reinterpret_cast(&result), sizeof(result)), - Bytes(hash)); + EXPECT_EQ(result, hash); }); }