python - 在Python中实现模幂的蒙哥马利阶梯法

标签 python cryptography rsa exponentiation modular-arithmetic

我正在尝试在 python 中实现 RSA 模幂的 mongomery-ladder 方法(因此 N=p•q,p,q 是素数),如下 paper 所示: montgomery-ladder pseudo code

我的代码如下所示:

  • x 代表底数,k 代表指数,N 代表模
# uses montgomery-ladder method for modular exponentiation
def montgomery_ladder(x, k, N):
    x %= N
    k %= N
    # getting the binary representation of k
    bin_k = list(map(int, bin(k)[2:]))
    # Initialize two variables to hold the intermediate results
    r0 = 1
    r1 = x

    # Loop through each bit of the binary exponent from most significant to the least significant
    for i in range(len(bin_k)):
        if bin_k[i] == 0:
            r1 = (r1 * r0) % N
            r0 = (r0 ** 2) % N
        else:
            r0 = (r0 * r1) % N
            r1 = (r1 ** 2) % N

    # The final result is in r0
    return r0

它不适用于非常大的数字,例如以下测试:

def main():
    x = 412432421343242134234233
    k = 62243535235312321213254235
    N = 10423451524353243462
    print(montgomery_ladder(x, k, N))
    print(pow(x, k, N))


if __name__ == '__main__':
    main()

产量:

7564492758006795519
179467895766154563

pow(x, k, n) 返回正确的答案,但我的函数没有返回正确的答案。 有什么想法吗?

最佳答案

删除开头的k %= N

关于python - 在Python中实现模幂的蒙哥马利阶梯法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77205133/

相关文章:

python - 如何在 Django 中使用 BeautifulSoup?

c# - .NET Core 2.0 RSA PlatformNotSupportedException

c# - 如何存储/检索 RSA 公钥/私钥

c# - System.Security.Cryptography.ProtectedData如何生成Unique Id

java - Rsa 算法生成 ? java中的字符

c# - RSA 导入手动 RSParams 因错误数据错误而失败

当顺序未知时迭代范围的 Pythonic 方式

python - npm 错误!吉普 错误!堆栈错误: Could not find any Visual Studio installation to use

encryption - 在 C# 中加密大字符串 - 最佳实践

Python 重新安装 --enable-unicode=ucs4 和 lxml undefined symbol : PyUnicodeUCS2_DecodeLatin1