Class to perform GF(2^field_size) operations on elements represented as integers. Given that elements are represented as integers, addition is simply xor, and not exposed here.
| 83 | ] |
| 84 | |
| 85 | class GF2Ops: |
| 86 | """Class to perform GF(2^field_size) operations on elements represented as integers. |
| 87 | |
| 88 | Given that elements are represented as integers, addition is simply xor, and not |
| 89 | exposed here. |
| 90 | """ |
| 91 | |
| 92 | def __init__(self, field_size): |
| 93 | """Construct a GF2Ops object for the specified field size.""" |
| 94 | self.field_size = field_size |
| 95 | self._modulus = GF2_MODULI[field_size] |
| 96 | assert self._modulus is not None |
| 97 | |
| 98 | def mul2(self, x): |
| 99 | """Multiply x by 2 in GF(2^field_size).""" |
| 100 | x <<= 1 |
| 101 | if x >> self.field_size: |
| 102 | x ^= self._modulus |
| 103 | return x |
| 104 | |
| 105 | def mul(self, x, y): |
| 106 | """Multiply x by y in GF(2^field_size).""" |
| 107 | ret = 0 |
| 108 | while y: |
| 109 | if y & 1: |
| 110 | ret ^= x |
| 111 | y >>= 1 |
| 112 | x = self.mul2(x) |
| 113 | return ret |
| 114 | |
| 115 | def sqr(self, x): |
| 116 | """Square x in GF(2^field_size).""" |
| 117 | return self.mul(x, x) |
| 118 | |
| 119 | def inv(self, x): |
| 120 | """Compute the inverse of x in GF(2^field_size).""" |
| 121 | assert x != 0 |
| 122 | # Use the extended polynomial Euclidean GCD algorithm on (modulus, x), over GF(2). |
| 123 | # See https://en.wikipedia.org/wiki/Polynomial_greatest_common_divisor. |
| 124 | t1, t2 = 0, 1 |
| 125 | r1, r2 = self._modulus, x |
| 126 | r1l, r2l = self.field_size + 1, r2.bit_length() |
| 127 | while r2: |
| 128 | q = r1l - r2l |
| 129 | r1 ^= r2 << q |
| 130 | t1 ^= t2 << q |
| 131 | r1l = r1.bit_length() |
| 132 | if r1 < r2: |
| 133 | t1, t2 = t2, t1 |
| 134 | r1, r2 = r2, r1 |
| 135 | r1l, r2l = r2l, r1l |
| 136 | assert r1 == 1 |
| 137 | return t1 |
| 138 | |
| 139 | class TestGF2Ops(unittest.TestCase): |
| 140 | """Test class for basic arithmetic properties of GF2Ops.""" |
no outgoing calls
no test coverage detected