laojun001 发表于 2025-3-6 13:53

privkey.py

from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import utils
from cryptography.hazmat.backends import default_backend

# 生成一个RSA私钥
private_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048,
    backend=default_backend()
)

# 打印私钥的PEM格式(一种常见的私钥格式)
pem = private_key.private_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PrivateFormat.PKCS8,
    encryption_algorithm=serialization.NoEncryption()
).decode('utf-8')
print("Private Key (PEM):")
print(pem)

# 使用私钥进行签名
message = b"This is a secret message"
signature = private_key.sign(
    message,
    padding.PSS(
      mgf=padding.MGF1(hashes.SHA256()),
      salt_length=padding.PSS.MAX_LENGTH
    ),
    hashes.SHA256()
)

# 打印签名
print("\nSignature:")
print(signature.hex())

# 假设你已经有了对应的公钥,你可以使用公钥来验证签名
public_key = private_key.public_key()
pem_public = public_key.public_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PublicFormat.SubjectPublicKeyInfo
).decode('utf-8')
print("\nPublic Key (PEM):")
print(pem_public)

# 验证签名
try:
    public_key.verify(
      signature,
      message,
      padding.PSS(
            mgf=padding.MGF1(hashes.SHA256()),
            salt_length=padding.PSS.MAX_LENGTH
      ),
      hashes.SHA256()
    )
    print("\nSignature verification succeeded.")
except Exception as e:
    print(f"\nSignature verification failed: {e}")
页: [1]
查看完整版本: privkey.py