🛠️ToolsShed

RSA 鍵ペア生成ツール

RSA-2048またはRSA-4096鍵ペアをPEM形式で生成します。

鍵はブラウザ内でWeb Crypto APIを使用して生成され、サーバーには送信されません。

よくある質問

コード実装

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.