蒙哥马利模乘算法python实现

#计算 A*B*R-1 modM
def mon_mul(A, B, M):
    B_bin = bin(B)[2:]
    C = 0
    for a in B_bin[::-1]:
        if int(a): C += A
        if int(bin(C)[-1]): C += M
        C >>= 1
    if C >= M: C -= M
    return C


if __name__ == '__main__':
    R=2**257
    R2=2**514
    M=0x8542D69E4C044F18E8B92435BF6FF7DE457283915C45517D722EDB8B08F1DFC3
    a=0xE8B92435BF6FF
    b=0x5517D722EDB8B
    A=mon_mul(a,R2,M)
    B=mon_mul(b,R2,M)
    C=mon_mul(A,B,M)
    res=mon_mul(C,R,M)
    print("(a*b)modM="+'{:x}'.format(res))

你可能感兴趣的:(密码算法软件语言实现,python)