攻防世界-精选免费训练题-rsa | Crypto
利用下面的命令可以解出公钥
openssl rsa -pubin -in .\pubkey.pem -text -noout
from math import isqrt
from pathlib import Path
from Crypto.PublicKey import RSA
def fermat_factor(n: int) -> tuple[int, int]:
x = isqrt(n)
if x * x < n:
x += 1
while True:
y2 = x * x - n
y = isqrt(y2)
if y * y == y2:
return x - y, x + y
x += 1
def strip_pkcs1_v15(block: bytes) -> bytes:
if len(block) >= 2 and block[0] == 0 and block[1] == 2:
sep = block.find(b"\x00", 2)
if sep != -1:
return block[sep + 1 :]
return block.lstrip(b"\x00")
def extract_flag(data: bytes) -> str:
start = data.find(b"flag{")
if start != -1:
end = data.find(b"}", start)
if end != -1:
return data[start : end + 1].decode()
return data.decode(errors="ignore").strip()
def main() -> None:
base = Path(__file__).resolve().parent
public_key = RSA.import_key((base / "pubkey.pem").read_bytes())
n = public_key.n
e = public_key.e
p, q = fermat_factor(n)
phi = (p - 1) * (q - 1)
d = pow(e, -1, phi)
ciphertext = int.from_bytes((base / "flag.enc").read_bytes(), "big")
plaintext_int = pow(ciphertext, d, n)
block = plaintext_int.to_bytes((n.bit_length() + 7) // 8, "big")
message = strip_pkcs1_v15(block)
print(extract_flag(message))
if __name__ == "__main__":
main()

浙公网安备 33010602011771号