# -*- coding: utf-8 -*-
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend

# ----------------------------
# 📌 你的 RSA 公钥参数（十六进制）
# ----------------------------
n = int("85EF373C4FF983240BEB6E32FCCE2F0691A07A3B62F39BA1D9D796DE7B12B2893C7CEAD38FC80A16B8993250CDEBDE4DC70ED434B8ECB4F4FA78FDED242860A42387C8D197E0D287966BD72BE824DD5E85006690A161598B2E2E9AB215C4842F30BC0A4E37CA92C4CE3D3B511ABCCDC986AEC400783F1A62EEA43D25B0A76F7BCF2CB430402DF308CE7A6ADB5E9AD5CB821435C007792D537AF7D801512BE6F5C696C69CB71B3C54A81E59EE9B7BCBB8D202A5B674020D599D016CFAF9607BA088F283C1E15678DC1AB28F1CDAEBA2757792265B760E0818EFA6E32B78DEC22644579ED25DF32AF30E51024E8C8B21A923E240C83E880EDE5284392D280B793BC73F0FA98BE30DAE72311AA3372640BCA172534A09A65A059EC67CDD0034C30D04F65034E4217A7E55166026FFFF96D2049F460C18F3F1EFA0A809003BB6EA41C13511B48A42C15A0BC2570AC15B1849D7591F387B2BE1C9933B4DD667733CB17E4C83E6EF7F2CD4B1C1D414A95C78809B1F97DED266C66D5C22BE70940F28FD", 16)
e = int("26F5", 16)  # 公钥指数，通常是 0x10001 (65537)

# ----------------------------
# 🛠 构造 RSA 公钥对象
# ----------------------------
public_numbers = rsa.RSAPublicNumbers(e=e, n=n)
public_key = public_numbers.public_key(default_backend())

# ----------------------------
# 📤 1. 导出为 PEM 格式公钥（PKCS#1 或 PKCS#8，这里用 PKCS#8 更通用）
# ----------------------------
# 你可以选择以下两种格式之一：

# ✅ 方式一：PKCS#8 格式（推荐，更通用，支持各种场景，如 Java、API 等）
# pem_public_pkcs8 = public_key.public_bytes(
#     encoding=serialization.Encoding.PEM,
#     format=serialization.PublicFormat.SubjectPublicKeyInfo  # 即 PKCS#8
# )

# with open("rsa_public_key.pem", "wb") as pem_pub_file:
#     pem_pub_file.write(pem_public_pkcs8)

# ✅ 方式二（可选）：PKCS#1 格式（传统，仅含公钥，某些旧系统可能用）
pem_public_pkcs1 = public_key.public_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PublicFormat.PKCS1
)
with open("rsa_public_key.pem", "wb") as pem_pub_file:
    pem_pub_file.write(pem_public_pkcs1)


# ----------------------------
# 📤 2. 导出为 DER 格式公钥（二进制，PKCS#8）
# ----------------------------
# der_public_pkcs8 = public_key.public_bytes(
#     encoding=serialization.Encoding.DER,
#     format=serialization.PublicFormat.SubjectPublicKeyInfo  # PKCS#8
# )

# with open("rsa_public_key.der", "wb") as der_pub_file:
#     der_pub_file.write(der_public_pkcs8)

# 📤 3. 导出为 DER 格式公钥（二进制，PKCS#1）
der_public_pkcs1 = public_key.public_bytes(
    encoding=serialization.Encoding.DER,
    format=serialization.PublicFormat.PKCS1  # PKCS#8
)

with open("rsa_public_key.der", "wb") as der_pub_file:
    der_pub_file.write(der_public_pkcs1)
# ----------------------------
# ✅ 完成提示
# ----------------------------
print("✅ RSA 公钥已成功生成：")
print("     - PEM 格式公钥文件：rsa_public_key.pem")
print("     - DER 格式公钥文件：rsa_public_key.der")