题目:
p = getPrime(512)
q = gmpy2.next_prime(p)
from Crypto.Util.number import *
import gmpy2
flag = b'NSSCTF{******}'
p = getPrime(512)
q = gmpy2.next_prime(p)
n = p*q
e = 65537
phi = (p-1)*(q-1)
m = bytes_to_long(flag)
c = pow(m, e, n)
print(f'n = {n}')
print(f'e = {e}')
print(f'c = {c}')
'''
n = 115637000420176820831322601039129424406844427046456738651883381559357542765613732363445112111006849040385859313572091386802534464534403117787314180179562651607533039692795522388596550968316951090748054495960090527479954143448774136390568881020918710834542819900918984139672802889774720153267841255456602500057
e = 65537
c = 98161406745910866780822530171878255235776133393411573803496865047700715941955255328757920065032397556905095591171977170479344602512244671081108703687450560269408412671849929423399172588599903975793985819498354819305128607934552101433664794909855378636055525016664559476808490723554481335856183927702549281730
'''
代码学习:
p = getPrime(512)
q = gmpy2.next_prime(p)
生成一个512位的质数p;
生成大于p的下一位指数为q
(详细的在blog)
解题wp以及代码:
1.思路:
就是用开平方解其中一个素数,然后用n解另外一个素数,之后正常解RSA
2.wp
题目生成了一个512位的素数�p,随后使用next_prime函数获取�p的下一个素数作为�q,然后再做RSA算法,本题素数都比较大,我们没办法直接分解这个素数。但是我们发现�p和�q之间似乎有一些联系,他们太接近了,素数在自然数中其实没那么少,我们可以进行测试:
from Crypto.Util.number import *
import gmpy2
p = getPrime(512)
q = gmpy2.next_prime(p)
print(q-p)
你会发现大部分情况下二者的差值都小于1000,那么有这层关系我们如何解题呢。考虑�n的算术平方根为��=�sn=n,同时��sn也是�p和�q的几何平均值。此时则有
我们又有�,�q,p是相邻的素数,�p的下一个素数为�q,同理也有��sn的下一个素数也应该是�q,到这里你或许应该知道我们该怎么操作了。但是如何编写代码求平方根呢,这里我们借助gmpy2中的isqrt函数,在后续我们更多的会使用gmpy2而不是Crypto中的数学函数(因为二者速度不是一个量级)。
sn = isqrt(n)
q = next_prime(sn)
p = n // q
注意除的时候需要用整除。
3.代码:
from Crypto.Util.number import *
from gmpy2 import *
p = getPrime(512)
q = gmpy2.next_prime(p)
n = 115637000420176820831322601039129424406844427046456738651883381559357542765613732363445112111006849040385859313572091386802534464534403117787314180179562651607533039692795522388596550968316951090748054495960090527479954143448774136390568881020918710834542819900918984139672802889774720153267841255456602500057
e = 65537
c = 98161406745910866780822530171878255235776133393411573803496865047700715941955255328757920065032397556905095591171977170479344602512244671081108703687450560269408412671849929423399172588599903975793985819498354819305128607934552101433664794909855378636055525016664559476808490723554481335856183927702549281730
sn = isqrt(n)
q = next_prime(sn)
p = n // q
phi = (p-1)*(q-1)
d = invert(e, phi)
m = pow(c, d, n)
print(long_to_bytes(m))