Debian Codegraph @

debian/rust-vendor/aws-lc-sys/aws-lc/crypto/fipsmodule/modes/polyval.c

raw
1 // Copyright (c) 2016, Google Inc.
2 // SPDX-License-Identifier: ISC
3
4 #include <openssl/base.h>
5
6 #include <assert.h>
7 #include <string.h>
8
9 #include "internal.h"
10 #include "../../internal.h"
11
12
13 // byte_reverse reverses the order of the bytes in |b->c|.
14 static void byte_reverse(uint8_t b[16]) {
15 uint64_t hi = CRYPTO_load_u64_le(b);
16 uint64_t lo = CRYPTO_load_u64_le(b + 8);
17 CRYPTO_store_u64_le(b, CRYPTO_bswap8(lo));
18 CRYPTO_store_u64_le(b + 8, CRYPTO_bswap8(hi));
19 }
20
21 // reverse_and_mulX_ghash interprets |b| as a reversed element of the GHASH
22 // field, multiplies that by 'x' and serialises the result back into |b|, but
23 // with GHASH's backwards bit ordering.
24 static void reverse_and_mulX_ghash(uint8_t b[16]) {
25 uint64_t hi = CRYPTO_load_u64_le(b);
26 uint64_t lo = CRYPTO_load_u64_le(b + 8);
27 const crypto_word_t carry = constant_time_eq_w(hi & 1, 1);
28 hi >>= 1;
29 hi |= lo << 63;
30 lo >>= 1;
31 lo ^= ((uint64_t) constant_time_select_w(carry, 0xe1, 0)) << 56;
32
33 CRYPTO_store_u64_le(b, CRYPTO_bswap8(lo));
34 CRYPTO_store_u64_le(b + 8, CRYPTO_bswap8(hi));
35 }
36
37 // POLYVAL(H, X_1, ..., X_n) =
38 // ByteReverse(GHASH(mulX_GHASH(ByteReverse(H)), ByteReverse(X_1), ...,
39 // ByteReverse(X_n))).
40 //
41 // See https://www.rfc-editor.org/rfc/rfc8452.html#appendix-A.
42
43 void CRYPTO_POLYVAL_init(struct polyval_ctx *ctx, const uint8_t key[16]) {
44 alignas(8) uint8_t H[16];
45 OPENSSL_memcpy(H, key, 16);
46 reverse_and_mulX_ghash(H);
47
48 int is_avx;
49 CRYPTO_ghash_init(&ctx->gmult, &ctx->ghash, ctx->Htable, &is_avx, H);
50 OPENSSL_memset(&ctx->S, 0, sizeof(ctx->S));
51 }
52
53 void CRYPTO_POLYVAL_update_blocks(struct polyval_ctx *ctx, const uint8_t *in,
54 size_t in_len) {
55 assert((in_len & 15) == 0);
56 alignas(8) uint8_t buf[32 * 16];
57
58 while (in_len > 0) {
59 size_t todo = in_len;
60 if (todo > sizeof(buf)) {
61 todo = sizeof(buf);
62 }
63 OPENSSL_memcpy(buf, in, todo);
64 in += todo;
65 in_len -= todo;
66
67 size_t blocks = todo / 16;
68 for (size_t i = 0; i < blocks; i++) {
69 byte_reverse(buf + 16 * i);
70 }
71
72 ctx->ghash(ctx->S, ctx->Htable, buf, todo);
73 }
74 }
75
76 void CRYPTO_POLYVAL_finish(const struct polyval_ctx *ctx, uint8_t out[16]) {
77 OPENSSL_memcpy(out, &ctx->S, 16);
78 byte_reverse(out);
79 }