Source

libgf2 / src / libgf2 / gf2.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
'''
Created on Oct 5, 2013

@author: jmsachs

Copyright 2013 Jason M Sachs

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

'''

import numpy as np

def _bitlenlt(x,y):
    xy = x | y
    return (x << 1) < xy

def _gf2GaussJordan(A,b):
    '''
    solves for x, where Ax = b, in GF2.
    A is an n x n matrix; b is an n-element vector or an n x m matrix.
    '''
    n = A.shape[0]
    assert n == A.shape[1]
    try:
        s = b.shape
    except:
        s = (len(b),1)
    assert n == s[0]
    m = s[1]
    C = np.zeros((n,n+m),int)
    C[:,:n] = A
    if m == 1:
        C[:,n] = b
    else:
        C[:,n:] = b

    fails = []
    for j in xrange(n):
        # Find pivot
        p = None
        for i in xrange(j,n):
            if C[i,j] == 1:
                p = i
                break
        if p is None:
            fails.append(j)
            continue
        if p != j:
            C[p,:],C[j,:] = np.copy(C[j,:]),np.copy(C[p,:])
        for i in range(n):
            if i == j:
                continue
            if C[i,j] != 0:
                C[i,:] ^= C[j,:]
    if len(fails) > 0:
        raise ValueError('singular matrix: missing indices = %s' % fails)
    x = C[:,n:]
    return x

def _bitlencmp(x,y):
    xy = x | y
    if (x << 1) < xy:
        return -1
    elif (y << 1) <= x:
        return 1
    else:
        return 0    

def _bitlen(x):
    n = 0
    while x > 0:
        n += 1
        x >>= 1
    return n

def _degree(poly):
    return _bitlen(poly)-1

def _bitsOf(p,n=None):
    def helper(p,n):
        if n is None:
            while p != 0:
                yield p & 1
                p >>= 1
        else:
            for _ in range(n):
                yield p & 1
                p >>= 1
    return tuple(helper(p,n))

def _gf2mul(x,y):
    z = 0
    while x > 0:
        if (x & 1) != 0:
            z ^= y
        y <<= 1
        x >>= 1
    return z

def _gf2mod(x,m):
    nx = _bitlen(x)
    nm = _bitlen(m)
    i = nx - nm
    while i >= 0:
        xnew = x ^ (m << i)
        if xnew < x:
            x = xnew
        i -= 1
    return x

def _gf2divmod(x,d):
    nx = _bitlen(x)
    nd = _bitlen(d)
    i = nx - nd
    q = 0
    while i >= 0:
        xnew = x ^ (d << i)
        if xnew < x:
            q |= (1 << i)
            x = xnew
        i -= 1
    return (q,x)

def _gf2divmodvect(xvec,dvec):
    nx = _bitlen(xvec[0])
    nd = _bitlen(dvec[0])
    i = nx - nd
    q = 0
    test = 1 << (nx-1)
    while i >= 0:
        if (xvec[0] & test) != 0:
            xvec = [x ^ (d << i) for (x,d) in zip(xvec,dvec)]
            q |= (1 << i)
        i -= 1
        test >>= 1
    return (q,xvec)
        
def _gf2pow(x,k):
    z = 0
    while k > 0:
        if (k & 1) != 0:
            z = _gf2mul(z,x)
        x = _gf2mul(x,x)
        k >>= 1
    return z
        
def _gf2powmod(x,k,m):
    z = 1
    while k > 0:
        if (k & 1) != 0:
            z = _gf2mod(_gf2mul(z,x),m)
        x = _gf2mod(_gf2mul(x,x),m)
        k >>= 1
    return z

def _gf2lshiftmod(x,k,m):
    return _gf2mod(_gf2mul(x,_gf2powmod(2,k,m)),m)

def _gf2rshiftmod(x,k,m):
    r = m >> 1
    return _gf2mod(_gf2mul(x,_gf2powmod(r,k,m)),m)
            
def _gf2exteuc(a,b):
    # based on Blankenship's algorithm
    # return (g,x,y) such that g = gcd(a,b) and g = ax+by
    arow = [a,1,0]
    brow = [b,0,1]
    while True:
        (_,rrow) = _gf2divmodvect(arow, brow)
        if rrow[0] == 0:
            break
        arow = brow
        brow = rrow
    return tuple(brow)

