native 0.0.1
Vectors, masks and wide register packs for C++26
Loading...
Searching...
No Matches
aes_constant.h
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Edward Kmett <ekmett@gmail.com>
2// SPDX-License-Identifier: BSD-2-Clause OR Apache-2.0
10#pragma once
11
12#include <array>
13#include <bit>
14#include <cstdint>
15
16namespace native::detail::aes_constant {
17 constexpr std::uint8_t field_product(std::uint8_t a, std::uint8_t b) noexcept {
18 unsigned x = a, y = b, result = 0;
19 for (unsigned bit = 0; bit < 8; ++bit) {
20 if (y & 1) result ^= x;
21 y >>= 1;
22 x = (x << 1) ^ ((x & 0x80) ? 0x11b : 0);
23 }
24 return static_cast<std::uint8_t>(result);
25 }
26
27 constexpr std::uint8_t field_inverse(std::uint8_t value) noexcept {
28 // In GF(256), x^254 is x^-1 for nonzero x; zero remains zero.
29 std::uint8_t result = 1;
30 for (unsigned exponent = 254; exponent; exponent >>= 1) {
31 if (exponent & 1) result = field_product(result, value);
32 value = field_product(value, value);
33 }
34 return result;
35 }
36
37 template<bool Inverse>
38 constexpr std::uint8_t substitute(std::uint8_t value) noexcept {
39 if constexpr (Inverse) {
40 return field_inverse(static_cast<std::uint8_t>(
41 std::rotl(value, 1) ^ std::rotl(value, 3) ^ std::rotl(value, 6) ^ 5));
42 } else {
43 auto x = field_inverse(value);
44 return static_cast<std::uint8_t>(x ^ std::rotl(x, 1) ^ std::rotl(x, 2) ^
45 std::rotl(x, 3) ^ std::rotl(x, 4) ^ 0x63);
46 }
47 }
48
49 template<bool Inverse>
50 constexpr auto shift_substitute(std::array<std::uint8_t, 16> const & input) noexcept {
51 std::array<std::uint8_t, 16> result{};
52 for (unsigned column = 0; column < 4; ++column) {
53 for (unsigned row = 0; row < 4; ++row) {
54 auto source = 4 * ((column + (Inverse ? 4 - row : row)) % 4) + row;
55 result[4 * column + row] = substitute<Inverse>(input[source]);
56 }
57 }
58 return result;
59 }
60
61 template<bool Inverse>
62 constexpr auto mix(std::array<std::uint8_t, 16> const & input) noexcept {
63 std::array<std::uint8_t, 16> result{};
64 constexpr std::uint8_t coefficients[2][4]{{2, 3, 1, 1}, {14, 11, 13, 9}};
65 for (unsigned column = 0; column < 4; ++column) {
66 for (unsigned row = 0; row < 4; ++row) {
67 for (unsigned term = 0; term < 4; ++term) {
68 result[4 * column + row] ^= field_product(input[4 * column + term],
69 coefficients[Inverse][(term + 4 - row) % 4]);
70 }
71 }
72 }
73 return result;
74 }
75}