A Pure Python way to calculate the multiplicative inverse in gf(2^8) using Python 3

8k Views Asked by At

How would I implement the Multiplicative Inverse in GF2^8 in Python 3? My current functions look like this:

def gf_add(a, b):
    return a ^ b

def gf_mul(a, b, mod=0x1B):
    p = bytes(hex(0x00))
    for i in range(8):
        if (b & 1) != 0:
            p ^= a
        high_bit_set = bytes(a & 0x80)
        a <<= 1
        if high_bit_set != 0:
            a ^= mod
        b >>= 1
    return p
2

There are 2 best solutions below

5
On BEST ANSWER

Here is how I'd do it:

def gf_degree(a) :
  res = 0
  a >>= 1
  while (a != 0) :
    a >>= 1;
    res += 1;
  return res

def gf_invert(a, mod=0x1B) :
  v = mod
  g1 = 1
  g2 = 0
  j = gf_degree(a) - 8

  while (a != 1) :
    if (j < 0) :
      a, v = v, a
      g1, g2 = g2, g1
      j = -j

    a ^= v << j
    g1 ^= g2 << j

    a %= 256  # Emulating 8-bit overflow
    g1 %= 256 # Emulating 8-bit overflow

    j = gf_degree(a) - gf_degree(v)

  return g1

The function gf_degree calculates the degree of the polynomial, and gf_invert, naturally, inverts any element of GF(2^8), except 0, of course. The implementation of gf_invert follows a "text-book" algorithm on finding the multiplicative inverse of elements of a finite field.

Example

print(gf_invert(5))   # 82
print(gf_invert(1))   #  1
print(gf_invert(255)) # 28

Here is a live demo.

As mentioned in the comments you could also have used a logarithmic approach, or simply use brute force (trying every combination of multiplication).

0
On

You might look at my libgf2 module (which no one else actually uses) and use GF2Element:

from libgf2 import GF2Element

x = GF2Element(0x8, 0x11B)
x.inv 
# find the inverse of x^3 in the quotient ring GF(2)[x]/p(x)
# where p(x) = x^8 + x^4 + x^3 + x + 1 (0x11B in bit vector format)

See this blog article for more details.


Note: libgf2 is in Python 2.7 so you'd have to port to Python 3, but it's a fairly small library.