def _exteuc(a,b):
    # based on Blankenship's algorithm
    # return (g,x,y) such that g = gcd(a,b) and g = ax+by
    arow = [a,1,0]
    brow = [b,0,1]
    while True:
        (q,r) = divmod(arow[0],brow[0])
        if r == 0:
            break
        rrow = [r,arow[1]-q*brow[1],arow[2]-q*brow[2]]
        arow = brow
        brow = rrow
    return tuple(brow)

def _gf2modinv(x,m):
    (r,y,_) = _gf2exteuc(x,m)
    if r != 1:
        raise ValueError('%x and %x are not relatively prime but have a common factor of %x' % (x,m,r))
    return y

def _modinv(x,m):
    (r,y,_) = _exteuc(x,m)
    if r != 1:
        raise ValueError('%d and %d are not relatively prime but have a common factor of %d' % (x,m,r))
    return y

def _calculateCofactors(factors):
    n = len(factors)
    cofactors = [1]*n
    for (i,factor) in enumerate(factors):
        cofactors = [x * factor if i != j else x for (j,x) in enumerate(cofactors)]    
    return tuple(cofactors) 

def _pullFactor(x, testFactor):
    n = 0
    fpower = 1
    while True:
        (q,r) = divmod(x, testFactor)
        if r != 0:
            break
        n += 1
        fpower *= testFactor
        x = q
    return (n,x,fpower)

def _calculateFactors(poly):
    n = _degree(poly)
    period = (1 << n) - 1
    m = period
    e1 = GF2Element(1, poly)
    if (e1 << m).value != 1:
        raise ValueError('%s not in primitive polynomial' % e1)
    factors = []
    def testFactors():
        for f in [3,5,7,11,13,17,19,23,29,31,37,41,43,47]:
            yield f
        f = 53
        while True:
            yield f
            f += 2
    for f in testFactors():
        if m < f*f:
            break
        (_,m,fpower) = _pullFactor(m,f)
        if fpower > 1:
            factors.append(fpower)
    if m > 1:
        factors.append(m)
    return factors
                
class GF2DiscreteLog(object):
    '''
    Facilitates computation of discrete logarithms, 
    after Clark and Weng (1994)
    "Maximal and Near-Maximal Shift Register Sequences:
    Efficient Event Counters and Easy Discrete Logarithms" 
    http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.44.118
    '''
    def __init__(self, poly, factors=None, maxtablesize=65536):
        self.poly = poly
        if factors is None:
            factors = _calculateFactors(poly)
        factors = tuple(factors)
        self.factors = factors
        cofactors = _calculateCofactors(factors)
        # verify factors
        e2 = GF2Element(1,poly)
        period = cofactors[0]*factors[0]
        self.period = period
        assert (e2 << period).value == 1
        lookup = []
        for (factor, cofactor) in zip(factors,cofactors):
            if factor > maxtablesize:
                raise ValueError('Factor %d exceeds maximum table size %d' % (factor, maxtablesize))
            g = e2 << cofactor
            gx = g
            glog = {1: 0}
            assert g.value != 1
            for i in xrange(1,factor):
                glog[gx.value] = i
                gx = gx * g
            assert gx.value == 1
            v = _modinv(cofactor, factor)
            lookup.append({'factor':factor, 'cofactor':cofactor, 'g':g, 'logtable':glog, 'v':v})
        self.lookup = lookup
    @staticmethod
    def _rem(x,item,period=None):
        cofactor = item['cofactor']
        y = x ** cofactor
        r = item['logtable'][y.value]
        if period is None:
            return r*cofactor*item['v']
        else:
            return (((r*cofactor)%period)*item['v'])%period
    def log(self, x):
        if isinstance(x, GF2Element):
            if x.poly != self.poly:
                raise ValueError('Element %s has a different polynomial than %x' % (x, self.poly))
        else:
            x = GF2Element(x,self.poly)
        r = [GF2DiscreteLog._rem(x,item,self.period) for item in self.lookup]
        return sum(r)%self.period 
            
class GF2(object):
    '''
    classdocs
    '''
    def __init__(self, x):
        self.value = x
    def __repr__(self):
        return 'GF2(0b{0:b})'.format(self.value)
    def __add__(self, other):
        return GF2(self.value ^ other.value)
    def __sub__(self, other):
        return GF2(self.value ^ other.value)
    def __mul__(self, other):
        return GF2(_gf2mul(self.value, other.value))
    def __mod__(self, other):
        return GF2(_gf2mod(self.value, other.value))
    def __eq__(self, other):
        return self.value == other.value
    def __ne__(self, other):
        return self.value != other.value
    def expmod(self, k, m):
        return GF2(_gf2powmod(self.value, k, m.value))
    
class GF2Element(object):
    def __init__(self, x, p):
        self.value = x
        self.poly = p
        n = _degree(p)
        self.fmt = 'GF2Element(0b{0:0%db},0x{1:x})' % n
    def _wrap(self, x):
        return GF2Element(_gf2mod(x,self.poly), self.poly)
    def _wrapraw(self, x):
        return GF2Element(x, self.poly)
    def __add__(self, other):
        return self._wrapraw(self.value ^ other.value)
    def __sub__(self, other):
        return self._wrapraw(self.value ^ other.value)
    def __mul__(self, other):
        return self._wrap(_gf2mul(self.value,other.value))
    def __pow__(self, k):
        return self._wrapraw(_gf2powmod(self.value,k,self.poly))
    def __lshift__(self, k):
        return self._wrapraw(_gf2lshiftmod(self.value,k,self.poly))
    def __rshift__(self, k):
        return self._wrapraw(_gf2rshiftmod(self.value,k,self.poly))
    def __repr__(self):
        return self.fmt.format(self.value, self.poly)
    def __eq__(self, other):
        return self.value == other.value and self.poly == other.poly 
    def __ne__(self, other):
        return self.value != other.value or self.poly != other.poly
   
if __name__ == '__main__':
    x1 = GF2(0b101101)
    x2 = GF2(0b110110)
    x3 = GF2(0b101)
    print x1+x2
    print x2
    print x3
    print x2*x3
    e1 = GF2Element(0b110, 137)
    print e1*e1
    print e1 << 6
    print e1 << 127
    print e1 >> 125
    e2 = GF2Element(0b100, 137)
    print e2 ** 2
    print e2 ** 3
    print e2 ** 127
    
    b = 0b11010011
    a = 0b101101
    (g,x,y) = _gf2exteuc(a,b)
    print g
    print x,y
    print _gf2mul(a,x) ^ _gf2mul(b,y)
    
    dlog5a = GF2DiscreteLog(0x23, [3,7])
    dlog5 = GF2DiscreteLog(0x25, [31])
    dlog8 = GF2DiscreteLog(0x11d, [3,5,17])
    dlog14 = GF2DiscreteLog(0x402b, [3,43,127])
    dlog16 = GF2DiscreteLog(0x1002d, [3,5,17,257])
    for dlog in [dlog5,dlog14]:
        e1 = GF2Element(1,dlog.poly)
        for i in xrange(21):
            x = e1 << i
            print 'log %s = %d' % (x, dlog.log(x)) 
    for dlog in [dlog14,dlog16]:
        e1 = GF2Element(1,dlog.poly)
        for i in xrange(0,3000,33):
            x = e1 << i
            print '%d: log %s = %d' % (i, x, dlog.log(x)) 
    e1 = GF2Element(1,dlog8.poly)
    print e1
    for i in xrange(9):
        print '1 << %d == %s' % (i,e1<<i)
    for i in xrange(100,109):
        print '1 << %d == %s' % (i,e1<<i)
    for i in xrange(200,209):
        print '1 << %d == %s' % (i,e1<<i)
    dlog14b = GF2DiscreteLog(0x402b)
    print dlog14b.factors
    dlog43 = GF2DiscreteLog(0x100000000065)
    print dlog43.factors
    
    A = np.matrix([[1,0,1,0,1],[0,1,1,0,1],[0,1,0,0,1],[1,0,0,0,0],[0,0,1,1,0]], int)
    b = _bitsOf(0b10010)
    x = _gf2GaussJordan(A, b)
    print b
    print x
    print ((A*np.matrix(x))&1).transpose()

    b2 = np.matrix([[1,0,0,1,0],[0,1,1,1,1],[1,1,0,0,0]]).transpose()
    x2 = _gf2GaussJordan(A, b2)
    print x2
    print ((A*np.matrix(x2))&1)

    I5 = np.matrix(np.eye(5,dtype=int))
    Ainv = _gf2GaussJordan(A,I5)
    print Ainv
    print A*Ainv&1