2018百越杯Crypto RSA
题目给的是标准的RSA加密格式
#!/usr/bin/env python3
import gmpy2
from Crypto.Util.number import getPrime
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
from base64 import b64encode
flag = open('flag', 'r').read().strip() * 23
def encrypt(p, q, e, msg):
while True:
n = p * q
try:
phi = (p - 1)*(q - 1)
pubkey = RSA.construct((int(n), int(e)))
key = PKCS1_v1_5.new(pubkey)
enc = b64encode(key.encrypt(msg))
return enc
except:
p = gmpy2.next_prime(p**2 + q**2)
q = gmpy2.next_prime(2*p*q)
e = gmpy2.next_prime(e**2)
p = getPrime(128)
q = getPrime(128)
n = p*q
e = getPrime(64)
pubkey = RSA.construct((n, e))
with open('pubkey.pem', 'wb') as f:
f.write(pubkey.exportKey())
with open('flag.enc', 'wb') as g:
g.write(encrypt(p, q, e, flag.encode()))
这里掌握如何从标准公钥 密文中提取处理数据
exp:
import gmpy2
import libnum
import base64
from Crypto.PublicKey import RSA
from Crypto.Util.number import getPrime
from Crypto.Cipher import PKCS1_v1_5
pub = RSA.importKey(open(r'D:\浏览器下载\182_57791b62232b7838fc3eaec054aa9e1ce9b75b97\pubkey.pem').read())
c = open(r'D:\浏览器下载\182_57791b62232b7838fc3eaec054aa9e1ce9b75b97\flag.enc').read()
flag_decode = base64.b64decode(c)
n = pub.n
e = pub.e
#n=62078208638445817213739226854534031566665495569130972218813975279479576033261
#e=9850747023606211927
#此题注意p、q的位置不能交换,否则报错
q = 184333227921154992916659782580114145999
p = 336771668019607304680919844592337860739
def decrypt(p,q,e,msg):
while True:
n = p * q
try:
phi = (p - 1)*(q - 1)
d = libnum.invmod(e,phi)
private_key = RSA.construct((int(n), int(e), int(d), int(p), int(q)))
decipher = PKCS1_v1_5.new(private_key)
flag = decipher.decrypt(msg,None)
return flag
break
except:
p = gmpy2.next_prime(p**2 + q**2)
q = gmpy2.next_prime(2*p*q)
e = gmpy2.next_prime(e**2)
print (decrypt(p,q,e,flag_decode))