🛠️ToolsShed

RSA 密钥对生成器

生成 RSA-2048 或 RSA-4096 密钥对,以 PEM 格式导出。

Keys are generated entirely in your browser using Web Crypto API and never sent to any server.

常见问题

代码实现

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

# Generate RSA key pair
def generate_rsa_key_pair(
    key_size: int = 2048,
    public_exponent: int = 65537,
) -> tuple[rsa.RSAPrivateKey, rsa.RSAPublicKey]:
    private_key = rsa.generate_private_key(
        public_exponent=public_exponent,
        key_size=key_size,
        backend=default_backend(),
    )
    return private_key, private_key.public_key()

# Serialize to PEM
def private_key_to_pem(key: rsa.RSAPrivateKey, password: bytes | None = None) -> str:
    encryption = (
        serialization.BestAvailableEncryption(password)
        if password else serialization.NoEncryption()
    )
    return key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=encryption,
    ).decode()

def public_key_to_pem(key: rsa.RSAPublicKey) -> str:
    return key.public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo,
    ).decode()

# Sign and verify
def sign(message: bytes, private_key: rsa.RSAPrivateKey) -> bytes:
    return private_key.sign(message, padding.PKCS1v15(), hashes.SHA256())

def verify(message: bytes, signature: bytes, public_key: rsa.RSAPublicKey) -> bool:
    try:
        public_key.verify(signature, message, padding.PKCS1v15(), hashes.SHA256())
        return True
    except Exception:
        return False


if __name__ == "__main__":
    priv, pub = generate_rsa_key_pair(2048)
    print(private_key_to_pem(priv))
    print(public_key_to_pem(pub))

    msg = b"Hello, RSA!"
    sig = sign(msg, priv)
    print("Signature valid:", verify(msg, sig, pub))

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.