forked from hinomori_minori/RSA-Chat
44 lines
1.2 KiB
Python
44 lines
1.2 KiB
Python
# scripts/gen_keys.py
|
|
|
|
from cryptography.hazmat.primitives.asymmetric import rsa
|
|
from cryptography.hazmat.primitives import serialization
|
|
import os
|
|
|
|
KEY_DIR = os.path.join(os.path.dirname(__file__), '../config/keys')
|
|
PRIVATE_KEY_PATH = os.path.join(KEY_DIR, 'private_key.pem')
|
|
PUBLIC_KEY_PATH = os.path.join(KEY_DIR, 'public_key.pem')
|
|
|
|
|
|
def generate_keys():
|
|
# 确保目录存在
|
|
os.makedirs(KEY_DIR, exist_ok=True)
|
|
|
|
# 生成私钥
|
|
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
|
priv_bytes = private_key.private_bytes(
|
|
encoding=serialization.Encoding.PEM,
|
|
format=serialization.PrivateFormat.PKCS8,
|
|
encryption_algorithm=serialization.NoEncryption()
|
|
)
|
|
|
|
# 生成公钥
|
|
public_key = private_key.public_key()
|
|
pub_bytes = public_key.public_bytes(
|
|
encoding=serialization.Encoding.PEM,
|
|
format=serialization.PublicFormat.SubjectPublicKeyInfo
|
|
)
|
|
|
|
# 写入文件
|
|
with open(PRIVATE_KEY_PATH, 'wb') as f:
|
|
f.write(priv_bytes)
|
|
|
|
with open(PUBLIC_KEY_PATH, 'wb') as f:
|
|
f.write(pub_bytes)
|
|
|
|
print(f"[√] 私钥已保存到 {PRIVATE_KEY_PATH}")
|
|
print(f"[√] 公钥已保存到 {PUBLIC_KEY_PATH}")
|
|
|
|
|
|
if __name__ == '__main__':
|
|
generate_keys()
|