中國剩餘定理來解密RSA密文
阿新 • • 發佈:2020-12-17
參考
程式
快速冪指數取模函式和模逆函式:
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)