1 // SPDX-License-Identifier: GPL-2.0 OR MIT
3 * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
5 * This is based in part on Andrew Moon's poly1305-donna, which is in the
9 typedef __uint128_t u128;
11 struct poly1305_internal {
17 static void poly1305_init_generic(void *ctx, const u8 key[16])
19 struct poly1305_internal *st = (struct poly1305_internal *)ctx;
22 /* r &= 0xffffffc0ffffffc0ffffffc0fffffff */
23 t0 = get_unaligned_le64(&key[0]);
24 t1 = get_unaligned_le64(&key[8]);
26 st->r[0] = t0 & 0xffc0fffffffULL;
27 st->r[1] = ((t0 >> 44) | (t1 << 20)) & 0xfffffc0ffffULL;
28 st->r[2] = ((t1 >> 24)) & 0x00ffffffc0fULL;
31 st->s[0] = st->r[1] * 20;
32 st->s[1] = st->r[2] * 20;
40 static void poly1305_blocks_generic(void *ctx, const u8 *input, size_t len,
43 struct poly1305_internal *st = (struct poly1305_internal *)ctx;
44 const u64 hibit = ((u64)padbit) << 40;
62 while (len >= POLY1305_BLOCK_SIZE) {
66 t0 = get_unaligned_le64(&input[0]);
67 t1 = get_unaligned_le64(&input[8]);
69 h0 += t0 & 0xfffffffffffULL;
70 h1 += ((t0 >> 44) | (t1 << 20)) & 0xfffffffffffULL;
71 h2 += (((t1 >> 24)) & 0x3ffffffffffULL) | hibit;
90 /* (partial) h %= p */
92 h0 = (u64)d0 & 0xfffffffffffULL;
95 h1 = (u64)d1 & 0xfffffffffffULL;
98 h2 = (u64)d2 & 0x3ffffffffffULL;
101 h0 = h0 & 0xfffffffffffULL;
104 input += POLY1305_BLOCK_SIZE;
105 len -= POLY1305_BLOCK_SIZE;
113 static void poly1305_emit_generic(void *ctx, u8 mac[16], const u32 nonce[4])
115 struct poly1305_internal *st = (struct poly1305_internal *)ctx;
126 h1 &= 0xfffffffffffULL;
129 h2 &= 0x3ffffffffffULL;
132 h0 &= 0xfffffffffffULL;
135 h1 &= 0xfffffffffffULL;
138 h2 &= 0x3ffffffffffULL;
141 h0 &= 0xfffffffffffULL;
147 g0 &= 0xfffffffffffULL;
150 g1 &= 0xfffffffffffULL;
151 g2 = h2 + c - (1ULL << 42);
153 /* select h if h < p, or h + -p if h >= p */
154 c = (g2 >> ((sizeof(u64) * 8) - 1)) - 1;
163 /* h = (h + nonce) */
164 t0 = ((u64)nonce[1] << 32) | nonce[0];
165 t1 = ((u64)nonce[3] << 32) | nonce[2];
167 h0 += t0 & 0xfffffffffffULL;
169 h0 &= 0xfffffffffffULL;
170 h1 += (((t0 >> 44) | (t1 << 20)) & 0xfffffffffffULL) + c;
172 h1 &= 0xfffffffffffULL;
173 h2 += (((t1 >> 24)) & 0x3ffffffffffULL) + c;
174 h2 &= 0x3ffffffffffULL;
176 /* mac = h % (2^128) */
177 h0 = h0 | (h1 << 44);
178 h1 = (h1 >> 20) | (h2 << 24);
180 put_unaligned_le64(h0, &mac[0]);
181 put_unaligned_le64(h1, &mac[8]);