NOTE: None of the following Python code has been tested. Furthermore, it's not real code but rather pseudo-code adapted to Python in order to explain a rigorous algorithm while making it readable as possible to people who don't know code or don't know Python.
Wikipedia has a very helpful algorithm for this and it is about the exact field you are dealing with. Let $\mathbf a$ be the first multiplicand and $\mathbf b$ be the second multiplicand. Now, initialize $\mathbf p=0$. At the end, the variable $\mathbf p$ will have the product. Wikipedia describes with more detail into the binary bit manipulations with this algorithm than I do, but here's the pseudo-Python code:
function multiply(a, b):
p = 0
# Loop through this eight times, once for each term in b:
repeat 8 times:
# If b's constant term is 1, then add p by a:
if coefficient(b, 1) == 1: p += a
# Now, we've taken care of this term by a.
# Therefore, get rid of the constant term of b and divide b by x:
b -= coefficient(b, 1)
b //= x
# carry stores the leading coefficient of a.
carry = coefficient(a, x^7)
# Now, get rid of the x^7 term and multiply a by x:
a -= coefficient(a, x^7)*x^7
a *= x
# Now, in order to deal with the loss of the x^7 term,
# which would now be an x^8 term since we multiplied by x,
# if carry had a value of 1, then we need to add x^4+x^3+x^2+1.
# We do this because x^8=x^4+x^3+x^2+1 in this field.
if carry == 1: a += x^4+x^3+x^2+1
# Finally, return the product:
return p
Now, we need to combine this with @stewbasic's idea of exponentiation by squaring:
function exponentiation(alpha, power):
answer = 1
# This represents alpha to the current power of 2.
# At the beginning, the first power of 2 is 2^0=1, so alpha^1=alpha.
alpha_to_power = alpha
# Loop through this eight times, once for each bit in power.
# We assume power is an eight bit number since alpha^256=1.
repeat 8 times:
# If the last bit of power is 1, then multiply alpha_to_power to answer:
if last_bit(power) == 1: answer = multiply(answer, alpha_to_power)
# Right shift power in order to get rid of the last bit:
power >>= 1
# Then, square alpha_to_power
# in order to advance to the next power of 2:
alpha_to_power = multiply(alpha_to_power, alpha_to_power)
# Finally, return the answer:
return answer
For some $GF(2^m)$, the multiply
function has a for
loop of m
and the exponentiation
function has a for
loop of m
in which the multiply
function is called 1-2 times each loop around. Therefore, this is a $O(m^2)$ algorithm, which is quite reasonable for your case of $m=8$.