implementing-rsa-key-pair-management skill (Anthropic-Cybersecurity-Skills)

From Public Agent Wiki

What it does. Generates, stores, rotates, and manages RSA key pairs following NIST Part of mukul975/Anthropic-Cybersecurity-Skills (817 security skills) (mukul975/Anthropic-Cybersecurity-Skills).

Upstream mukul975/Anthropic-Cybersecurity-Skills
Skill file skills/implementing-rsa-key-pair-management/SKILL.md
License Apache-2.0 (skill folder LICENSE)
Author mukul975
Fetched 2026-09-10

Install

  • npx skills add mukul975/Anthropic-Cybersecurity-Skills --skill implementing-rsa-key-pair-management, or copy the skill folder into ~/.claude/skills/implementing-rsa-key-pair-management/.
  • Raw file: curl -sL https://raw.githubusercontent.com/mukul975/Anthropic-Cybersecurity-Skills/HEAD/skills/implementing-rsa-key-pair-management/SKILL.md

SKILL.md (verbatim)

name: implementing-rsa-key-pair-management
description: Generates, stores, rotates, and manages RSA key pairs following NIST
  SP 800-57 guidelines, covering serialization formats (PEM, DER, PKCS#8), passphrase
  protection, and key strength validation. Use when creating or rotating RSA keys
  for signatures, key exchange, or encryption, or when auditing existing keys for
  proper storage and NIST-compliant strength.
domain: cybersecurity
subdomain: cryptography
tags:
- cryptography
- rsa
- key-management
- pki
- asymmetric-encryption
version: '1.0'
author: mahipal
license: Apache-2.0
nist_csf:
- PR.DS-01
- PR.DS-02
- PR.DS-10
mitre_attack:
- T1600
- T1573
- T1553
- T1486

Implementing RSA Key Pair Management

Overview

RSA (Rivest-Shamir-Adleman) is the most widely deployed asymmetric cryptographic algorithm, used for digital signatures, key exchange, and encryption. This skill covers generating, storing, rotating, and managing RSA key pairs following NIST SP 800-57 key management guidelines, including key serialization formats (PEM, DER, PKCS#8), passphrase protection, and key strength validation.

When to Use

  • When deploying or configuring implementing rsa key pair management capabilities in your environment
  • When establishing security controls aligned to compliance requirements
  • When building or improving security architecture for this domain
  • When conducting security assessments that require this implementation

Prerequisites

  • Familiarity with cryptography concepts and tools
  • Access to a test or lab environment for safe execution
  • Python 3.8+ with required dependencies installed
  • Appropriate authorization for any testing activities

Objectives

  • Generate RSA key pairs with appropriate key sizes (2048, 3072, 4096 bits)
  • Serialize keys in PEM and DER formats with PKCS#8
  • Protect private keys with strong passphrase encryption
  • Implement key rotation with versioning
  • Extract public key components and fingerprints
  • Validate key strength and detect weak keys
  • Sign and verify data using RSA-PSS

Key Concepts

RSA Key Sizes and Security Strength

Key Size (bits) Security Strength (bits) Recommended Until
2048 112 2030
3072 128 Beyond 2030
4096 ~140 Beyond 2030

RSA Padding Schemes

Scheme Use Case Standard
OAEP Encryption PKCS#1 v2.2 (RFC 8017)
PSS Signatures PKCS#1 v2.2 (RFC 8017)
PKCS#1 v1.5 Legacy only Deprecated for new systems

Key Storage Formats

  • PEM: Base64-encoded with headers, human-readable
  • DER: Binary ASN.1 encoding, compact
  • PKCS#8: Standard for private key encapsulation
  • PKCS#12/PFX: Bundled key + certificate, password-protected

Security Considerations

  • Minimum 3072-bit keys for new deployments (NIST recommendation)
  • Always protect private keys with AES-256-CBC passphrase encryption
  • Use RSA-PSS for signatures (not PKCS#1 v1.5)
  • Use RSA-OAEP for encryption (not PKCS#1 v1.5)
  • Store private keys with restrictive file permissions (0600)
  • Implement key rotation at least annually

Validation Criteria

  • Key generation produces valid RSA key pair
  • Public key can be extracted from private key
  • Private key is protected with passphrase
  • RSA-PSS signature verification succeeds
  • Tampered signature verification fails
  • Key fingerprint is computed correctly
  • Key rotation maintains old key access for verification

Other files in this skill

assets/template.md (verbatim)

RSA Key Pair Management Template

Key Generation Checklist

  • Select key size (minimum 3072 bits for new deployments)
  • Generate key pair using secure random number generator
  • Protect private key with strong passphrase (AES-256)
  • Compute and record key fingerprint (SHA-256)
  • Set restrictive file permissions on private key
  • Store public key in accessible location
  • Document key metadata (size, algorithm, creation date)

Key Metadata Template

{
  "key_id": "rsa-prod-001",
  "algorithm": "RSA",
  "key_size": 4096,
  "public_exponent": 65537,
  "fingerprint_sha256": "<hex-digest>",
  "created_at": "2024-01-01T00:00:00Z",
  "expires_at": "2025-01-01T00:00:00Z",
  "usage": ["sign", "verify"],
  "owner": "security-team",
  "version": 1
}

Key Rotation Schedule

Environment Rotation Frequency Grace Period
Production 12 months 30 days
Staging 6 months 14 days
Development 3 months 7 days

Quick Reference

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

# Generate
key = rsa.generate_private_key(public_exponent=65537, key_size=4096)

# Sign (RSA-PSS)
signature = key.sign(data, padding.PSS(
    mgf=padding.MGF1(hashes.SHA256()),
    salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())

# Verify
key.public_key().verify(signature, data, padding.PSS(
    mgf=padding.MGF1(hashes.SHA256()),
    salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())

references/api-reference.md (verbatim)

API Reference: RSA Key Pair Lifecycle Management

Libraries Used

Library Purpose
cryptography RSA key generation, signing, verification, serialization
os Secure random bytes, file permissions
datetime Certificate validity periods and key rotation schedules
json Export key metadata and audit reports

Installation

pip install cryptography

Key Generation

Generate RSA Key Pair

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

def generate_rsa_keypair(key_size=4096):
    """Generate an RSA key pair. Use 2048 minimum, 4096 recommended."""
    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=key_size,
    )
    return private_key

Serialize Private Key (PEM, encrypted)

def save_private_key(private_key, filepath, passphrase):
    pem = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.BestAvailableEncryption(
            passphrase.encode()
        ),
    )
    with open(filepath, "wb") as f:
        f.write(pem)
    os.chmod(filepath, 0o600)  # Restrict permissions

Serialize Public Key

def save_public_key(private_key, filepath):
    public_key = private_key.public_key()
    pem = public_key.public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo,
    )
    with open(filepath, "wb") as f:
        f.write(pem)

Load Existing Key

def load_private_key(filepath, passphrase=None):
    with open(filepath, "rb") as f:
        private_key = serialization.load_pem_private_key(
            f.read(),
            password=passphrase.encode() if passphrase else None,
        )
    return private_key

def load_public_key(filepath):
    with open(filepath, "rb") as f:
        public_key = serialization.load_pem_public_key(f.read())
    return public_key

Signing and Verification

Sign Data

def sign_data(private_key, data):
    signature = private_key.sign(
        data,
        padding.PSS(
            mgf=padding.MGF1(hashes.SHA256()),
            salt_length=padding.PSS.MAX_LENGTH,
        ),
        hashes.SHA256(),
    )
    return signature

Verify Signature

from cryptography.exceptions import InvalidSignature

def verify_signature(public_key, data, signature):
    try:
        public_key.verify(
            signature,
            data,
            padding.PSS(
                mgf=padding.MGF1(hashes.SHA256()),
                salt_length=padding.PSS.MAX_LENGTH,
            ),
            hashes.SHA256(),
        )
        return True
    except InvalidSignature:
        return False

Encryption and Decryption

Encrypt with RSA-OAEP

def encrypt_data(public_key, plaintext):
    ciphertext = public_key.encrypt(
        plaintext,
        padding.OAEP(
            mgf=padding.MGF1(algorithm=hashes.SHA256()),
            algorithm=hashes.SHA256(),
            label=None,
        ),
    )
    return ciphertext

Decrypt with RSA-OAEP

def decrypt_data(private_key, ciphertext):
    plaintext = private_key.decrypt(
        ciphertext,
        padding.OAEP(
            mgf=padding.MGF1(algorithm=hashes.SHA256()),
            algorithm=hashes.SHA256(),
            label=None,
        ),
    )
    return plaintext

Key Audit and Rotation

Inspect Key Properties

def audit_key(filepath, passphrase=None):
    key = load_private_key(filepath, passphrase)
    pub = key.public_key()
    numbers = pub.public_numbers()
    return {
        "key_size": key.key_size,
        "compliant": key.key_size >= 2048,
        "recommended": key.key_size >= 4096,
        "public_exponent": numbers.e,
        "modulus_bits": numbers.n.bit_length(),
        "format": "PKCS8-PEM",
        "encrypted": passphrase is not None,
    }

Check Key Strength

def check_key_strength(key_path, passphrase=None):
    key = load_private_key(key_path, passphrase)
    findings = []
    if key.key_size < 2048:
        findings.append({
            "issue": f"Key size {key.key_size} bits is below minimum (2048)",
            "severity": "critical",
        })
    elif key.key_size < 4096:
        findings.append({
            "issue": f"Key size {key.key_size} bits — 4096 recommended",
            "severity": "low",
        })
    return {"key_size": key.key_size, "findings": findings}

Self-Signed Certificate Generation

from cryptography import x509
from cryptography.x509.oid import NameOID
from datetime import datetime, timedelta, timezone

def create_self_signed_cert(private_key, common_name, days_valid=365):
    subject = issuer = x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, common_name),
        x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Security Audit"),
    ])
    cert = (
        x509.CertificateBuilder()
        .subject_name(subject)
        .issuer_name(issuer)
        .public_key(private_key.public_key())
        .serial_number(x509.random_serial_number())
        .not_valid_before(datetime.now(timezone.utc))
        .not_valid_after(datetime.now(timezone.utc) + timedelta(days=days_valid))
        .sign(private_key, hashes.SHA256())
    )
    return cert

Output Format

{
  "key_path": "/etc/pki/private/server.key",
  "key_size": 4096,
  "public_exponent": 65537,
  "compliant": true,
  "encrypted": true,
  "certificate": {
    "common_name": "server.example.com",
    "not_before": "2025-01-15T00:00:00Z",
    "not_after": "2026-01-15T00:00:00Z",
    "serial_number": "ABC123..."
  },
  "findings": []
}

references/standards.md (verbatim)

Standards and References - RSA Key Pair Management

Primary Standards

NIST FIPS 186-5 - Digital Signature Standard (DSS)

RFC 8017 - PKCS #1: RSA Cryptography Specifications Version 2.2

RFC 5958 - Asymmetric Key Packages (PKCS#8 v2)

RFC 7468 - Textual Encodings of PKIX, PKCS, and CMS Structures

NIST SP 800-57 Part 1 Rev. 5 - Key Management

NIST SP 800-131A Rev. 2 - Transitioning Cryptographic Algorithms

Python Library References

cryptography (pyca/cryptography)

references/workflows.md (verbatim)

Workflows - RSA Key Pair Management

Workflow 1: Key Pair Generation

[Select Key Size] (3072 or 4096 bits)
      |
[Generate RSA Key Pair]
(public_exponent=65537)
      |
[Serialize Private Key]
(PEM/PKCS#8 with AES-256-CBC passphrase)
      |
[Extract and Serialize Public Key]
(PEM/SubjectPublicKeyInfo)
      |
[Compute Key Fingerprint]
(SHA-256 of DER-encoded public key)
      |
[Store Keys with Metadata]
(key_id, creation_date, algorithm, size)

Workflow 2: Digital Signature (RSA-PSS)

[Document/Data to Sign]
      |
[Hash Data] (SHA-256)
      |
[Load Private Key] (decrypt with passphrase)
      |
[RSA-PSS Sign]
(padding=PSS, mgf=MGF1(SHA256), salt_length=PSS.MAX_LENGTH)
      |
[Output Signature] (DER or Base64)

Workflow 3: Signature Verification

[Document + Signature + Public Key]
      |
[Load Public Key]
      |
[RSA-PSS Verify]
(same padding parameters as signing)
      |
[Valid?]
  YES --> Accept
  NO  --> Reject (data or signature tampered)

Workflow 4: Key Rotation

[Current Key Pair (version N)]
      |
[Generate New Key Pair (version N+1)]
      |
[Update Active Key Reference]
      |
[Archive Old Key Pair]
(mark as "decrypt/verify only")
      |
[After Grace Period: Destroy Old Private Key]
(keep public key for verification)

Workflow 5: RSA Encryption (OAEP)

[Plaintext] (max size depends on key and padding)
      |
[Load Recipient's Public Key]
      |
[RSA-OAEP Encrypt]
(padding=OAEP, mgf=MGF1(SHA256), algorithm=SHA256)
      |
[Ciphertext]

Back to mukul975/Anthropic-Cybersecurity-Skills (817 security skills) or Agent skills.