In my cryptography project, I have to deal with GF(2^8) arithmetic operations. Essentially, the sum operation in this this field (GF(2^8) is normal XOR operation, and the product operation a*b is (a*b) mod m(x). You can skip this mathematics part.
My job is to inverse a matrix 4×4 in GF(2^8). This is not difficult, but it’s too tedious to re-implement every matrix operations by hand. I would like to make use of this functionality (inverse a matrix) in numpy, but I was not able to make numpy use my operations between items of a matrix. Say, instead of performing adding between 2 items using ‘+’, I want it to perform XOR whenever ‘+’ operation is used.
I have created a class of my customer type, call GF28. The code can be found below:
class GF28(float):
def __init__(self, value):
self.value = value
def __add__(self, b):
if isinstance(b, GF28):
return GF28(ops.add(self.value, b.value))
else:
return GF28(ops.add(self.value, b))
__rsub__ = __isub__ = __sub__ = __radd__ = __iadd__ = __add__
def __mul__(self, b):
if isinstance(b, GF28):
return GF28(ops.mul(self.value, b.value))
else:
return GF28(ops.mul(self.value, b))
__rmul__ = __imul__ = __mul__
def __div__(self, b):
return self.__mul__(self.inv(b))
__rdiv__ = __idiv__ = __div__
def inv(self):
return GF28(ops.inv(self.value))
def __float__(self):
return self
And then I create a matrix of these GF28 items using:
a = array([[GF28(10), GF28(20), GF28(30)],
[GF28(12), GF28(21), GF28(4)],
[GF28(9), GF28(16), GF28(13)]])
It appears that only the float() cast function is being used, the rest is not touched at all.
Please help me to make this operation overriding work. Thanks a lot.
[edit] Performing basic matrix operation is already ok. If somebody could make this work with matrix inversion, I would really appreciate it. Thanks!
Declare
ato be ofdtypeobject:Then the type of the elements in the array are
GF28. For example: