多项式模2运算及求逆元
在GF(28)域上,多项式相加相减结果相同,均为异或操作
x3+x2+1 对应的二进制为 1101 用整数表示就是 13
x2+x+1 对应的二进制为 0111 用整数表示就是 7
x3+x2+1 + x2+x+1 = x3+2x2+x+2 = x3+x 等同于 1101⊕0111 = 1010 用整数表示就是 10 既是 13⊕7
def add(a, b): return a^b def sub(a, b): return a^b
在GF(28)域上,多项式乘法
先模拟一下模2乘法运算
getBit的实现,乘法的实现
''' num为正整数并且小于32位 ''' def getBit(num): bit = 0 top_bit = 1 for i in range(32): if top_bit & num != 0: bit = i + 1 top_bit <<= 1 return bit
# a、b为二进制的整数表示 def multiply(a, b): len1 = getBit(a) # getBit函数返回 此整数表示的二进制的长度 len2 = getBit(b) # 假设 a=10 表示的二进制为 1010 则len1=4 res_len = int(len1 + len2 - 1) res = 0x0 for i in range(len1): temp = b * (a & 0x1) # 每次a的第一位与b相乘 temp <<= i # 结果左移 res ^= temp # 异或 模2 a >>= 1 return res
除法的实现
''' 多项式模2除法 X^3 / X^3+X+1 商 1 余 X+1 与整数相除略有不同 返回值为整数 (商, 余数) ''' def divide_and_mod(a, b): len1 = getBit(a) len2 = getBit(b) len3 = len1 - len2 if a < b: if len3 == 0: return (1, a^b) else: return (0, a) top_bit = 1; top_bit <<= (len1 - 1) b <<= (len1 - len2) quotient = 0 # 商 remainder = 0 # 余数 # 除法运算,最后不包含 for i in range(len3): quotient <<= 1 if top_bit & a != 0: # a最高位为1,则商为1 quotient ^= 1 a ^= b else: a ^= 0 top_bit >>= 1 b >>= 1 # 最后一次运算与之前的运算规则不同,需要比较大小 quotient <<= 1 if a < b: remainder = a else: quotient ^= 1 remainder = a ^ b return (quotient, remainder)
求最大公因式及逆元有欧几里得算法和扩展欧几里得算法得到
def divide(a, b): q, r = divide_and_mod(a, b) return q def mod(a, b): q, r = divide_and_mod(a, b) return r def gcd(a, b): r = mod(a, b) while r != 0: a = b b = r r = mod(a, b) return b def findModInverse(a, m): if gcd(a, m) != 1: return None x1, x2 = 1, 0 y1, y2 = 0, 1 r = 1 while r != 0: q = divide(m ,a) r = mod(m, a) x1, y1 = sub(x1, multiply(q, x2) ), sub(y1, multiply(q, y2)) x1, x2 = x2, x1 y1, y2 = y2, y1 m, a = a, r return y1
WE ARE ALL IN THE GUTTER, BUT SOME OF US ARE LOOKING AT THE STARS