中国剩余定理来解密RSA密文

参考

https://wonderful.blog.csdn.net/article/details/79671263?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.control&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.control



程序

快速幂指数取模函数和模逆函数:

def fast_power(base, power, MOD):
    result = 1
    while power > 0:
        # If power is odd
        if power % 2 == 1:
            result = (result * base) % MOD

        # Divide the power by 2
        power = power // 2
        # Multiply base to itself
        base = (base * base) % MOD
    return result
def gcd(a, b):
    while a != 0:
        a, b = b%a, a
    return b

# calc : b^(-1) mod m
def findModeInverse(b, m, show = True):
    if gcd(m,b) != 1:
        return None
    A1, A2, A3 = 1, 0, m
    B1, B2, B3 = 0, 1, b
    if show:
        print('-'*54)
        print("|{:^5}\t{:^5}\t{:^5}\t{:^5}\t{:^5}\t{:^5}\t{:^5}|".format("Q","A1","A2","A3","B1","B2","B3"))
        print("|{:^5}\t{:^5}\t{:^5}\t{:^5}\t{:^5}\t{:^5}\t{:^5}|".format("-", A1, A2, A3, B1, B2, B3))
    while True:
        Q = A3//B3
        B1,B2,B3,A1,A2,A3 = (A1-Q*B1),(A2-Q*B2),(A3-Q*B3),B1,B2,B3
        if show:
            print("|{:^5}\t{:^5}\t{:^5}\t{:^5}\t{:^5}\t{:^5}\t{:^5}|".format(Q, A1, A2, A3, B1, B2, B3))
        if B3 == 0:
            return None
        elif B3 == 1:
            break
    if show:
        print("-"*54)
    return B2%m

RSA系统参数

# RSA系统参数定义
p = 137 
q = 131
n = p*q
phi_n = (p-1)*(q-1)
e = 3
d = findModeInverse(e, phi_n, False)
# RSA 加密
M = 513
C = fast_power(M, e, n) # 密文 8363
# RSA解密
M_ = fast_power(C, d, n) # 解密明文
print("正常的解密结果:", M_)
# 中国剩余定理
dp = d % (p-1)
dq = d % (q-1)
Cp = C % p
Cq = C % q
qlnv = findModeInverse(q, p, False) # q对p的逆元 : 114
Mp = fast_power(Cp, dp, p) # 102
Mq = fast_power(Cq, dq, q) # 120
h = (qlnv * ((Mp - Mq) % p)) % p
_M = Mq + h*q
print("CRT的解密结果:", _M)

效果

posted @ 2020-12-17 13:52  爱吃砂糖橘的白龙  阅读(1935)  评论(0编辑  收藏  举报