# FileName: verify
# Author: XXX
# Version: 0.0.3
# Date: 2023/5/2
# Description: 计算RSA的(公钥/私钥),并找出其他(公钥/私钥)。
# Others:
# 计算欧拉函数后的值,前一半的值与modulus前一半一样
# openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:512 -outform DER -out ./key.der
# openssl asn1parse -inform DER -in ./key.der -item ASN1_ANY
import math
import random
publicExponent = 0x010001
prime1 = 0x0E4E4866A7933FDD62A8DD15346798AC6E54BF1F637B58CBF95D822D4ACD14D53
prime2 = 0x0C639A901DFCFAF2A30319AE6CF6A03548DB187B6366DCC187DDA017F07F78339
# 计算公共模
modulus = prime1 * prime2
# 计算欧拉函数值
phi = ((prime1 - 1) * (prime2 - 1))
# 计算最小公倍数
lcm = math.lcm((prime1 - 1), (prime2 - 1))
# 计算最大公因数
gcd = math.gcd((prime1 - 1), (prime2 - 1))
print("公共模数值:",hex(modulus))
print("欧拉函数值:",hex(phi))
# 两个数的乘积 = 最大公因数 X 最小公倍数
print("最小公倍数:",hex(lcm))
print("最大公因数:",hex(gcd))
# RSA私钥
privateExponent = pow(publicExponent, -1, mod=phi)
print(" 公钥:", hex(publicExponent))
print(" 私钥:", hex(privateExponent))
serial = 1
print("以下是能解密[RSA公钥]加密密文的Key")
while serial <= gcd:
# 能解密[RSA公钥加密]密文的私钥Key
# 只要是lcm倍数的逆元都可以当作私钥Key
privateExponent_key = pow(publicExponent, -1, mod=(lcm * serial))
# 验证(公钥加密 = 其他私钥解密)
plaintext = random.getrandbits(128)
ciphertext = pow(plaintext, publicExponent, mod=modulus)
decryption = pow(ciphertext, privateExponent_key, mod=modulus)
if decryption == plaintext:
print("NO.%d 私钥:" % serial, hex(privateExponent_key))
else:
print("NO.%d 错误!" % serial)
serial = serial + 1
serial = 1
print("以下是能解密[RSA私钥]加密密文的Key")
while serial <= 30:
# 能解密[RSA私钥加密]密文的公钥Key
publicExponent_key = pow(privateExponent, -1, mod=(lcm * serial))
# 验证(私钥加密 = 其他公钥解密)
plaintext = random.getrandbits(128)
ciphertext = pow(plaintext, privateExponent, mod=modulus)
decryption = pow(ciphertext, publicExponent_key, mod=modulus)
if decryption == plaintext:
print("NO.%d 公钥:" % serial, hex(publicExponent_key))
else:
print("NO.%d 错误!" % serial)
serial = serial + 1
RSA 原理
最新推荐文章于 2024-09-09 00:00:00 发布