github.com/jasoet/gopki@v1.15.0/keypair/algo/rsa.go (about) 1 // Package algo provides algorithm-specific implementations for cryptographic key pair generation. 2 // This file contains RSA key pair generation and management functionality with security best practices. 3 package algo 4 5 import ( 6 "crypto/rand" 7 "crypto/rsa" 8 "crypto/x509" 9 "encoding/pem" 10 "fmt" 11 "github.com/jasoet/gopki/keypair/format" 12 "strings" 13 14 "golang.org/x/crypto/ssh" 15 ) 16 17 // KeySize represents a secure RSA key size with predefined safe values only. 18 // This type enforces compile-time safety by restricting key sizes to security-approved values. 19 // Developers cannot create custom KeySize values - only predefined constants are allowed. 20 type KeySize struct { 21 bits int // unexported field - cannot be set directly by external code 22 } 23 24 // Predefined RSA key sizes with security and performance recommendations. 25 // These are the ONLY valid KeySize values that can be used for key generation. 26 var ( 27 KeySize2048 = KeySize{bits: 2048} // Minimum secure key size, good performance (recommended for most use cases) 28 KeySize3072 = KeySize{bits: 3072} // Enhanced security level, moderate performance impact 29 KeySize4096 = KeySize{bits: 4096} // Maximum security level, slower performance (recommended for long-term security) 30 ) 31 32 // Bits returns the key size in bits for internal cryptographic operations. 33 func (ks KeySize) Bits() int { 34 return ks.bits 35 } 36 37 // RSAKeyPair represents a generated RSA key pair containing both private and public keys. 38 // The public key is derived from the private key to ensure mathematical relationship. 39 type RSAKeyPair struct { 40 PrivateKey *rsa.PrivateKey // The RSA private key 41 PublicKey *rsa.PublicKey // The corresponding RSA public key 42 } 43 44 // GenerateRSAKeyPair generates a new RSA key pair with the specified key size. 45 // The function enforces a minimum key size of 2048 bits for security compliance. 46 // 47 // Parameters: 48 // - keySize: The desired key size in bits (minimum 2048) 49 // 50 // Returns: 51 // - *RSAKeyPair: The generated key pair 52 // - error: Error if key size is too small or generation fails 53 // 54 // Security considerations: 55 // - Uses crypto/rand.Reader for secure random number generation 56 // - Enforces minimum 2048-bit key size as per current security standards 57 // - Keys below 2048 bits are considered cryptographically weak 58 // 59 // Example: 60 // 61 // keyPair, err := GenerateRSAKeyPair(KeySize2048) 62 // if err != nil { 63 // log.Printf("RSA key generation failed: %v", err) 64 // } 65 func GenerateRSAKeyPair(keySize KeySize) (*RSAKeyPair, error) { 66 bits := keySize.Bits() 67 if bits < 2048 { 68 return nil, fmt.Errorf("RSA key size must be at least 2048 bits") 69 } 70 71 privateKey, err := rsa.GenerateKey(rand.Reader, bits) 72 if err != nil { 73 return nil, fmt.Errorf("failed to generate RSA private key: %w", err) 74 } 75 76 return &RSAKeyPair{ 77 PrivateKey: privateKey, 78 PublicKey: &privateKey.PublicKey, 79 }, nil 80 } 81 82 // PrivateKeyToPEM converts the RSA private key to PEM format using PKCS#8 encoding. 83 // PKCS#8 format provides better interoperability compared to PKCS#1. 84 // 85 // Returns: 86 // - PEM: PEM-encoded private key data 87 // - error: Error if marshaling or encoding fails 88 // 89 // The returned PEM block will have type "PRIVATE KEY" and contain the 90 // PKCS#8 encoded private key data. 91 // 92 // Example: 93 // 94 // pemData, err := keyPair.PrivateKeyToPEM() 95 // if err != nil { 96 // log.Printf("Private key PEM conversion failed: %v", err) 97 // } 98 func (kp *RSAKeyPair) PrivateKeyToPEM() (format.PEM, error) { 99 privateKeyBytes, err := x509.MarshalPKCS8PrivateKey(kp.PrivateKey) 100 if err != nil { 101 return nil, fmt.Errorf("failed to marshal private key: %w", err) 102 } 103 104 privateKeyPEM := pem.EncodeToMemory(&pem.Block{ 105 Type: "PRIVATE KEY", 106 Bytes: privateKeyBytes, 107 }) 108 109 return privateKeyPEM, nil 110 } 111 112 // PublicKeyToPEM converts the RSA public key to PEM format using PKIX encoding. 113 // PKIX format is the standard format for public key encoding in X.509 certificates. 114 // 115 // Returns: 116 // - PEM: PEM-encoded public key data 117 // - error: Error if marshaling or encoding fails 118 // 119 // The returned PEM block will have type "PUBLIC KEY" and contain the 120 // PKIX encoded public key data. 121 // 122 // Example: 123 // 124 // pemData, err := keyPair.PublicKeyToPEM() 125 // if err != nil { 126 // log.Printf("Public key PEM conversion failed: %v", err) 127 // } 128 func (kp *RSAKeyPair) PublicKeyToPEM() (format.PEM, error) { 129 publicKeyBytes, err := x509.MarshalPKIXPublicKey(kp.PublicKey) 130 if err != nil { 131 return nil, fmt.Errorf("failed to marshal public key: %w", err) 132 } 133 134 publicKeyPEM := pem.EncodeToMemory(&pem.Block{ 135 Type: "PUBLIC KEY", 136 Bytes: publicKeyBytes, 137 }) 138 139 return publicKeyPEM, nil 140 } 141 142 // RSAKeyPairFromPEM reconstructs an RSA key pair from PEM-encoded private key data. 143 // The function parses the private key and derives the public key from it. 144 // 145 // Parameters: 146 // - privateKeyPEM: PEM-encoded private key data in PKCS#8 format 147 // 148 // Returns: 149 // - *RSAKeyPair: The reconstructed key pair 150 // - error: Error if PEM decoding, parsing, or type assertion fails 151 // 152 // The function expects the PEM block to contain a PKCS#8 encoded private key. 153 // It will validate that the key is actually an RSA key before returning. 154 // 155 // Example: 156 // 157 // keyPair, err := RSAKeyPairFromPEM(pemData) 158 // if err != nil { 159 // log.Printf("Failed to reconstruct RSA key pair: %v", err) 160 // } 161 func RSAKeyPairFromPEM(privateKeyPEM format.PEM) (*RSAKeyPair, error) { 162 block, _ := pem.Decode(privateKeyPEM) 163 if block == nil { 164 return nil, fmt.Errorf("failed to decode PEM block") 165 } 166 167 privateKey, err := x509.ParsePKCS8PrivateKey(block.Bytes) 168 if err != nil { 169 return nil, fmt.Errorf("failed to parse private key: %w", err) 170 } 171 172 rsaPrivateKey, ok := privateKey.(*rsa.PrivateKey) 173 if !ok { 174 return nil, fmt.Errorf("private key is not an RSA key") 175 } 176 177 return &RSAKeyPair{ 178 PrivateKey: rsaPrivateKey, 179 PublicKey: &rsaPrivateKey.PublicKey, 180 }, nil 181 } 182 183 // PrivateKeyToDER converts the RSA private key to DER (Distinguished Encoding Rules) format. 184 // DER is a binary format that is more compact than PEM and faster to parse. 185 // 186 // Returns: 187 // - DER: DER-encoded private key data 188 // - error: Error if marshaling fails 189 // 190 // The function uses PKCS#8 encoding for maximum compatibility across different systems. 191 // DER format is typically 30% smaller than equivalent PEM format. 192 // 193 // Example: 194 // 195 // derData, err := keyPair.PrivateKeyToDER() 196 // if err != nil { 197 // log.Printf("DER conversion failed: %v", err) 198 // } 199 func (kp *RSAKeyPair) PrivateKeyToDER() (format.DER, error) { 200 derBytes, err := x509.MarshalPKCS8PrivateKey(kp.PrivateKey) 201 if err != nil { 202 return nil, fmt.Errorf("failed to marshal private key to DER: %w", err) 203 } 204 return derBytes, nil 205 } 206 207 // PublicKeyToDER converts the RSA public key to DER (Distinguished Encoding Rules) format. 208 // DER is a binary format that provides compact storage and fast parsing. 209 // 210 // Returns: 211 // - []byte: DER-encoded public key data 212 // - error: Error if marshaling fails 213 // 214 // The function uses PKIX encoding for standard compatibility. 215 // DER format is the binary equivalent of PEM without Base64 encoding and headers. 216 // 217 // Example: 218 // 219 // derData, err := keyPair.PublicKeyToDER() 220 // if err != nil { 221 // log.Printf("DER conversion failed: %v", err) 222 // } 223 func (kp *RSAKeyPair) PublicKeyToDER() (format.DER, error) { 224 derBytes, err := x509.MarshalPKIXPublicKey(kp.PublicKey) 225 if err != nil { 226 return nil, fmt.Errorf("failed to marshal public key to DER: %w", err) 227 } 228 return derBytes, nil 229 } 230 231 // PublicKeyToSSH converts the RSA public key to SSH public key format. 232 // The SSH format is used in authorized_keys files and for key identification. 233 // 234 // Parameters: 235 // - comment: Optional comment to include in the SSH key (commonly username@hostname) 236 // 237 // Returns: 238 // - SSH: SSH public key in format "ssh-rsa base64-key [comment]" 239 // - error: Error if conversion fails 240 // 241 // Example: 242 // 243 // sshKey, err := keyPair.PublicKeyToSSH("user@example.com") 244 // if err != nil { 245 // log.Printf("SSH conversion failed: %v", err) 246 // } 247 func (kp *RSAKeyPair) PublicKeyToSSH(comment string) (format.SSH, error) { 248 sshPubKey, err := ssh.NewPublicKey(kp.PublicKey) 249 if err != nil { 250 return "", fmt.Errorf("failed to convert to SSH public key: %w", err) 251 } 252 253 sshData := ssh.MarshalAuthorizedKey(sshPubKey) 254 sshStr := strings.TrimSpace(string(sshData)) 255 256 // Add comment if provided and not already present 257 if comment != "" && !strings.Contains(sshStr, comment) { 258 parts := strings.SplitN(sshStr, " ", 3) 259 if len(parts) >= 2 { 260 sshStr = parts[0] + " " + parts[1] + " " + comment 261 } 262 } 263 264 return format.SSH(sshStr), nil 265 } 266 267 // PrivateKeyToSSH converts the RSA private key to OpenSSH private key format. 268 // This format is used by OpenSSH for storing private keys, with optional passphrase protection. 269 // 270 // Parameters: 271 // - comment: Optional comment to embed in the key file 272 // - passphrase: Optional passphrase for key encryption (empty string for unencrypted) 273 // 274 // Returns: 275 // - SSH: OpenSSH private key in PEM-like format 276 // - error: Error if conversion fails 277 // 278 // Security note: Using a passphrase is recommended for private key storage. 279 // 280 // Example: 281 // 282 // sshKey, err := keyPair.PrivateKeyToSSH("my-key", "secure-passphrase") 283 // if err != nil { 284 // log.Printf("SSH conversion failed: %v", err) 285 // } 286 func (kp *RSAKeyPair) PrivateKeyToSSH(comment string, passphrase string) (format.SSH, error) { 287 var pemBlock *pem.Block 288 var err error 289 290 if passphrase == "" { 291 pemBlock, err = ssh.MarshalPrivateKey(kp.PrivateKey, comment) 292 } else { 293 pemBlock, err = ssh.MarshalPrivateKeyWithPassphrase(kp.PrivateKey, comment, []byte(passphrase)) 294 } 295 296 if err != nil { 297 return "", fmt.Errorf("failed to marshal SSH private key: %w", err) 298 } 299 300 sshPrivateKey := pem.EncodeToMemory(pemBlock) 301 return format.SSH(sshPrivateKey), nil 302 } 303 304 // RSAKeyPairFromDER reconstructs an RSA key pair from DER-encoded private key data. 305 // The function parses the private key and derives the public key from it. 306 // 307 // Parameters: 308 // - privateKeyDER: DER-encoded private key data in PKCS#8 format 309 // 310 // Returns: 311 // - *RSAKeyPair: The reconstructed key pair 312 // - error: Error if parsing or type assertion fails 313 // 314 // The function expects the DER data to contain a PKCS#8 encoded private key. 315 // It will validate that the key is actually an RSA key before returning. 316 // 317 // Example: 318 // 319 // keyPair, err := RSAKeyPairFromDER(derData) 320 // if err != nil { 321 // log.Printf("Failed to reconstruct RSA key pair from DER: %v", err) 322 // } 323 func RSAKeyPairFromDER(privateKeyDER format.DER) (*RSAKeyPair, error) { 324 privateKey, err := x509.ParsePKCS8PrivateKey(privateKeyDER) 325 if err != nil { 326 return nil, fmt.Errorf("failed to parse DER private key: %w", err) 327 } 328 329 rsaPrivateKey, ok := privateKey.(*rsa.PrivateKey) 330 if !ok { 331 return nil, fmt.Errorf("private key is not an RSA key") 332 } 333 334 return &RSAKeyPair{ 335 PrivateKey: rsaPrivateKey, 336 PublicKey: &rsaPrivateKey.PublicKey, 337 }, nil 338 } 339 340 // RSAKeyPairFromSSH reconstructs an RSA key pair from SSH-encoded private key data. 341 // The function parses the SSH private key and derives the public key from it. 342 // 343 // Parameters: 344 // - privateKeySSH: SSH-encoded private key data in OpenSSH format 345 // - passphrase: Passphrase for encrypted keys (empty string for unencrypted) 346 // 347 // Returns: 348 // - *RSAKeyPair: The reconstructed key pair 349 // - error: Error if parsing, decryption, or type assertion fails 350 // 351 // The function expects the SSH data to contain an OpenSSH formatted private key. 352 // It will validate that the key is actually an RSA key before returning. 353 // 354 // Example: 355 // 356 // keyPair, err := RSAKeyPairFromSSH(sshData, "passphrase") 357 // if err != nil { 358 // log.Printf("Failed to reconstruct RSA key pair from SSH: %v", err) 359 // } 360 func RSAKeyPairFromSSH(privateKeySSH format.SSH, passphrase string) (*RSAKeyPair, error) { 361 var rawKey interface{} 362 var err error 363 364 if passphrase == "" { 365 rawKey, err = ssh.ParseRawPrivateKey([]byte(privateKeySSH)) 366 } else { 367 rawKey, err = ssh.ParseRawPrivateKeyWithPassphrase([]byte(privateKeySSH), []byte(passphrase)) 368 } 369 370 if err != nil { 371 return nil, fmt.Errorf("failed to parse SSH private key: %w", err) 372 } 373 374 rsaPrivateKey, ok := rawKey.(*rsa.PrivateKey) 375 if !ok { 376 return nil, fmt.Errorf("SSH private key is not an RSA key, got %T", rawKey) 377 } 378 379 return &RSAKeyPair{ 380 PrivateKey: rsaPrivateKey, 381 PublicKey: &rsaPrivateKey.PublicKey, 382 }, nil 383 }