Python 使用 nacl 生成密钥对
目录
使用的库: PyNaCl
安装依赖: pip install PyNaCl
from nacl.signing import SigningKey
from nacl.public import PrivateKey
def generate_curve25519_keypair():
# 生成私钥
private_key = PrivateKey.generate()
# 从私钥生成公钥
public_key = private_key.public_key
# 将私钥和公钥导出为字节形式,便于存储或传输
private_key_bytes = private_key.encode()
public_key_bytes = public_key.encode()
# 打印密钥
print(" ----- Curve25519 key pair -----")
print("Private Key (hex):", private_key_bytes.hex())
print("Public Key (hex):", public_key_bytes.hex())
# 适用于 JWT 签名
def generate_ed25519_keypair():
# 生成私钥
private_key = SigningKey.generate()
# 从私钥生成公钥
public_key = private_key.verify_key
# 将私钥和公钥导出为字节形式,便于存储或传输
private_key_bytes = private_key.encode()
public_key_bytes = public_key.encode()
# 打印密钥
print(" ----- Ed25519 key pair -----")
print("Private Key (hex):", private_key_bytes.hex())
print("Public Key (hex):", public_key_bytes.hex())
if __name__ == "__main__":
generate_curve25519_keypair()
generate_ed25519_keypair()