已知信息
下载压缩包,包含一个flag.enc和pubkey.pem
flag.enc里面的即是密文
pubkey.pem里面的是n(模数)和e(公钥)
解题思路
- 解析pubkey.pem文件,得到n和e
- 质因数分解n,得到p(质因数)和q(质因数)
- 由p、q计算出phi(n)
- 由e、phi(n)计算出d(私钥)
- 并保存为pem格式
- 解密
使用python进行解题工作(我用conda作为包管理,python版本为3.8.5)
准备工作
(conda安装python环境自带openssl,如果没有自行安装)
安装pycryptodome、gmpy2两个包
openssl:可用于解析公钥(文件pubkey.pem),及解密
pycryptodome:可用于解析公钥及生成私钥(生成私钥需提供计算出的n,d)
gmpy2:求解d
具体步骤
1. 解析公钥
方法一:使用openssl
> openssl rsa -pubin -text -modulus -in pubkey.pem
RSA Public-Key: (256 bit)
Modulus:
00:c2:63:6a:e5:c3:d8:e4:3f:fb:97:ab:09:02:8f:
1a:ac:6c:0b:f6:cd:3d:70:eb:ca:28:1b:ff:e9:7f:
be:30:dd
Exponent: 65537 (0x10001)
Modulus=C2636AE5C3D8E43FFB97AB09028F1AAC6C0BF6CD3D70EBCA281BFFE97FBE30DD
writing RSA key
-----BEGIN PUBLIC KEY-----
MDwwDQYJKoZIhvcNAQEBBQADKwAwKAIhAMJjauXD2OQ/+5erCQKPGqxsC/bNPXDr
yigb/+l/vjDdAgMBAAE=
-----END PUBLIC KEY-----
得到e=65537
n=C2636AE5C3D8E43FFB97AB09028F1AAC6C0BF6CD3D70EBCA281BFFE97FBE30DD
n转换为10进制得到
n=87924348264132406875276140514499937145050893665602592992418171647042491658461
方法二:使用python的pycryptodome库
from Crypto.PublicKey import RSA
with open('pubkey.pem', 'r') as f:
key = f.read()
pubkey = RSA.import_key(key)
print('n:', pubkey.n)
print('e:', pubkey.e)
n: 87924348264132406875276140514499937145050893665602592992418171647042491658461
e: 65537
2. 质因数分解
打开网站http://www.factordb.com/分解
得到:
p = 275127860351348928173285174381581152299
q = 319576316814478949870590164193048041239
3. 计算出phi(n)
公式为:phi(n) = (p-1)*(q-1)
计算出phi(n) = 87924348264132406875276140514499937144456189488436765114374296308467862464924
4. 计算私钥
import gmpy2 as gp
e = 65537
u = 87924348264132406875276140514499937144456189488436765114374296308467862464924
d = gp.invert(e, u)
print(d)
10866948760844599168252082612378495977388271279679231539839049698621994994673
5. 输出私钥
from Crypto.PublicKey import RSA
n = 87924348264132406875276140514499937145050893665602592992418171647042491658461
e = 65537
d = 10866948760844599168252082612378495977388271279679231539839049698621994994673
prikey = RSA.construct((n, e, d), False)
with open('prikey.pem', 'wb') as f:
key = prikey.export_key()
print(key)
f.write(key)
# with open('prikey.pem', 'w') as f:
# key = prikey.export_key().decode('utf-8')
# print(key)
# f.write(key)
提供两种输出方式,经验证都能被openssl识别
6. 解密
openssl rsautl -decrypt -in flag.enc -inkey prikey.pem
答案就不写出来了