| 1 |
// SPDX-License-Identifier: GPL-2.0 |
| 2 |
/* |
| 3 |
* Copyright 2018 Google LLC |
| 4 |
*/ |
| 5 |
|
| 6 |
/* |
| 7 |
* Implementation of the NH almost-universal hash function, specifically the |
| 8 |
* variant of NH used in Adiantum. This is *not* a cryptographic hash function. |
| 9 |
* |
| 10 |
* Reference: section 6.3 of "Adiantum: length-preserving encryption for |
| 11 |
* entry-level processors" (https://eprint.iacr.org/2018/720.pdf). |
| 12 |
*/ |
| 13 |
|
| 14 |
#include <crypto/nh.h> |
| 15 |
#include <linux/export.h> |
| 16 |
#include <linux/kernel.h> |
| 17 |
#include <linux/module.h> |
| 18 |
#include <linux/unaligned.h> |
| 19 |
|
| 20 |
#ifdef CONFIG_CRYPTO_LIB_NH_ARCH |
| 21 |
#include "nh.h" /* $(SRCARCH)/nh.h */ |
| 22 |
#else |
| 23 |
static bool nh_arch(const u32 *key, const u8 *message, size_t message_len, |
| 24 |
__le64 hash[NH_NUM_PASSES]) |
| 25 |
{ |
| 26 |
return false; |
| 27 |
} |
| 28 |
#endif |
| 29 |
|
| 30 |
void nh(const u32 *key, const u8 *message, size_t message_len, |
| 31 |
__le64 hash[NH_NUM_PASSES]) |
| 32 |
{ |
| 33 |
u64 sums[4] = { 0, 0, 0, 0 }; |
| 34 |
|
| 35 |
if (nh_arch(key, message, message_len, hash)) |
| 36 |
return; |
| 37 |
|
| 38 |
static_assert(NH_PAIR_STRIDE == 2); |
| 39 |
static_assert(NH_NUM_PASSES == 4); |
| 40 |
|
| 41 |
while (message_len) { |
| 42 |
u32 m0 = get_unaligned_le32(message + 0); |
| 43 |
u32 m1 = get_unaligned_le32(message + 4); |
| 44 |
u32 m2 = get_unaligned_le32(message + 8); |
| 45 |
u32 m3 = get_unaligned_le32(message + 12); |
| 46 |
|
| 47 |
sums[0] += (u64)(u32)(m0 + key[0]) * (u32)(m2 + key[2]); |
| 48 |
sums[1] += (u64)(u32)(m0 + key[4]) * (u32)(m2 + key[6]); |
| 49 |
sums[2] += (u64)(u32)(m0 + key[8]) * (u32)(m2 + key[10]); |
| 50 |
sums[3] += (u64)(u32)(m0 + key[12]) * (u32)(m2 + key[14]); |
| 51 |
sums[0] += (u64)(u32)(m1 + key[1]) * (u32)(m3 + key[3]); |
| 52 |
sums[1] += (u64)(u32)(m1 + key[5]) * (u32)(m3 + key[7]); |
| 53 |
sums[2] += (u64)(u32)(m1 + key[9]) * (u32)(m3 + key[11]); |
| 54 |
sums[3] += (u64)(u32)(m1 + key[13]) * (u32)(m3 + key[15]); |
| 55 |
key += NH_MESSAGE_UNIT / sizeof(key[0]); |
| 56 |
message += NH_MESSAGE_UNIT; |
| 57 |
message_len -= NH_MESSAGE_UNIT; |
| 58 |
} |
| 59 |
|
| 60 |
hash[0] = cpu_to_le64(sums[0]); |
| 61 |
hash[1] = cpu_to_le64(sums[1]); |
| 62 |
hash[2] = cpu_to_le64(sums[2]); |
| 63 |
hash[3] = cpu_to_le64(sums[3]); |
| 64 |
} |
| 65 |
EXPORT_SYMBOL_GPL(nh); |
| 66 |
|
| 67 |
#ifdef nh_mod_init_arch |
| 68 |
static int __init nh_mod_init(void) |
| 69 |
{ |
| 70 |
nh_mod_init_arch(); |
| 71 |
return 0; |
| 72 |
} |
| 73 |
subsys_initcall(nh_mod_init); |
| 74 |
|
| 75 |
static void __exit nh_mod_exit(void) |
| 76 |
{ |
| 77 |
} |
| 78 |
module_exit(nh_mod_exit); |
| 79 |
#endif |
| 80 |
|
| 81 |
MODULE_DESCRIPTION("NH almost-universal hash function"); |
| 82 |
MODULE_LICENSE("GPL"); |