from Crypto.Util.number import * from Crypto.PublicKey import RSA from secret import s, FLAG def gen_prime(s): while True: r = getPrime(s) R = [r] t = int(5 * s / 2) + 1 for i in range(0, t): R.append(r + getRandomRange(0, 4 * s ** 2)) p = reduce(lambda a, b: a * b, R, 2) + 1 if isPrime(p): if len(bin(p)[2:]) == 1024: return p while True: p = gen_prime(s) q = gen_prime(s) n = p * q e = 65537 d = inverse(e, (p-1)*(q-1)) if len(bin(n)[2:]) == 2048: break msg = FLAG key = RSA.construct((long(n), long(e), long(d), long(p), long(p))) for _ in xrange(s): enc = key.encrypt(msg, 0)[0] msg = enc print(key.publickey().exportKey()) print('-' * 76) print(enc.encode('base64')) print ('-' * 76)
时间: 2024-04-10 22:34:33 浏览: 181
这段代码看起来是使用RSA加密算法生成密钥对,并进行信息加密的过程。以下是代码的完善建议:
1. 导入所需的模块和函数:
```python
from Crypto.Util.number import getPrime, inverse, getRandomRange
from Crypto.PublicKey import RSA
import base64
```
2. 修改 `long` 函数为 `int`:
```python
key = RSA.construct((int(n), int(e), int(d), int(p), int(p)))
```
3. 将 `xrange` 替换为 `range`(Python 3.x 不再支持 `xrange`):
```python
for _ in range(s):
```
4. 修改打印语句中的 `enc.encode('base64')` 为 `base64.b64encode(enc)`:
```python
print(base64.b64encode(enc))
```
完成这些修改后,代码应该如下所示:
```python
from Crypto.Util.number import getPrime, inverse, getRandomRange
from Crypto.PublicKey import RSA
import base64
from secret import s, FLAG
def gen_prime(s):
while True:
r = getPrime(s)
R = [r]
t = int(5 * s / 2) + 1
for i in range(0, t):
R.append(r + getRandomRange(0, 4 * s ** 2))
p = reduce(lambda a, b: a * b, R, 2) + 1
if isPrime(p):
if len(bin(p)[2:]) == 1024:
return p
while True:
p = gen_prime(s)
q = gen_prime(s)
n = p * q
e = 65537
d = inverse(e, (p-1)*(q-1))
if len(bin(n)[2:]) == 2048:
break
msg = FLAG
key = RSA.construct((int(n), int(e), int(d), int(p), int(p)))
for _ in range(s):
enc = key.encrypt(msg, 0)[0]
msg = enc
print(key.publickey().exportKey())
print('-' * 76)
print(base64.b64encode(enc))
print('-' * 76)
```
请注意,这只是对代码进行了一些基本的修正和完善,还可能存在其他需要优化的地方。
阅读全文