Skip to content

Instantly share code, notes, and snippets.

@chinchila
Last active February 15, 2026 22:35
Show Gist options
  • Select an option

  • Save chinchila/b765f842a7a299445be8a0101cec6b80 to your computer and use it in GitHub Desktop.

Select an option

Save chinchila/b765f842a7a299445be8a0101cec6b80 to your computer and use it in GitHub Desktop.
Multiplication GF(2**8) using matrices
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