Rabin加解密算法
详细代码如下:
# 空空
# dahouzi.cn
import random
from sympy import isprimedef decrypt_rabin(c, p, q):"""解密 Rabin 密文Args:c (int): 密文p (int): 素数 pq (int): 素数 qReturns:tuple: 解密结果 M1, M2, M3, M4"""n = p * q# 计算 m1, m2, m3, m4m1 = pow(c, (p + 1) // 4, p)m2 = (-m1) % pm3 = pow(c, (q + 1) // 4, q)m4 = (-m3) % q# 计算 a, ba = q * ModReverse(q, p)b = p * ModReverse(p, q)# 计算解密结果 M1, M2, M3, M4M1 = (a * m1 + b * m3) % nM2 = (a * m1 + b * m4) % nM3 = (a * m2 + b * m3) % nM4 = (a * m2 + b * m4) % nreturn M1, M2, M3, M4def ModReverse(a, n):"""计算模逆Args:a (int): 整数n (int): 模数Returns:int: a 在模 n 下的逆"""arr = [0, 1]gcd = EX_GCD(a, n, arr)if gcd == 1:return (arr[0] % n + n) % nelse:return -1def EX_GCD(a, b, arr):"""计算扩展欧几里得算法Args:a (int): 整数 ab (int): 整数 barr (list): 结果数组Returns:int: 最大公约数"""if b == 0:arr[0] = 1arr[1] = 0return ag = EX_GCD(b, a % b, arr)t = arr[0]arr[0] = arr[1]arr[1] = t - a // b * arr[1]return gdef rabin_encrypt(plaintext, p, q):"""Rabin 加密Args:plaintext (int): 明文p (int): 素数 pq (int): 素数 qReturns:int: 密文"""# 计算公钥 nn = p * q# 计算密文ciphertext = pow(plaintext, 2, n)return ciphertext# 示例用法p = 19
q = 23
plaintext = 183
ciphertext = rabin_encrypt(plaintext, p, q)
print("---------message-----------")
print("plaintext:", plaintext)
print("ciphertext:", ciphertext)print("---------public key[n]、private key[p、q]------------")
print("p:", p)
print("q:", q)
print("n:", p * q)
#print("---------公钥n、私钥p、q------------")# 解密
M1, M2, M3, M4 = decrypt_rabin(ciphertext, p, q)
print("---------Decrypt------------")
print("M1:", M1)
print("M2:", M2)
print("M3:", M3)
print("M4:", M4)
#print("---------解密------------")