RSA 算法 python

python 同时被 3 个专栏收录
57 篇文章 0 订阅
5 篇文章 0 订阅
38 篇文章 0 订阅
def RSA(p,q,m):

    print(f"1: p: {p} q: {q} M: {m}")
    n = p*q
    print(f"2: n = p*q {p} *{q} = {n}")
    temp = (p-1)*(q-1)
    print(f"3: (p-1)*(q-1) = {p-1} *{q-1} = {temp}")
    e = 1
    print(f"4:e should be less than n and relatively prime to (p-1)*(q-1) = {p-1} *{q-1} = {temp}")
    for _ in range(1,n):
        if temp%_ is not 0:
            e = _
            break
    print(f"Hence, e is {e}")
    print("5: Here, we should find an integer d such that e*d mod((p-1)*(q-1)) = 1")
    d = 1
    for _ in range(1,temp):
       if e*_ % temp == 1:
        d = _
        print(f"Here d = {_}")
        print(f"we have e*d mod((p-1)*(q-1)) = {e*d} mod {temp} = 1")
    print(f"6: Public key = (e,n) = ({e},{n})")
    print(f"7: Private key = (d,n) = ({d},{n})")
    encrypted = m**e%n
    print(f"Encrypted message: c = m^e mod n = {m}^{e} mod {n} = {encrypted}")
    decrypted = encrypted**d%n
    print(f"Decrypted message: m = c^d mod n = {encrypted}^{d} mod {n} = {decrypted}")



RSA(p = 17,q = 31,m = 5)

# print(160%2)

运行结果:

1: p: 17 q: 31 M: 5
2: n = p*q 17 *31 = 527
3: (p-1)*(q-1) = 16 *30 = 480
4:e should be less than n and relatively prime to (p-1)*(q-1) = 16 *30 = 480
Hence, e is 7
5: Here, we should find an interger d such that e*d mod((p-1)*(q-1)) = 1
Here d = 343
we have e*d mod((p-1)*(q-1)) = 2401 mod 480 = 1
6: Public key = (e,n) = (7,527)
7: Private key = (d,n) = (343,527)
Encrypted message: c = m^e mod n = 5^7 mod 527 = 129
Decrypted message: m = c^d mod n = 129^343 mod 527 = 5
[Finished in 0.6s]

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值