Last active
February 15, 2026 22:35
-
-
Save chinchila/b765f842a7a299445be8a0101cec6b80 to your computer and use it in GitHub Desktop.
Multiplication GF(2**8) using matrices
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import numpy as np | |
| def companion_matrix(): | |
| C = np.zeros((8, 8), dtype=int) | |
| for i in range(7): | |
| C[i, i + 1] = 1 | |
| C[7, [0, 1, 3, 4]] = 1 | |
| return C | |
| def matrix_mod2(mat): | |
| return np.mod(mat, 2) | |
| def generate_multiplication_matrix(alpha): | |
| C = companion_matrix() | |
| M = np.zeros((8, 8), dtype=int) | |
| binary_representation = [(alpha >> i) & 1 for i in range(8)] | |
| for i, bit in enumerate(binary_representation): | |
| if bit: | |
| M += np.linalg.matrix_power(C, i) | |
| return (M) | |
| def gf2_8_multiply(a, b): | |
| irreducible_poly = 0x11b | |
| result = 0 | |
| for _ in range(8): | |
| if b & 1: | |
| result ^= a | |
| carry = a & 0x80 | |
| a <<= 1 | |
| if carry: | |
| a ^= irreducible_poly | |
| b >>= 1 | |
| return result & 0xFF | |
| for alpha in range(256): | |
| for beta in range(256): | |
| expected = gf2_8_multiply(alpha, beta) | |
| matrix = generate_multiplication_matrix(alpha) | |
| v = np.array([int(k) for k in '{:08b}'.format(beta)[::-1]]) | |
| value = (v@matrix)%2 | |
| aux = int("".join([str(k) for k in value])[::-1], 2) | |
| if aux != expected: | |
| print("deu ruim:", alpha, beta, aux, expected, value, '{:08b}'.format(expected)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment