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;
22 x = (x << 1) ^ ((x & 0x80) ? 0x11b : 0);
24 return static_cast<std::uint8_t
>(result);
27 constexpr std::uint8_t field_inverse(std::uint8_t value)
noexcept {
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);
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));
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);
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]);
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]);