github.com/jasoet/gopki@v1.15.0/keypair/keypair.go (about) 1 // Package keypair provides type-safe cryptographic key pair generation and management 2 // using Go generics for compile-time type safety. It supports RSA, ECDSA, and Ed25519 3 // algorithms with unified interfaces and format conversion utilities. 4 // 5 // The package uses generic constraints to ensure type safety at compile time: 6 // - Param interface constrains key generation parameters 7 // - KeyPair interface constrains key pair types 8 // - PublicKey and PrivateKey interfaces constrain key types 9 // 10 // Example usage: 11 // 12 // // Generate RSA key pair 13 // rsaKeys, err := GenerateKeyPair[algo.KeySize, *algo.RSAKeyPair](2048) 14 // 15 // // Generate ECDSA key pair 16 // ecdsaKeys, err := GenerateKeyPair[algo.ECDSACurve, *algo.ECDSAKeyPair](algo.P256) 17 // 18 // // Generate Ed25519 key pair 19 // ed25519Keys, err := GenerateKeyPair[algo.Ed25519Config, *algo.Ed25519KeyPair]("") 20 package keypair 21 22 import ( 23 "crypto/ecdsa" 24 "crypto/ed25519" 25 "crypto/elliptic" 26 "crypto/rsa" 27 "crypto/x509" 28 "encoding/pem" 29 "fmt" 30 "github.com/jasoet/gopki/keypair/algo" 31 "github.com/jasoet/gopki/keypair/format" 32 "os" 33 "path/filepath" 34 "strings" 35 36 "golang.org/x/crypto/ssh" 37 ) 38 39 // Param defines the constraint for key generation parameters. 40 // It accepts KeySize for RSA, ECDSACurve for ECDSA, or Ed25519Config for Ed25519. 41 type Param interface { 42 algo.KeySize | algo.ECDSACurve | algo.Ed25519Config 43 } 44 45 // KeyPair defines the constraint for key pair types. 46 // It accepts pointers to RSAKeyPair, ECDSAKeyPair, or Ed25519KeyPair. 47 type KeyPair interface { 48 *algo.RSAKeyPair | *algo.ECDSAKeyPair | *algo.Ed25519KeyPair 49 } 50 51 // PublicKey defines the constraint for public key types. 52 // It accepts pointers to RSA/ECDSA public keys or Ed25519 public key values. 53 type PublicKey interface { 54 *rsa.PublicKey | *ecdsa.PublicKey | ed25519.PublicKey 55 } 56 57 // PrivateKey defines the constraint for private key types. 58 // It accepts pointers to RSA/ECDSA private keys or Ed25519 private key values. 59 type PrivateKey interface { 60 *rsa.PrivateKey | *ecdsa.PrivateKey | ed25519.PrivateKey 61 } 62 63 // GenericPrivateKey represents any private key type for functions that need to work with multiple key types dynamically 64 type GenericPrivateKey any 65 66 // GenericPublicKey represents any public key type for functions that need to work with multiple key types dynamically 67 type GenericPublicKey any 68 69 // GenericKeyPair represents any keypair type for functions that need to work with multiple keypair types dynamically 70 type GenericKeyPair any 71 72 // KeyPairManager provides type-safe operations for cryptographic key pairs. 73 // It encapsulates a key pair and provides methods for format conversion, validation, 74 // comparison, and file I/O operations while maintaining type safety through generics. 75 // 76 // Type parameter: 77 // - K: KeyPair type (*algo.RSAKeyPair, *algo.ECDSAKeyPair, or *algo.Ed25519KeyPair) 78 // 79 // Example usage: 80 // 81 // // Generate an RSA key pair manager 82 // manager, err := Generate[algo.KeySize, *algo.RSAKeyPair](algo.KeySize2048) 83 // 84 // // Extract keys 85 // privateKey := manager.PrivateKey() 86 // publicKey := manager.PublicKey() 87 // 88 // // Convert to formats 89 // privatePEM, publicPEM, err := manager.ToPEM() 90 // 91 // // Save to files 92 // err = manager.SaveToPEM("private.pem", "public.pem") 93 type Manager[K KeyPair, P PrivateKey, B PublicKey] struct { 94 keyPair K 95 privateKey P 96 publicKey B 97 } 98 99 // KeyInfo contains metadata about a cryptographic key pair. 100 // This information is useful for identifying key properties and ensuring 101 // compatibility with different cryptographic operations. 102 type KeyInfo struct { 103 Algorithm string // "RSA", "ECDSA", "Ed25519" 104 KeySize int // Bits for RSA, curve size for ECDSA, 256 for Ed25519 105 Curve string // For ECDSA: "P-256", "P-384", "P-521", etc. Empty for RSA and Ed25519 106 } 107 108 // NewManager creates a new KeyPairManager instance from an existing key pair. 109 // This constructor wraps an existing key pair to provide the manager's functionality. 110 // 111 // Type parameter: 112 // - K: KeyPair type (*algo.RSAKeyPair, *algo.ECDSAKeyPair, or *algo.Ed25519KeyPair) 113 // 114 // Parameters: 115 // - keyPair: The key pair to wrap in the manager 116 // 117 // Returns a new KeyPairManager instance. 118 // 119 // Example: 120 // 121 // rsaKeyPair, _ := algo.GenerateRSAKeyPair(algo.KeySize2048) 122 // manager := NewManager(rsaKeyPair) 123 func NewManager[K KeyPair, P PrivateKey, B PublicKey](keyPair K, privateKey P, publicKey B) *Manager[K, P, B] { 124 return &Manager[K, P, B]{ 125 keyPair: keyPair, 126 privateKey: privateKey, 127 publicKey: publicKey, 128 } 129 } 130 131 // Generate creates a new KeyPairManager with a freshly generated key pair. 132 // This factory method generates a key pair using the specified parameters and wraps it in a manager. 133 // 134 // Type parameters: 135 // - T: Parameter type (algo.KeySize, algo.ECDSACurve, or algo.Ed25519Config) 136 // - K: KeyPair type (*algo.RSAKeyPair, *algo.ECDSAKeyPair, or *algo.Ed25519KeyPair) 137 // 138 // Parameters: 139 // - param: Algorithm-specific parameter (key size, curve, or config) 140 // 141 // Returns a new KeyPairManager instance or an error if generation fails. 142 // 143 // Examples: 144 // 145 // // Generate RSA key pair manager 146 // rsaManager, err := Generate[algo.KeySize, *algo.RSAKeyPair](algo.KeySize2048) 147 // 148 // // Generate ECDSA key pair manager 149 // ecdsaManager, err := Generate[algo.ECDSACurve, *algo.ECDSAKeyPair](algo.P256) 150 // 151 // // Generate Ed25519 key pair manager 152 // ed25519Manager, err := Generate[algo.Ed25519Config, *algo.Ed25519KeyPair]("") 153 func Generate[T Param, K KeyPair, P PrivateKey, B PublicKey](param T) (*Manager[K, P, B], error) { 154 switch par := any(param).(type) { 155 case algo.KeySize: 156 kp, err := algo.GenerateRSAKeyPair(par) 157 if err != nil { 158 return nil, fmt.Errorf("failed to generate RSA key pair: %w", err) 159 } 160 return NewManager(any(kp).(K), any(kp.PrivateKey).(P), any(kp.PublicKey).(B)), nil 161 case algo.ECDSACurve: 162 kp, err := algo.GenerateECDSAKeyPair(par) 163 if err != nil { 164 return nil, fmt.Errorf("failed to generate ECDSA key pair: %w", err) 165 } 166 return NewManager(any(kp).(K), any(kp.PrivateKey).(P), any(kp.PublicKey).(B)), nil 167 case algo.Ed25519Config: 168 kp, err := algo.GenerateEd25519KeyPair() 169 if err != nil { 170 return nil, fmt.Errorf("failed to generate Ed25519 key pair: %w", err) 171 } 172 return NewManager(any(kp).(K), any(kp.PrivateKey).(P), any(kp.PublicKey).(B)), nil 173 default: 174 return nil, fmt.Errorf("unsupported parameter type") 175 } 176 } 177 178 // KeyPair returns the underlying key pair managed by this instance. 179 // 180 // Returns the key pair of type K. 181 // 182 // Example: 183 // 184 // keyPair := manager.KeyPair() 185 func (m *Manager[K, P, B]) KeyPair() K { 186 return m.keyPair 187 } 188 189 // PrivateKey extracts the private key from the managed key pair. 190 // The returned type is determined by the key pair type and returned as interface{}. 191 // Use type assertion to convert to the specific key type you need. 192 // 193 // Returns the private key as interface{} or nil if extraction fails. 194 // 195 // Example: 196 // 197 // privateKey := manager.PrivateKey() 198 // if rsaKey, ok := privateKey.(*rsa.PrivateKey); ok { 199 // // Use RSA private key 200 // } 201 func (m *Manager[K, P, B]) PrivateKey() P { 202 return m.privateKey 203 } 204 205 // PublicKey extracts the public key from the managed key pair. 206 // The returned type is determined by the key pair type and returned as interface{}. 207 // Use type assertion to convert to the specific key type you need. 208 // 209 // Returns the public key as interface{} or nil if extraction fails. 210 // 211 // Example: 212 // 213 // publicKey := manager.PublicKey() 214 // if rsaKey, ok := publicKey.(*rsa.PublicKey); ok { 215 // // Use RSA public key 216 // } 217 func (m *Manager[K, P, B]) PublicKey() B { 218 return m.publicKey 219 } 220 221 // ToPEM converts the managed key pair to PEM format, returning both private and public keys. 222 // This method provides a convenient way to get both keys in PEM format in a single call. 223 // 224 // Returns: 225 // - privateKey: PEM-encoded private key in PKCS#8 format 226 // - publicKey: PEM-encoded public key in PKIX format 227 // - error: Error if conversion fails 228 // 229 // Example: 230 // 231 // privatePEM, publicPEM, err := manager.ToPEM() 232 // if err != nil { 233 // log.Printf("Failed to convert to PEM: %v", err) 234 // } 235 func (m *Manager[K, P, B]) ToPEM() (privateKey, publicKey format.PEM, err error) { 236 switch kp := any(m.keyPair).(type) { 237 case *algo.RSAKeyPair: 238 privateKey, err = PrivateKeyToPEM(kp.PrivateKey) 239 if err != nil { 240 return nil, nil, fmt.Errorf("failed to convert RSA private key to PEM: %w", err) 241 } 242 publicKey, err = PublicKeyToPEM(&kp.PrivateKey.PublicKey) 243 if err != nil { 244 return nil, nil, fmt.Errorf("failed to convert RSA public key to PEM: %w", err) 245 } 246 case *algo.ECDSAKeyPair: 247 privateKey, err = PrivateKeyToPEM(kp.PrivateKey) 248 if err != nil { 249 return nil, nil, fmt.Errorf("failed to convert ECDSA private key to PEM: %w", err) 250 } 251 publicKey, err = PublicKeyToPEM(&kp.PrivateKey.PublicKey) 252 if err != nil { 253 return nil, nil, fmt.Errorf("failed to convert ECDSA public key to PEM: %w", err) 254 } 255 case *algo.Ed25519KeyPair: 256 privateKey, err = PrivateKeyToPEM(kp.PrivateKey) 257 if err != nil { 258 return nil, nil, fmt.Errorf("failed to convert Ed25519 private key to PEM: %w", err) 259 } 260 publicKey, err = PublicKeyToPEM(kp.PublicKey) 261 if err != nil { 262 return nil, nil, fmt.Errorf("failed to convert Ed25519 public key to PEM: %w", err) 263 } 264 default: 265 return nil, nil, fmt.Errorf("unsupported key pair type") 266 } 267 268 return privateKey, publicKey, nil 269 } 270 271 // ToDER converts the managed key pair to DER format, returning both private and public keys. 272 // This method provides a convenient way to get both keys in DER format in a single call. 273 // 274 // Returns: 275 // - privateKey: DER-encoded private key in PKCS#8 format 276 // - publicKey: DER-encoded public key in PKIX format 277 // - error: Error if conversion fails 278 // 279 // Example: 280 // 281 // privateDER, publicDER, err := manager.ToDER() 282 // if err != nil { 283 // log.Printf("Failed to convert to DER: %v", err) 284 // } 285 func (m *Manager[K, P, B]) ToDER() (privateKey, publicKey format.DER, err error) { 286 switch kp := any(m.keyPair).(type) { 287 case *algo.RSAKeyPair: 288 privateKey, err = PrivateKeyToDER(kp.PrivateKey) 289 if err != nil { 290 return nil, nil, fmt.Errorf("failed to convert RSA private key to DER: %w", err) 291 } 292 publicKey, err = PublicKeyToDER(&kp.PrivateKey.PublicKey) 293 if err != nil { 294 return nil, nil, fmt.Errorf("failed to convert RSA public key to DER: %w", err) 295 } 296 case *algo.ECDSAKeyPair: 297 privateKey, err = PrivateKeyToDER(kp.PrivateKey) 298 if err != nil { 299 return nil, nil, fmt.Errorf("failed to convert ECDSA private key to DER: %w", err) 300 } 301 publicKey, err = PublicKeyToDER(&kp.PrivateKey.PublicKey) 302 if err != nil { 303 return nil, nil, fmt.Errorf("failed to convert ECDSA public key to DER: %w", err) 304 } 305 case *algo.Ed25519KeyPair: 306 privateKey, err = PrivateKeyToDER(kp.PrivateKey) 307 if err != nil { 308 return nil, nil, fmt.Errorf("failed to convert Ed25519 private key to DER: %w", err) 309 } 310 publicKey, err = PublicKeyToDER(kp.PublicKey) 311 if err != nil { 312 return nil, nil, fmt.Errorf("failed to convert Ed25519 public key to DER: %w", err) 313 } 314 default: 315 return nil, nil, fmt.Errorf("unsupported key pair type") 316 } 317 318 return privateKey, publicKey, nil 319 } 320 321 // ToSSH converts the managed key pair to SSH format, returning both private and public keys. 322 // This method provides a convenient way to get both keys in SSH format in a single call. 323 // 324 // Parameters: 325 // - comment: Optional comment to include in the SSH keys (commonly username@hostname) 326 // - passphrase: Optional passphrase for private key encryption (empty string for unencrypted) 327 // 328 // Returns: 329 // - privateKey: SSH-encoded private key in OpenSSH format 330 // - publicKey: SSH-encoded public key in authorized_keys format 331 // - error: Error if conversion fails 332 // 333 // Example: 334 // 335 // privateSSH, publicSSH, err := manager.ToSSH("user@host", "passphrase") 336 // if err != nil { 337 // log.Printf("Failed to convert to SSH: %v", err) 338 // } 339 func (m *Manager[K, P, B]) ToSSH(comment, passphrase string) (privateKey, publicKey format.SSH, err error) { 340 switch kp := any(m.keyPair).(type) { 341 case *algo.RSAKeyPair: 342 privateKey, err = PrivateKeyToSSH(kp.PrivateKey, comment, passphrase) 343 if err != nil { 344 return "", "", fmt.Errorf("failed to convert RSA private key to SSH: %w", err) 345 } 346 publicKey, err = PublicKeyToSSH(&kp.PrivateKey.PublicKey, comment) 347 if err != nil { 348 return "", "", fmt.Errorf("failed to convert RSA public key to SSH: %w", err) 349 } 350 case *algo.ECDSAKeyPair: 351 privateKey, err = PrivateKeyToSSH(kp.PrivateKey, comment, passphrase) 352 if err != nil { 353 return "", "", fmt.Errorf("failed to convert ECDSA private key to SSH: %w", err) 354 } 355 publicKey, err = PublicKeyToSSH(&kp.PrivateKey.PublicKey, comment) 356 if err != nil { 357 return "", "", fmt.Errorf("failed to convert ECDSA public key to SSH: %w", err) 358 } 359 case *algo.Ed25519KeyPair: 360 privateKey, err = PrivateKeyToSSH(kp.PrivateKey, comment, passphrase) 361 if err != nil { 362 return "", "", fmt.Errorf("failed to convert Ed25519 private key to SSH: %w", err) 363 } 364 publicKey, err = PublicKeyToSSH(kp.PublicKey, comment) 365 if err != nil { 366 return "", "", fmt.Errorf("failed to convert Ed25519 public key to SSH: %w", err) 367 } 368 default: 369 return "", "", fmt.Errorf("unsupported key pair type") 370 } 371 372 return privateKey, publicKey, nil 373 } 374 375 // LoadFromPEM creates a new KeyPairManager by loading a private key from a PEM file. 376 // The public key is automatically derived from the private key. 377 // 378 // Type parameter: 379 // - K: KeyPair type (*algo.RSAKeyPair, *algo.ECDSAKeyPair, or *algo.Ed25519KeyPair) 380 // 381 // Parameters: 382 // - privateKeyFile: Path to the PEM-encoded private key file 383 // 384 // Returns a new KeyPairManager instance or an error if loading fails. 385 // 386 // Example: 387 // 388 // manager, err := LoadFromPEM[*algo.RSAKeyPair]("private.pem") 389 // if err != nil { 390 // log.Printf("Failed to load key pair: %v", err) 391 // } 392 func LoadFromPEM[K KeyPair, P PrivateKey, B PublicKey](privateKeyFile string) (*Manager[K, P, B], error) { 393 // Read private key file 394 privateData, err := os.ReadFile(privateKeyFile) 395 if err != nil { 396 return nil, fmt.Errorf("failed to read private key file %s: %w", privateKeyFile, err) 397 } 398 399 return LoadFromPEMData[K, P, B](privateData) 400 } 401 402 // LoadFromDER creates a new KeyPairManager by loading a private key from a DER file. 403 // The public key is automatically derived from the private key. 404 // 405 // Type parameter: 406 // - K: KeyPair type (*algo.RSAKeyPair, *algo.ECDSAKeyPair, or *algo.Ed25519KeyPair) 407 // 408 // Parameters: 409 // - privateKeyFile: Path to the DER-encoded private key file 410 // 411 // Returns a new KeyPairManager instance or an error if loading fails. 412 // 413 // Example: 414 // 415 // manager, err := LoadFromDER[*algo.ECDSAKeyPair]("private.der") 416 // if err != nil { 417 // log.Printf("Failed to load key pair: %v", err) 418 // } 419 func LoadFromDER[K KeyPair, P PrivateKey, B PublicKey](privateKeyFile string) (*Manager[K, P, B], error) { 420 // Read private key file 421 privateData, err := os.ReadFile(privateKeyFile) 422 if err != nil { 423 return nil, fmt.Errorf("failed to read private key file %s: %w", privateKeyFile, err) 424 } 425 426 return LoadFromDERData[K, P, B](privateData) 427 } 428 429 // LoadFromSSH creates a new KeyPairManager by loading a private key from an SSH file. 430 // The public key is automatically derived from the private key. 431 // 432 // Type parameter: 433 // - K: KeyPair type (*algo.RSAKeyPair, *algo.ECDSAKeyPair, or *algo.Ed25519KeyPair) 434 // 435 // Parameters: 436 // - privateKeyFile: Path to the SSH-encoded private key file 437 // - passphrase: Passphrase for encrypted private keys (empty string for unencrypted) 438 // 439 // Returns a new KeyPairManager instance or an error if loading fails. 440 // 441 // Example: 442 // 443 // manager, err := LoadFromSSH[*algo.Ed25519KeyPair]("id_ed25519", "passphrase") 444 // if err != nil { 445 // log.Printf("Failed to load key pair: %v", err) 446 // } 447 func LoadFromSSH[K KeyPair, P PrivateKey, B PublicKey](privateKeyFile string, passphrase string) (*Manager[K, P, B], error) { 448 // Read private key file 449 privateData, err := os.ReadFile(privateKeyFile) 450 if err != nil { 451 return nil, fmt.Errorf("failed to read private key file %s: %w", privateKeyFile, err) 452 } 453 454 return LoadFromSSHData[K, P, B](format.SSH(privateData), passphrase) 455 } 456 457 // LoadFromPEMData creates a new KeyPairManager by parsing private key data in PEM format. 458 // The public key is automatically derived from the private key. 459 // 460 // Type parameter: 461 // - K: KeyPair type (*algo.RSAKeyPair, *algo.ECDSAKeyPair, or *algo.Ed25519KeyPair) 462 // 463 // Parameters: 464 // - privateKeyPEM: PEM-encoded private key data 465 // 466 // Returns a new KeyPairManager instance or an error if parsing fails. 467 // 468 // Example: 469 // 470 // manager, err := LoadFromPEMData[*algo.RSAKeyPair](pemData) 471 // if err != nil { 472 // log.Printf("Failed to load key pair: %v", err) 473 // } 474 func LoadFromPEMData[K KeyPair, P PrivateKey, B PublicKey](privateKeyPEM format.PEM) (*Manager[K, P, B], error) { 475 var zero K 476 477 // Parse private key to determine type 478 block, _ := pem.Decode(privateKeyPEM) 479 if block == nil { 480 return nil, fmt.Errorf("failed to decode private key PEM") 481 } 482 483 privateKey, err := x509.ParsePKCS8PrivateKey(block.Bytes) 484 if err != nil { 485 return nil, fmt.Errorf("failed to parse private key: %w", err) 486 } 487 488 // Reconstruct KeyPair based on private key type 489 switch priv := privateKey.(type) { 490 case *rsa.PrivateKey: 491 keyPair := &algo.RSAKeyPair{ 492 PrivateKey: priv, 493 PublicKey: &priv.PublicKey, 494 } 495 if result, ok := any(keyPair).(K); ok { 496 return NewManager(result, any(priv).(P), any(&priv.PublicKey).(B)), nil 497 } 498 case *ecdsa.PrivateKey: 499 keyPair := &algo.ECDSAKeyPair{ 500 PrivateKey: priv, 501 PublicKey: &priv.PublicKey, 502 } 503 if result, ok := any(keyPair).(K); ok { 504 return NewManager(result, any(priv).(P), any(&priv.PublicKey).(B)), nil 505 } 506 case ed25519.PrivateKey: 507 keyPair := &algo.Ed25519KeyPair{ 508 PrivateKey: priv, 509 PublicKey: priv.Public().(ed25519.PublicKey), 510 } 511 if result, ok := any(keyPair).(K); ok { 512 return NewManager(result, any(priv).(P), any(priv.Public().(ed25519.PublicKey)).(B)), nil 513 } 514 } 515 516 return nil, fmt.Errorf("key type mismatch or unsupported key type: expected %T", zero) 517 } 518 519 // LoadFromDERData creates a new KeyPairManager by parsing private key data in DER format. 520 // The public key is automatically derived from the private key. 521 // 522 // Type parameter: 523 // - K: KeyPair type (*algo.RSAKeyPair, *algo.ECDSAKeyPair, or *algo.Ed25519KeyPair) 524 // 525 // Parameters: 526 // - privateKeyDER: DER-encoded private key data 527 // 528 // Returns a new KeyPairManager instance or an error if parsing fails. 529 // 530 // Example: 531 // 532 // manager, err := LoadFromDERData[*algo.ECDSAKeyPair](derData) 533 // if err != nil { 534 // log.Printf("Failed to load key pair: %v", err) 535 // } 536 func LoadFromDERData[K KeyPair, P PrivateKey, B PublicKey](privateKeyDER format.DER) (*Manager[K, P, B], error) { 537 var zero K 538 539 // Parse private key to determine type 540 privateKey, err := x509.ParsePKCS8PrivateKey(privateKeyDER) 541 if err != nil { 542 return nil, fmt.Errorf("failed to parse private key: %w", err) 543 } 544 545 // Reconstruct KeyPair based on private key type 546 switch priv := privateKey.(type) { 547 case *rsa.PrivateKey: 548 keyPair := &algo.RSAKeyPair{ 549 PrivateKey: priv, 550 PublicKey: &priv.PublicKey, 551 } 552 if result, ok := any(keyPair).(K); ok { 553 return NewManager(result, any(priv).(P), any(&priv.PublicKey).(B)), nil 554 } 555 case *ecdsa.PrivateKey: 556 keyPair := &algo.ECDSAKeyPair{ 557 PrivateKey: priv, 558 PublicKey: &priv.PublicKey, 559 } 560 if result, ok := any(keyPair).(K); ok { 561 return NewManager(result, any(priv).(P), any(&priv.PublicKey).(B)), nil 562 } 563 case ed25519.PrivateKey: 564 keyPair := &algo.Ed25519KeyPair{ 565 PrivateKey: priv, 566 PublicKey: priv.Public().(ed25519.PublicKey), 567 } 568 if result, ok := any(keyPair).(K); ok { 569 return NewManager(result, any(priv).(P), any(priv.Public().(ed25519.PublicKey)).(B)), nil 570 } 571 } 572 573 return nil, fmt.Errorf("key type mismatch or unsupported key type: expected %T", zero) 574 } 575 576 // LoadFromSSHData creates a new KeyPairManager by parsing private key data in SSH format. 577 // The public key is automatically derived from the private key. 578 // 579 // Type parameter: 580 // - K: KeyPair type (*algo.RSAKeyPair, *algo.ECDSAKeyPair, or *algo.Ed25519KeyPair) 581 // 582 // Parameters: 583 // - privateKeySSH: SSH-encoded private key data 584 // - passphrase: Passphrase for encrypted private keys (empty string for unencrypted) 585 // 586 // Returns a new KeyPairManager instance or an error if parsing fails. 587 // 588 // Example: 589 // 590 // manager, err := LoadFromSSHData[*algo.Ed25519KeyPair](sshData, "passphrase") 591 // if err != nil { 592 // log.Printf("Failed to load key pair: %v", err) 593 // } 594 func LoadFromSSHData[K KeyPair, P PrivateKey, B PublicKey](privateKeySSH format.SSH, passphrase string) (*Manager[K, P, B], error) { 595 var zero K 596 var privateKey interface{} 597 var err error 598 599 // Parse private key to determine type 600 if passphrase == "" { 601 privateKey, err = ssh.ParseRawPrivateKey([]byte(privateKeySSH)) 602 } else { 603 privateKey, err = ssh.ParseRawPrivateKeyWithPassphrase([]byte(privateKeySSH), []byte(passphrase)) 604 } 605 606 if err != nil { 607 return nil, fmt.Errorf("failed to parse SSH private key: %w", err) 608 } 609 610 // Reconstruct KeyPair based on private key type 611 switch priv := privateKey.(type) { 612 case *rsa.PrivateKey: 613 keyPair := &algo.RSAKeyPair{ 614 PrivateKey: priv, 615 PublicKey: &priv.PublicKey, 616 } 617 if result, ok := any(keyPair).(K); ok { 618 return NewManager(result, any(priv).(P), any(&priv.PublicKey).(B)), nil 619 } 620 case *ecdsa.PrivateKey: 621 keyPair := &algo.ECDSAKeyPair{ 622 PrivateKey: priv, 623 PublicKey: &priv.PublicKey, 624 } 625 if result, ok := any(keyPair).(K); ok { 626 return NewManager(result, any(priv).(P), any(&priv.PublicKey).(B)), nil 627 } 628 case ed25519.PrivateKey: 629 keyPair := &algo.Ed25519KeyPair{ 630 PrivateKey: priv, 631 PublicKey: priv.Public().(ed25519.PublicKey), 632 } 633 if result, ok := any(keyPair).(K); ok { 634 return NewManager(result, any(priv).(P), any(priv.Public().(ed25519.PublicKey)).(B)), nil 635 } 636 case *ed25519.PrivateKey: 637 keyPair := &algo.Ed25519KeyPair{ 638 PrivateKey: *priv, 639 PublicKey: priv.Public().(ed25519.PublicKey), 640 } 641 if result, ok := any(keyPair).(K); ok { 642 return NewManager(result, any(*priv).(P), any(priv.Public().(ed25519.PublicKey)).(B)), nil 643 } 644 } 645 646 return nil, fmt.Errorf("key type mismatch or unsupported key type: expected %T", zero) 647 } 648 649 // GetInfo returns metadata about the managed key pair. 650 // This includes algorithm type, key size, and curve information for ECDSA keys. 651 // 652 // Returns KeyInfo struct with algorithm details or an error if analysis fails. 653 // 654 // Example: 655 // 656 // info, err := manager.GetInfo() 657 // if err != nil { 658 // log.Printf("Failed to get key info: %v", err) 659 // } 660 // fmt.Printf("Algorithm: %s, KeySize: %d", info.Algorithm, info.KeySize) 661 func (m *Manager[K, P, B]) GetInfo() (KeyInfo, error) { 662 switch kp := any(m.keyPair).(type) { 663 case *algo.RSAKeyPair: 664 return KeyInfo{ 665 Algorithm: "RSA", 666 KeySize: kp.PrivateKey.Size() * 8, // Convert bytes to bits 667 Curve: "", 668 }, nil 669 case *algo.ECDSAKeyPair: 670 var curve string 671 var keySize int 672 673 switch kp.PrivateKey.Curve { 674 case elliptic.P224(): 675 curve = "P-224" 676 keySize = 224 677 case elliptic.P256(): 678 curve = "P-256" 679 keySize = 256 680 case elliptic.P384(): 681 curve = "P-384" 682 keySize = 384 683 case elliptic.P521(): 684 curve = "P-521" 685 keySize = 521 686 default: 687 curve = "Unknown" 688 keySize = kp.PrivateKey.Curve.Params().BitSize 689 } 690 691 return KeyInfo{ 692 Algorithm: "ECDSA", 693 KeySize: keySize, 694 Curve: curve, 695 }, nil 696 case *algo.Ed25519KeyPair: 697 return KeyInfo{ 698 Algorithm: "Ed25519", 699 KeySize: 256, // Ed25519 keys are always 256 bits 700 Curve: "", 701 }, nil 702 default: 703 return KeyInfo{}, fmt.Errorf("unsupported key pair type") 704 } 705 } 706 707 // Validate verifies the mathematical relationship between the private and public keys. 708 // This ensures the key pair is valid and the public key correctly derives from the private key. 709 // 710 // Returns nil if the key pair is valid, or an error describing the validation failure. 711 // 712 // Example: 713 // 714 // err := manager.Validate() 715 // if err != nil { 716 // log.Printf("Key pair validation failed: %v", err) 717 // } 718 func (m *Manager[K, P, B]) Validate() error { 719 switch kp := any(m.keyPair).(type) { 720 case *algo.RSAKeyPair: 721 // Verify RSA key pair relationship 722 if kp.PrivateKey.PublicKey.N.Cmp(kp.PublicKey.N) != 0 { 723 return fmt.Errorf("RSA public key N does not match private key") 724 } 725 if kp.PrivateKey.PublicKey.E != kp.PublicKey.E { 726 return fmt.Errorf("RSA public key E does not match private key") 727 } 728 // Verify RSA private key components 729 if err := kp.PrivateKey.Validate(); err != nil { 730 return fmt.Errorf("RSA private key validation failed: %w", err) 731 } 732 case *algo.ECDSAKeyPair: 733 // Verify ECDSA key pair relationship 734 if kp.PrivateKey.PublicKey.X.Cmp(kp.PublicKey.X) != 0 { 735 return fmt.Errorf("ECDSA public key X does not match private key") 736 } 737 if kp.PrivateKey.PublicKey.Y.Cmp(kp.PublicKey.Y) != 0 { 738 return fmt.Errorf("ECDSA public key Y does not match private key") 739 } 740 if kp.PrivateKey.PublicKey.Curve != kp.PublicKey.Curve { 741 return fmt.Errorf("ECDSA public key curve does not match private key") 742 } 743 // Verify the key is on the curve 744 if !kp.PrivateKey.PublicKey.Curve.IsOnCurve(kp.PublicKey.X, kp.PublicKey.Y) { 745 return fmt.Errorf("ECDSA public key is not on the specified curve") 746 } 747 case *algo.Ed25519KeyPair: 748 // Verify Ed25519 key pair relationship 749 derivedPublic := kp.PrivateKey.Public().(ed25519.PublicKey) 750 if !derivedPublic.Equal(kp.PublicKey) { 751 return fmt.Errorf("Ed25519 public key does not match private key") 752 } 753 default: 754 return fmt.Errorf("unsupported key pair type") 755 } 756 757 return nil 758 } 759 760 // ValidatePrivateKey checks the validity and security standards of the private key. 761 // This includes verifying key size meets minimum security requirements. 762 // 763 // Returns nil if the private key is valid and secure, or an error describing the issue. 764 // 765 // Example: 766 // 767 // err := manager.ValidatePrivateKey() 768 // if err != nil { 769 // log.Printf("Private key validation failed: %v", err) 770 // } 771 func (m *Manager[K, P, B]) ValidatePrivateKey() error { 772 switch kp := any(m.keyPair).(type) { 773 case *algo.RSAKeyPair: 774 // Check minimum key size (2048 bits) 775 keySize := kp.PrivateKey.Size() * 8 776 if keySize < 2048 { 777 return fmt.Errorf("RSA key size %d bits is below minimum security requirement of 2048 bits", keySize) 778 } 779 // Validate RSA private key components 780 if err := kp.PrivateKey.Validate(); err != nil { 781 return fmt.Errorf("RSA private key validation failed: %w", err) 782 } 783 case *algo.ECDSAKeyPair: 784 // Check that private key is not zero 785 if kp.PrivateKey.D == nil || kp.PrivateKey.D.Sign() == 0 { 786 return fmt.Errorf("ECDSA private key is zero or nil") 787 } 788 // Check that private key is within valid range for the curve 789 n := kp.PrivateKey.Curve.Params().N 790 if kp.PrivateKey.D.Cmp(n) >= 0 { 791 return fmt.Errorf("ECDSA private key is outside valid range for curve") 792 } 793 case *algo.Ed25519KeyPair: 794 // Ed25519 keys are always 64 bytes (512 bits) for private key 795 if len(kp.PrivateKey) != ed25519.PrivateKeySize { 796 return fmt.Errorf("Ed25519 private key has invalid size: expected %d bytes, got %d", 797 ed25519.PrivateKeySize, len(kp.PrivateKey)) 798 } 799 default: 800 return fmt.Errorf("unsupported key pair type") 801 } 802 803 return nil 804 } 805 806 // CompareWith compares two key managers for mathematical equality. 807 // This method compares both the private and public keys to determine if they are identical. 808 // 809 // Parameters: 810 // - other: Another KeyPairManager to compare with 811 // 812 // Returns: 813 // - bool: true if both key pairs are mathematically identical, false otherwise 814 // 815 // Example: 816 // 817 // isEqual := manager1.CompareWith(manager2) 818 // if isEqual { 819 // fmt.Println("Key pairs are identical") 820 // } 821 func (m *Manager[K, P, B]) CompareWith(other *Manager[K, P, B]) bool { 822 return m.ComparePrivateKeys(other) && m.ComparePublicKeys(other) 823 } 824 825 // ComparePrivateKeys compares only the private keys of two key managers. 826 // This method determines if the private keys are mathematically identical. 827 // 828 // Parameters: 829 // - other: Another KeyPairManager to compare private keys with 830 // 831 // Returns: 832 // - bool: true if private keys are identical, false otherwise 833 // 834 // Example: 835 // 836 // arePrivateKeysEqual := manager1.ComparePrivateKeys(manager2) 837 func (m *Manager[K, P, B]) ComparePrivateKeys(other *Manager[K, P, B]) bool { 838 switch kp1 := any(m.keyPair).(type) { 839 case *algo.RSAKeyPair: 840 if kp2, ok := any(other.keyPair).(*algo.RSAKeyPair); ok { 841 return kp1.PrivateKey.Equal(kp2.PrivateKey) 842 } 843 case *algo.ECDSAKeyPair: 844 if kp2, ok := any(other.keyPair).(*algo.ECDSAKeyPair); ok { 845 return kp1.PrivateKey.Equal(kp2.PrivateKey) 846 } 847 case *algo.Ed25519KeyPair: 848 if kp2, ok := any(other.keyPair).(*algo.Ed25519KeyPair); ok { 849 return kp1.PrivateKey.Equal(kp2.PrivateKey) 850 } 851 } 852 return false 853 } 854 855 // ComparePublicKeys compares only the public keys of two key managers. 856 // This method determines if the public keys are mathematically identical. 857 // 858 // Parameters: 859 // - other: Another KeyPairManager to compare public keys with 860 // 861 // Returns: 862 // - bool: true if public keys are identical, false otherwise 863 // 864 // Example: 865 // 866 // arePublicKeysEqual := manager1.ComparePublicKeys(manager2) 867 func (m *Manager[K, P, B]) ComparePublicKeys(other *Manager[K, P, B]) bool { 868 switch kp1 := any(m.keyPair).(type) { 869 case *algo.RSAKeyPair: 870 if kp2, ok := any(other.keyPair).(*algo.RSAKeyPair); ok { 871 return kp1.PublicKey.Equal(kp2.PublicKey) 872 } 873 case *algo.ECDSAKeyPair: 874 if kp2, ok := any(other.keyPair).(*algo.ECDSAKeyPair); ok { 875 return kp1.PublicKey.Equal(kp2.PublicKey) 876 } 877 case *algo.Ed25519KeyPair: 878 if kp2, ok := any(other.keyPair).(*algo.Ed25519KeyPair); ok { 879 return kp1.PublicKey.Equal(kp2.PublicKey) 880 } 881 } 882 return false 883 } 884 885 // Clone creates a new KeyPairManager with the same key pair. 886 // This method creates a shallow copy of the KeyPairManager, sharing the same underlying key pair data. 887 // 888 // Returns: 889 // - *KeyPairManager[K]: A new KeyPairManager instance with the same key pair 890 // 891 // Note: This creates a shallow copy. The underlying cryptographic keys are shared between instances. 892 // If you need a deep copy with new cryptographic material, generate a new key pair instead. 893 // 894 // Example: 895 // 896 // clonedManager := manager.Clone() 897 // // clonedManager and manager share the same key pair data 898 func (m *Manager[K, P, B]) Clone() *Manager[K, P, B] { 899 return &Manager[K, P, B]{ 900 keyPair: m.keyPair, 901 } 902 } 903 904 // IsValid checks if the KeyPairManager is properly initialized. 905 // This method verifies that the KeyPairManager contains a valid key pair. 906 // 907 // Returns: 908 // - bool: true if the manager is initialized with a valid key pair, false otherwise 909 // 910 // This method checks: 911 // - KeyPairManager is not nil 912 // - Key pair is not nil 913 // - Key pair contains valid private and public keys 914 // 915 // Example: 916 // 917 // if manager.IsValid() { 918 // fmt.Println("Manager is ready to use") 919 // } else { 920 // fmt.Println("Manager is not properly initialized") 921 // } 922 func (m *Manager[K, P, B]) IsValid() bool { 923 if m == nil { 924 return false 925 } 926 927 switch kp := any(m.keyPair).(type) { 928 case *algo.RSAKeyPair: 929 return kp != nil && kp.PrivateKey != nil && kp.PublicKey != nil 930 case *algo.ECDSAKeyPair: 931 return kp != nil && kp.PrivateKey != nil && kp.PublicKey != nil 932 case *algo.Ed25519KeyPair: 933 return kp != nil && len(kp.PrivateKey) == ed25519.PrivateKeySize && len(kp.PublicKey) == ed25519.PublicKeySize 934 default: 935 return false 936 } 937 } 938 939 // SaveToPEM saves the managed key pair to separate PEM files. 940 // This method provides a convenient way to save both keys to files in PEM format. 941 // 942 // Parameters: 943 // - privateFile: Path where the private key will be saved 944 // - publicFile: Path where the public key will be saved 945 // 946 // File permissions: 947 // - Private key files: 0600 (readable/writable by owner only) 948 // - Public key files: 0600 (for consistency) 949 // - Directories: 0700 (accessible by owner only) 950 // 951 // Example: 952 // 953 // err := manager.SaveToPEM("private.pem", "public.pem") 954 // if err != nil { 955 // log.Printf("Failed to save key pair: %v", err) 956 // } 957 func (m *Manager[K, P, B]) SaveToPEM(privateFile, publicFile string) error { 958 privateKeyPEM, publicKeyPEM, err := m.ToPEM() 959 if err != nil { 960 return fmt.Errorf("failed to convert keys to PEM: %w", err) 961 } 962 963 if err := savePEMToFile(privateKeyPEM, privateFile); err != nil { 964 return fmt.Errorf("failed to save private key: %w", err) 965 } 966 967 if err := savePEMToFile(publicKeyPEM, publicFile); err != nil { 968 return fmt.Errorf("failed to save public key: %w", err) 969 } 970 971 return nil 972 } 973 974 // SaveToDER saves the managed key pair to separate DER files. 975 // This method provides a convenient way to save both keys to files in DER format. 976 // 977 // Parameters: 978 // - privateFile: Path where the private key will be saved 979 // - publicFile: Path where the public key will be saved 980 // 981 // File permissions: 982 // - Private key files: 0600 (readable/writable by owner only) 983 // - Public key files: 0600 (for consistency) 984 // - Directories: 0700 (accessible by owner only) 985 // 986 // Example: 987 // 988 // err := manager.SaveToDER("private.der", "public.der") 989 // if err != nil { 990 // log.Printf("Failed to save key pair: %v", err) 991 // } 992 func (m *Manager[K, P, B]) SaveToDER(privateFile, publicFile string) error { 993 privateKeyDER, publicKeyDER, err := m.ToDER() 994 if err != nil { 995 return fmt.Errorf("failed to convert keys to DER: %w", err) 996 } 997 998 if err := saveDERToFile(privateKeyDER, privateFile); err != nil { 999 return fmt.Errorf("failed to save private key: %w", err) 1000 } 1001 1002 if err := saveDERToFile(publicKeyDER, publicFile); err != nil { 1003 return fmt.Errorf("failed to save public key: %w", err) 1004 } 1005 1006 return nil 1007 } 1008 1009 // SaveToSSH saves the managed key pair to separate SSH files. 1010 // This method provides a convenient way to save both keys to files in SSH format. 1011 // 1012 // Parameters: 1013 // - privateFile: Path where the private key will be saved 1014 // - publicFile: Path where the public key will be saved 1015 // - comment: Optional comment to include in the SSH keys (commonly username@hostname) 1016 // - passphrase: Optional passphrase for private key encryption (empty string for unencrypted) 1017 // 1018 // File permissions: 1019 // - Private key files: 0600 (readable/writable by owner only) 1020 // - Public key files: 0600 (for consistency) 1021 // - Directories: 0700 (accessible by owner only) 1022 // 1023 // Example: 1024 // 1025 // err := manager.SaveToSSH("id_rsa", "id_rsa.pub", "user@host", "passphrase") 1026 // if err != nil { 1027 // log.Printf("Failed to save key pair: %v", err) 1028 // } 1029 func (m *Manager[K, P, B]) SaveToSSH(privateFile, publicFile string, comment, passphrase string) error { 1030 privateKeySSH, publicKeySSH, err := m.ToSSH(comment, passphrase) 1031 if err != nil { 1032 return fmt.Errorf("failed to convert keys to SSH: %w", err) 1033 } 1034 1035 if err := saveSSHToFile(privateKeySSH, privateFile); err != nil { 1036 return fmt.Errorf("failed to save private key: %w", err) 1037 } 1038 1039 if err := saveSSHToFile(publicKeySSH, publicFile); err != nil { 1040 return fmt.Errorf("failed to save public key: %w", err) 1041 } 1042 1043 return nil 1044 } 1045 1046 // PrivateKeyToPEM converts a private key to PEM-encoded format. 1047 // The key is marshaled using PKCS#8 format for maximum compatibility. 1048 // 1049 // Type parameter: 1050 // - T: Private key type (*rsa.PrivateKey, *ecdsa.PrivateKey, or ed25519.PrivateKey) 1051 // 1052 // Parameters: 1053 // - privateKey: The private key to convert 1054 // 1055 // Returns PEM-encoded data or an error if conversion fails. 1056 // 1057 // Example: 1058 // 1059 // pemData, err := PrivateKeyToPEM(rsaPrivateKey) 1060 // if err != nil { 1061 // log.Printf("Failed to convert private key: %v", err) 1062 // } 1063 func PrivateKeyToPEM[T PrivateKey](privateKey T) (format.PEM, error) { 1064 privateKeyBytes, err := x509.MarshalPKCS8PrivateKey(privateKey) 1065 if err != nil { 1066 return nil, fmt.Errorf("failed to marshal private key: %w", err) 1067 } 1068 1069 privateKeyPEM := pem.EncodeToMemory(&pem.Block{ 1070 Type: "PRIVATE KEY", 1071 Bytes: privateKeyBytes, 1072 }) 1073 1074 return privateKeyPEM, nil 1075 } 1076 1077 // PublicKeyToPEM converts a public key to PEM-encoded format. 1078 // The key is marshaled using PKIX format for standard compatibility. 1079 // 1080 // Type parameter: 1081 // - T: Public key type (*rsa.PublicKey, *ecdsa.PublicKey, or ed25519.PublicKey) 1082 // 1083 // Parameters: 1084 // - publicKey: The public key to convert 1085 // 1086 // Returns PEM-encoded data or an error if conversion fails. 1087 // 1088 // Example: 1089 // 1090 // pemData, err := PublicKeyToPEM(rsaPublicKey) 1091 // if err != nil { 1092 // log.Printf("Failed to convert public key: %v", err) 1093 // } 1094 func PublicKeyToPEM[T PublicKey](publicKey T) (format.PEM, error) { 1095 publicKeyBytes, err := x509.MarshalPKIXPublicKey(publicKey) 1096 if err != nil { 1097 return nil, fmt.Errorf("failed to marshal public key: %w", err) 1098 } 1099 1100 publicKeyPEM := pem.EncodeToMemory(&pem.Block{ 1101 Type: "PUBLIC KEY", 1102 Bytes: publicKeyBytes, 1103 }) 1104 1105 return publicKeyPEM, nil 1106 } 1107 1108 // PrivateKeyToDER converts a private key to DER-encoded format. 1109 // The key is marshaled using PKCS#8 format for maximum compatibility. 1110 // 1111 // Type parameter: 1112 // - T: Private key type (*rsa.PrivateKey, *ecdsa.PrivateKey, or ed25519.PrivateKey) 1113 // 1114 // Parameters: 1115 // - privateKey: The private key to convert 1116 // 1117 // Returns DER-encoded data or an error if conversion fails. 1118 // 1119 // Example: 1120 // 1121 // derData, err := PrivateKeyToDER(rsaPrivateKey) 1122 // if err != nil { 1123 // log.Printf("Failed to convert private key: %v", err) 1124 // } 1125 func PrivateKeyToDER[T PrivateKey](privateKey T) (format.DER, error) { 1126 privateKeyBytes, err := x509.MarshalPKCS8PrivateKey(privateKey) 1127 if err != nil { 1128 return nil, fmt.Errorf("failed to marshal private key: %w", err) 1129 } 1130 1131 return privateKeyBytes, nil 1132 } 1133 1134 // PublicKeyToDER converts a public key to DER-encoded format. 1135 // The key is marshaled using PKIX format for standard compatibility. 1136 // 1137 // Type parameter: 1138 // - T: Public key type (*rsa.PublicKey, *ecdsa.PublicKey, or ed25519.PublicKey) 1139 // 1140 // Parameters: 1141 // - publicKey: The public key to convert 1142 // 1143 // Returns DER-encoded data or an error if conversion fails. 1144 // 1145 // Example: 1146 // 1147 // derData, err := PublicKeyToDER(rsaPublicKey) 1148 // if err != nil { 1149 // log.Printf("Failed to convert public key: %v", err) 1150 // } 1151 func PublicKeyToDER[T PublicKey](publicKey T) (format.DER, error) { 1152 publicKeyBytes, err := x509.MarshalPKIXPublicKey(publicKey) 1153 if err != nil { 1154 return nil, fmt.Errorf("failed to marshal public key: %w", err) 1155 } 1156 1157 return publicKeyBytes, nil 1158 } 1159 1160 // PrivateKeyToSSH converts a private key to SSH-encoded format. 1161 // The key is marshaled using OpenSSH private key format with optional passphrase protection. 1162 // 1163 // Type parameter: 1164 // - T: Private key type (*rsa.PrivateKey, *ecdsa.PrivateKey, or ed25519.PrivateKey) 1165 // 1166 // Parameters: 1167 // - privateKey: The private key to convert 1168 // - comment: Optional comment to embed in the key file 1169 // - passphrase: Optional passphrase for key encryption (empty string for unencrypted) 1170 // 1171 // Returns SSH-encoded data or an error if conversion fails. 1172 // 1173 // Security note: Using a passphrase is recommended for private key storage. 1174 // 1175 // Example: 1176 // 1177 // sshData, err := PrivateKeyToSSH(rsaPrivateKey, "my-key", "secure-passphrase") 1178 // if err != nil { 1179 // log.Printf("Failed to convert private key: %v", err) 1180 // } 1181 func PrivateKeyToSSH[T PrivateKey](privateKey T, comment string, passphrase string) (format.SSH, error) { 1182 var pemBlock *pem.Block 1183 var err error 1184 1185 if passphrase == "" { 1186 pemBlock, err = ssh.MarshalPrivateKey(privateKey, comment) 1187 } else { 1188 pemBlock, err = ssh.MarshalPrivateKeyWithPassphrase(privateKey, comment, []byte(passphrase)) 1189 } 1190 1191 if err != nil { 1192 return "", fmt.Errorf("failed to marshal SSH private key: %w", err) 1193 } 1194 1195 sshPrivateKey := pem.EncodeToMemory(pemBlock) 1196 return format.SSH(sshPrivateKey), nil 1197 } 1198 1199 // PublicKeyToSSH converts a public key to SSH-encoded format. 1200 // The key is marshaled using SSH public key format suitable for authorized_keys files. 1201 // 1202 // Type parameter: 1203 // - T: Public key type (*rsa.PublicKey, *ecdsa.PublicKey, or ed25519.PublicKey) 1204 // 1205 // Parameters: 1206 // - publicKey: The public key to convert 1207 // - comment: Optional comment to include in the SSH key (commonly username@hostname) 1208 // 1209 // Returns SSH-encoded data in format "ssh-rsa base64-key [comment]" or an error if conversion fails. 1210 // 1211 // Example: 1212 // 1213 // sshData, err := PublicKeyToSSH(rsaPublicKey, "user@example.com") 1214 // if err != nil { 1215 // log.Printf("Failed to convert public key: %v", err) 1216 // } 1217 func PublicKeyToSSH[T PublicKey](publicKey T, comment string) (format.SSH, error) { 1218 sshPubKey, err := ssh.NewPublicKey(publicKey) 1219 if err != nil { 1220 return "", fmt.Errorf("failed to convert to SSH public key: %w", err) 1221 } 1222 1223 sshData := ssh.MarshalAuthorizedKey(sshPubKey) 1224 sshStr := strings.TrimSpace(string(sshData)) 1225 1226 // Add comment if provided and not already present 1227 if comment != "" && !strings.Contains(sshStr, comment) { 1228 parts := strings.SplitN(sshStr, " ", 3) 1229 if len(parts) >= 2 { 1230 sshStr = parts[0] + " " + parts[1] + " " + comment 1231 } 1232 } 1233 1234 return format.SSH(sshStr), nil 1235 } 1236 1237 // PrivateKeyFromSSH parses a private key from SSH-encoded data. 1238 // The function handles OpenSSH format with optional passphrase decryption. 1239 // 1240 // Type parameter: 1241 // - T: Expected private key type (*rsa.PrivateKey, *ecdsa.PrivateKey, or ed25519.PrivateKey) 1242 // 1243 // Parameters: 1244 // - sshData: SSH-encoded private key data 1245 // - passphrase: Passphrase for encrypted keys (empty string for unencrypted) 1246 // 1247 // Returns the parsed private key or an error if parsing fails or type assertion fails. 1248 // 1249 // Example: 1250 // 1251 // ed25519PrivKey, err := PrivateKeyFromSSH[ed25519.PrivateKey](sshData, "passphrase") 1252 // if err != nil { 1253 // log.Printf("Failed to parse private key: %v", err) 1254 // } 1255 func PrivateKeyFromSSH[T PrivateKey](sshData format.SSH, passphrase string) (T, error) { 1256 var zero T 1257 var privateKey interface{} 1258 var err error 1259 1260 if passphrase == "" { 1261 privateKey, err = ssh.ParseRawPrivateKey([]byte(sshData)) 1262 } else { 1263 privateKey, err = ssh.ParseRawPrivateKeyWithPassphrase([]byte(sshData), []byte(passphrase)) 1264 } 1265 1266 if err != nil { 1267 return zero, fmt.Errorf("failed to parse SSH private key: %w", err) 1268 } 1269 1270 if typedKey, ok := privateKey.(T); ok { 1271 return typedKey, nil 1272 } 1273 1274 return zero, fmt.Errorf("private key type mismatch: expected %T, got %T", zero, privateKey) 1275 } 1276 1277 // PublicKeyFromPEM parses a public key from PEM-encoded data. 1278 // The function expects PKIX format and returns the appropriate public key type. 1279 // 1280 // Type parameter: 1281 // - T: Expected public key type (*rsa.PublicKey, *ecdsa.PublicKey, or ed25519.PublicKey) 1282 // 1283 // Parameters: 1284 // - pemData: PEM-encoded public key data 1285 // 1286 // Returns the parsed public key or an error if parsing fails or type assertion fails. 1287 // 1288 // Example: 1289 // 1290 // rsaPubKey, err := PublicKeyFromPEM[*rsa.PublicKey](pemData) 1291 // if err != nil { 1292 // log.Printf("Failed to parse public key: %v", err) 1293 // } 1294 func PublicKeyFromPEM[T PublicKey](pemData format.PEM) (T, error) { 1295 var zero T 1296 1297 block, _ := pem.Decode(pemData) 1298 if block == nil { 1299 return zero, fmt.Errorf("failed to decode PEM block") 1300 } 1301 1302 publicKey, err := x509.ParsePKIXPublicKey(block.Bytes) 1303 if err != nil { 1304 return zero, fmt.Errorf("failed to parse PKIX public key: %w", err) 1305 } 1306 1307 if typedKey, ok := publicKey.(T); ok { 1308 return typedKey, nil 1309 } 1310 1311 return zero, fmt.Errorf("public key type mismatch: expected %T, got %T", zero, publicKey) 1312 } 1313 1314 // PublicKeyFromDER parses a public key from DER-encoded data. 1315 // The function expects PKIX format and returns the appropriate public key type. 1316 // 1317 // Type parameter: 1318 // - T: Expected public key type (*rsa.PublicKey, *ecdsa.PublicKey, or ed25519.PublicKey) 1319 // 1320 // Parameters: 1321 // - derData: DER-encoded public key data 1322 // 1323 // Returns the parsed public key or an error if parsing fails or type assertion fails. 1324 // 1325 // Example: 1326 // 1327 // ecdsaPubKey, err := PublicKeyFromDER[*ecdsa.PublicKey](derData) 1328 // if err != nil { 1329 // log.Printf("Failed to parse public key: %v", err) 1330 // } 1331 func PublicKeyFromDER[T PublicKey](derData format.DER) (T, error) { 1332 var zero T 1333 1334 publicKey, err := x509.ParsePKIXPublicKey(derData) 1335 if err != nil { 1336 return zero, fmt.Errorf("failed to parse PKIX public key: %w", err) 1337 } 1338 1339 if typedKey, ok := publicKey.(T); ok { 1340 return typedKey, nil 1341 } 1342 1343 return zero, fmt.Errorf("public key type mismatch: expected %T, got %T", zero, publicKey) 1344 } 1345 1346 // PublicKeyFromSSH parses a public key from SSH-encoded data. 1347 // The function handles SSH public key format (authorized_keys format). 1348 // 1349 // Type parameter: 1350 // - T: Expected public key type (*rsa.PublicKey, *ecdsa.PublicKey, or ed25519.PublicKey) 1351 // 1352 // Parameters: 1353 // - sshData: SSH-encoded public key data 1354 // 1355 // Returns the parsed public key or an error if parsing fails or type assertion fails. 1356 // 1357 // Example: 1358 // 1359 // ed25519PubKey, err := PublicKeyFromSSH[ed25519.PublicKey](sshData) 1360 // if err != nil { 1361 // log.Printf("Failed to parse public key: %v", err) 1362 // } 1363 func PublicKeyFromSSH[T PublicKey](sshData format.SSH) (T, error) { 1364 var zero T 1365 1366 publicKey, _, _, _, err := ssh.ParseAuthorizedKey([]byte(sshData)) 1367 if err != nil { 1368 return zero, fmt.Errorf("failed to parse SSH public key: %w", err) 1369 } 1370 1371 // Extract the underlying crypto.PublicKey 1372 var cryptoPublicKey interface{} 1373 1374 // Check if it's a certificate first 1375 if cert, ok := publicKey.(*ssh.Certificate); ok { 1376 if cryptoKey, ok := cert.Key.(ssh.CryptoPublicKey); ok { 1377 cryptoPublicKey = cryptoKey.CryptoPublicKey() 1378 } 1379 } else if cryptoKey, ok := publicKey.(ssh.CryptoPublicKey); ok { 1380 // Regular SSH public key (not certificate) 1381 cryptoPublicKey = cryptoKey.CryptoPublicKey() 1382 } else { 1383 return zero, fmt.Errorf("cannot extract crypto public key from SSH key type: %s", publicKey.Type()) 1384 } 1385 1386 if typedKey, ok := cryptoPublicKey.(T); ok { 1387 return typedKey, nil 1388 } 1389 1390 return zero, fmt.Errorf("public key type mismatch: expected %T, got %T", zero, cryptoPublicKey) 1391 } 1392 1393 // GetPublicKey extracts the public key from a private key with type safety. 1394 // This function works with all supported key types and maintains type relationships. 1395 // 1396 // Type parameters: 1397 // - TPriv: Private key type (*rsa.PrivateKey, *ecdsa.PrivateKey, or ed25519.PrivateKey) 1398 // - TPub: Expected public key type (*rsa.PublicKey, *ecdsa.PublicKey, or ed25519.PublicKey) 1399 // 1400 // Parameters: 1401 // - privateKey: The private key from which to extract the public key 1402 // 1403 // Returns the corresponding public key or an error if extraction fails. 1404 // 1405 // Example: 1406 // 1407 // rsaPublicKey, err := GetPublicKey[*rsa.PrivateKey, *rsa.PublicKey](rsaPrivateKey) 1408 // if err != nil { 1409 // log.Printf("Failed to get public key: %v", err) 1410 // } 1411 func GetPublicKey[TPriv PrivateKey, TPub PublicKey](privateKey TPriv) (TPub, error) { 1412 var zero TPub 1413 1414 switch priv := any(privateKey).(type) { 1415 case *rsa.PrivateKey: 1416 if pub, ok := any(&priv.PublicKey).(TPub); ok { 1417 return pub, nil 1418 } 1419 case *ecdsa.PrivateKey: 1420 if pub, ok := any(&priv.PublicKey).(TPub); ok { 1421 return pub, nil 1422 } 1423 case ed25519.PrivateKey: 1424 if pub, ok := any(priv.Public().(ed25519.PublicKey)).(TPub); ok { 1425 return pub, nil 1426 } 1427 } 1428 1429 return zero, fmt.Errorf("unsupported key type or type mismatch") 1430 } 1431 1432 // ToPEMFiles saves a key pair to separate private and public key files in PEM format. 1433 // The function creates the necessary directory structure and sets appropriate file permissions. 1434 // 1435 // Type parameter: 1436 // - T: Key pair type (*algo.RSAKeyPair, *algo.ECDSAKeyPair, or *algo.Ed25519KeyPair) 1437 // 1438 // Parameters: 1439 // - keyPair: The key pair to save 1440 // - privateFile: Path where the private key will be saved 1441 // - publicFile: Path where the public key will be saved 1442 // 1443 // File permissions: 1444 // - Private key files: 0600 (readable/writable by owner only) 1445 // - Public key files: 0600 (for consistency, though public keys could be more permissive) 1446 // - Directories: 0700 (accessible by owner only) 1447 // 1448 // Example: 1449 // 1450 // err := ToPEMFiles(rsaKeyPair, "private.pem", "public.pem") 1451 // if err != nil { 1452 // log.Printf("Failed to save key pair: %v", err) 1453 // } 1454 func ToPEMFiles[T KeyPair](keyPair T, privateFile, publicFile string) error { 1455 var privateKeyPEM, publicKeyPEM format.PEM 1456 var err error 1457 1458 switch kp := any(keyPair).(type) { 1459 case *algo.RSAKeyPair: 1460 privateKeyPEM, err = PrivateKeyToPEM(kp.PrivateKey) 1461 if err != nil { 1462 return fmt.Errorf("failed to convert RSA private key to PEM: %w", err) 1463 } 1464 publicKeyPEM, err = PublicKeyToPEM(&kp.PrivateKey.PublicKey) 1465 if err != nil { 1466 return fmt.Errorf("failed to convert RSA public key to PEM: %w", err) 1467 } 1468 case *algo.ECDSAKeyPair: 1469 privateKeyPEM, err = PrivateKeyToPEM(kp.PrivateKey) 1470 if err != nil { 1471 return fmt.Errorf("failed to convert ECDSA private key to PEM: %w", err) 1472 } 1473 publicKeyPEM, err = PublicKeyToPEM(&kp.PrivateKey.PublicKey) 1474 if err != nil { 1475 return fmt.Errorf("failed to convert ECDSA public key to PEM: %w", err) 1476 } 1477 case *algo.Ed25519KeyPair: 1478 privateKeyPEM, err = PrivateKeyToPEM(kp.PrivateKey) 1479 if err != nil { 1480 return fmt.Errorf("failed to convert Ed25519 private key to PEM: %w", err) 1481 } 1482 publicKeyPEM, err = PublicKeyToPEM(kp.PublicKey) 1483 if err != nil { 1484 return fmt.Errorf("failed to convert Ed25519 public key to PEM: %w", err) 1485 } 1486 default: 1487 return fmt.Errorf("unsupported key pair type") 1488 } 1489 1490 if err := savePEMToFile(privateKeyPEM, privateFile); err != nil { 1491 return fmt.Errorf("failed to save private key: %w", err) 1492 } 1493 1494 if err := savePEMToFile(publicKeyPEM, publicFile); err != nil { 1495 return fmt.Errorf("failed to save public key: %w", err) 1496 } 1497 1498 return nil 1499 } 1500 1501 // ToDERFiles saves a key pair to separate private and public key files in DER format. 1502 // The function creates the necessary directory structure and sets appropriate file permissions. 1503 // 1504 // Type parameter: 1505 // - T: Key pair type (*algo.RSAKeyPair, *algo.ECDSAKeyPair, or *algo.Ed25519KeyPair) 1506 // 1507 // Parameters: 1508 // - keyPair: The key pair to save 1509 // - privateFile: Path where the private key will be saved 1510 // - publicFile: Path where the public key will be saved 1511 // 1512 // File permissions: 1513 // - Private key files: 0600 (readable/writable by owner only) 1514 // - Public key files: 0600 (for consistency, though public keys could be more permissive) 1515 // - Directories: 0700 (accessible by owner only) 1516 // 1517 // Example: 1518 // 1519 // err := ToDERFiles(rsaKeyPair, "private.der", "public.der") 1520 // if err != nil { 1521 // log.Printf("Failed to save key pair: %v", err) 1522 // } 1523 func ToDERFiles[T KeyPair](keyPair T, privateFile, publicFile string) error { 1524 var privateKeyDER, publicKeyDER format.DER 1525 var err error 1526 1527 switch kp := any(keyPair).(type) { 1528 case *algo.RSAKeyPair: 1529 privateKeyDER, err = PrivateKeyToDER(kp.PrivateKey) 1530 if err != nil { 1531 return fmt.Errorf("failed to convert RSA private key to DER: %w", err) 1532 } 1533 publicKeyDER, err = PublicKeyToDER(&kp.PrivateKey.PublicKey) 1534 if err != nil { 1535 return fmt.Errorf("failed to convert RSA public key to DER: %w", err) 1536 } 1537 case *algo.ECDSAKeyPair: 1538 privateKeyDER, err = PrivateKeyToDER(kp.PrivateKey) 1539 if err != nil { 1540 return fmt.Errorf("failed to convert ECDSA private key to DER: %w", err) 1541 } 1542 publicKeyDER, err = PublicKeyToDER(&kp.PrivateKey.PublicKey) 1543 if err != nil { 1544 return fmt.Errorf("failed to convert ECDSA public key to DER: %w", err) 1545 } 1546 case *algo.Ed25519KeyPair: 1547 privateKeyDER, err = PrivateKeyToDER(kp.PrivateKey) 1548 if err != nil { 1549 return fmt.Errorf("failed to convert Ed25519 private key to DER: %w", err) 1550 } 1551 publicKeyDER, err = PublicKeyToDER(kp.PublicKey) 1552 if err != nil { 1553 return fmt.Errorf("failed to convert Ed25519 public key to DER: %w", err) 1554 } 1555 default: 1556 return fmt.Errorf("unsupported key pair type") 1557 } 1558 1559 if err := saveDERToFile(privateKeyDER, privateFile); err != nil { 1560 return fmt.Errorf("failed to save private key: %w", err) 1561 } 1562 1563 if err := saveDERToFile(publicKeyDER, publicFile); err != nil { 1564 return fmt.Errorf("failed to save public key: %w", err) 1565 } 1566 1567 return nil 1568 } 1569 1570 // ToSSHFiles saves a key pair to separate private and public key files in SSH format. 1571 // The function creates the necessary directory structure and sets appropriate file permissions. 1572 // 1573 // Type parameter: 1574 // - T: Key pair type (*algo.RSAKeyPair, *algo.ECDSAKeyPair, or *algo.Ed25519KeyPair) 1575 // 1576 // Parameters: 1577 // - keyPair: The key pair to save 1578 // - privateFile: Path where the private key will be saved 1579 // - publicFile: Path where the public key will be saved 1580 // - comment: Optional comment to include in the SSH keys 1581 // - passphrase: Optional passphrase for private key encryption (empty string for unencrypted) 1582 // 1583 // File permissions: 1584 // - Private key files: 0600 (readable/writable by owner only) 1585 // - Public key files: 0600 (for consistency, though public keys could be more permissive) 1586 // - Directories: 0700 (accessible by owner only) 1587 // 1588 // Example: 1589 // 1590 // err := ToSSHFiles(rsaKeyPair, "id_rsa", "id_rsa.pub", "user@host", "passphrase") 1591 // if err != nil { 1592 // log.Printf("Failed to save key pair: %v", err) 1593 // } 1594 func ToSSHFiles[T KeyPair](keyPair T, privateFile, publicFile string, comment string, passphrase string) error { 1595 var privateKeySSH, publicKeySSH format.SSH 1596 var err error 1597 1598 switch kp := any(keyPair).(type) { 1599 case *algo.RSAKeyPair: 1600 privateKeySSH, err = PrivateKeyToSSH(kp.PrivateKey, comment, passphrase) 1601 if err != nil { 1602 return fmt.Errorf("failed to convert RSA private key to SSH: %w", err) 1603 } 1604 publicKeySSH, err = PublicKeyToSSH(&kp.PrivateKey.PublicKey, comment) 1605 if err != nil { 1606 return fmt.Errorf("failed to convert RSA public key to SSH: %w", err) 1607 } 1608 case *algo.ECDSAKeyPair: 1609 privateKeySSH, err = PrivateKeyToSSH(kp.PrivateKey, comment, passphrase) 1610 if err != nil { 1611 return fmt.Errorf("failed to convert ECDSA private key to SSH: %w", err) 1612 } 1613 publicKeySSH, err = PublicKeyToSSH(&kp.PrivateKey.PublicKey, comment) 1614 if err != nil { 1615 return fmt.Errorf("failed to convert ECDSA public key to SSH: %w", err) 1616 } 1617 case *algo.Ed25519KeyPair: 1618 privateKeySSH, err = PrivateKeyToSSH(kp.PrivateKey, comment, passphrase) 1619 if err != nil { 1620 return fmt.Errorf("failed to convert Ed25519 private key to SSH: %w", err) 1621 } 1622 publicKeySSH, err = PublicKeyToSSH(kp.PublicKey, comment) 1623 if err != nil { 1624 return fmt.Errorf("failed to convert Ed25519 public key to SSH: %w", err) 1625 } 1626 default: 1627 return fmt.Errorf("unsupported key pair type") 1628 } 1629 1630 if err := saveSSHToFile(privateKeySSH, privateFile); err != nil { 1631 return fmt.Errorf("failed to save private key: %w", err) 1632 } 1633 1634 if err := saveSSHToFile(publicKeySSH, publicFile); err != nil { 1635 return fmt.Errorf("failed to save public key: %w", err) 1636 } 1637 1638 return nil 1639 } 1640 1641 // FromPEMFiles loads a key pair from separate private and public key files in PEM format. 1642 // The function reads both files and reconstructs the appropriate KeyPair type. 1643 // 1644 // Type parameter: 1645 // - K: KeyPair type (*algo.RSAKeyPair, *algo.ECDSAKeyPair, or *algo.Ed25519KeyPair) 1646 // 1647 // Parameters: 1648 // - privateFile: Path to the private key PEM file 1649 // - publicFile: Path to the public key PEM file 1650 // 1651 // Returns the reconstructed key pair or an error if reading or parsing fails. 1652 // 1653 // Example: 1654 // 1655 // rsaKeyPair, err := FromPEMFiles[*algo.RSAKeyPair]("private.pem", "public.pem") 1656 // if err != nil { 1657 // log.Printf("Failed to load key pair: %v", err) 1658 // } 1659 func FromPEMFiles[K KeyPair](privateFile, publicFile string) (K, error) { 1660 var zero K 1661 1662 // Read private key file 1663 privateData, err := os.ReadFile(privateFile) 1664 if err != nil { 1665 return zero, fmt.Errorf("failed to read private key file %s: %w", privateFile, err) 1666 } 1667 1668 // Read public key file 1669 publicData, err := os.ReadFile(publicFile) 1670 if err != nil { 1671 return zero, fmt.Errorf("failed to read public key file %s: %w", publicFile, err) 1672 } 1673 1674 // Parse private key to determine type 1675 privatePEM := format.PEM(privateData) 1676 block, _ := pem.Decode(privatePEM) 1677 if block == nil { 1678 return zero, fmt.Errorf("failed to decode private key PEM from %s", privateFile) 1679 } 1680 1681 privateKey, err := x509.ParsePKCS8PrivateKey(block.Bytes) 1682 if err != nil { 1683 return zero, fmt.Errorf("failed to parse private key from %s: %w", privateFile, err) 1684 } 1685 1686 // Parse public key 1687 publicPEM := format.PEM(publicData) 1688 publicBlock, _ := pem.Decode(publicPEM) 1689 if publicBlock == nil { 1690 return zero, fmt.Errorf("failed to decode public key PEM from %s", publicFile) 1691 } 1692 1693 publicKey, err := x509.ParsePKIXPublicKey(publicBlock.Bytes) 1694 if err != nil { 1695 return zero, fmt.Errorf("failed to parse public key from %s: %w", publicFile, err) 1696 } 1697 1698 // Reconstruct KeyPair based on private key type 1699 switch priv := privateKey.(type) { 1700 case *rsa.PrivateKey: 1701 if rsaPub, ok := publicKey.(*rsa.PublicKey); ok { 1702 keyPair := &algo.RSAKeyPair{ 1703 PrivateKey: priv, 1704 PublicKey: rsaPub, 1705 } 1706 if result, ok := any(keyPair).(K); ok { 1707 return result, nil 1708 } 1709 } 1710 case *ecdsa.PrivateKey: 1711 if ecdsaPub, ok := publicKey.(*ecdsa.PublicKey); ok { 1712 keyPair := &algo.ECDSAKeyPair{ 1713 PrivateKey: priv, 1714 PublicKey: ecdsaPub, 1715 } 1716 if result, ok := any(keyPair).(K); ok { 1717 return result, nil 1718 } 1719 } 1720 case ed25519.PrivateKey: 1721 if ed25519Pub, ok := publicKey.(ed25519.PublicKey); ok { 1722 keyPair := &algo.Ed25519KeyPair{ 1723 PrivateKey: priv, 1724 PublicKey: ed25519Pub, 1725 } 1726 if result, ok := any(keyPair).(K); ok { 1727 return result, nil 1728 } 1729 } 1730 } 1731 1732 return zero, fmt.Errorf("key type mismatch or unsupported key type") 1733 } 1734 1735 // FromDERFiles loads a key pair from separate private and public key files in DER format. 1736 // The function reads both files and reconstructs the appropriate KeyPair type. 1737 // 1738 // Type parameter: 1739 // - K: KeyPair type (*algo.RSAKeyPair, *algo.ECDSAKeyPair, or *algo.Ed25519KeyPair) 1740 // 1741 // Parameters: 1742 // - privateFile: Path to the private key DER file 1743 // - publicFile: Path to the public key DER file 1744 // 1745 // Returns the reconstructed key pair or an error if reading or parsing fails. 1746 // 1747 // Example: 1748 // 1749 // ecdsaKeyPair, err := FromDERFiles[*algo.ECDSAKeyPair]("private.der", "public.der") 1750 // if err != nil { 1751 // log.Printf("Failed to load key pair: %v", err) 1752 // } 1753 func FromDERFiles[K KeyPair](privateFile, publicFile string) (K, error) { 1754 var zero K 1755 1756 // Read private key file 1757 privateData, err := os.ReadFile(privateFile) 1758 if err != nil { 1759 return zero, fmt.Errorf("failed to read private key file %s: %w", privateFile, err) 1760 } 1761 1762 // Read public key file 1763 publicData, err := os.ReadFile(publicFile) 1764 if err != nil { 1765 return zero, fmt.Errorf("failed to read public key file %s: %w", publicFile, err) 1766 } 1767 1768 // Parse private key to determine type 1769 privateDER := format.DER(privateData) 1770 privateKey, err := x509.ParsePKCS8PrivateKey(privateDER) 1771 if err != nil { 1772 return zero, fmt.Errorf("failed to parse private key from %s: %w", privateFile, err) 1773 } 1774 1775 // Parse public key 1776 publicDER := format.DER(publicData) 1777 publicKey, err := x509.ParsePKIXPublicKey(publicDER) 1778 if err != nil { 1779 return zero, fmt.Errorf("failed to parse public key from %s: %w", publicFile, err) 1780 } 1781 1782 // Reconstruct KeyPair based on private key type 1783 switch priv := privateKey.(type) { 1784 case *rsa.PrivateKey: 1785 if rsaPub, ok := publicKey.(*rsa.PublicKey); ok { 1786 keyPair := &algo.RSAKeyPair{ 1787 PrivateKey: priv, 1788 PublicKey: rsaPub, 1789 } 1790 if result, ok := any(keyPair).(K); ok { 1791 return result, nil 1792 } 1793 } 1794 case *ecdsa.PrivateKey: 1795 if ecdsaPub, ok := publicKey.(*ecdsa.PublicKey); ok { 1796 keyPair := &algo.ECDSAKeyPair{ 1797 PrivateKey: priv, 1798 PublicKey: ecdsaPub, 1799 } 1800 if result, ok := any(keyPair).(K); ok { 1801 return result, nil 1802 } 1803 } 1804 case ed25519.PrivateKey: 1805 if ed25519Pub, ok := publicKey.(ed25519.PublicKey); ok { 1806 keyPair := &algo.Ed25519KeyPair{ 1807 PrivateKey: priv, 1808 PublicKey: ed25519Pub, 1809 } 1810 if result, ok := any(keyPair).(K); ok { 1811 return result, nil 1812 } 1813 } 1814 } 1815 1816 return zero, fmt.Errorf("key type mismatch or unsupported key type") 1817 } 1818 1819 // FromSSHFiles loads a key pair from separate private and public key files in SSH format. 1820 // The function reads both files and reconstructs the appropriate KeyPair type. 1821 // 1822 // Type parameter: 1823 // - K: KeyPair type (*algo.RSAKeyPair, *algo.ECDSAKeyPair, or *algo.Ed25519KeyPair) 1824 // 1825 // Parameters: 1826 // - privateFile: Path to the SSH private key file 1827 // - publicFile: Path to the SSH public key file 1828 // - passphrase: Passphrase for encrypted private keys (empty string for unencrypted) 1829 // 1830 // Returns the reconstructed key pair or an error if reading or parsing fails. 1831 // 1832 // Example: 1833 // 1834 // ed25519KeyPair, err := FromSSHFiles[*algo.Ed25519KeyPair]("id_ed25519", "id_ed25519.pub", "passphrase") 1835 // if err != nil { 1836 // log.Printf("Failed to load key pair: %v", err) 1837 // } 1838 func FromSSHFiles[K KeyPair](privateFile, publicFile string, passphrase string) (K, error) { 1839 var zero K 1840 1841 // Read private key file 1842 privateData, err := os.ReadFile(privateFile) 1843 if err != nil { 1844 return zero, fmt.Errorf("failed to read private key file %s: %w", privateFile, err) 1845 } 1846 1847 // Read public key file 1848 publicData, err := os.ReadFile(publicFile) 1849 if err != nil { 1850 return zero, fmt.Errorf("failed to read public key file %s: %w", publicFile, err) 1851 } 1852 1853 // Parse private key to determine type 1854 privateSSH := format.SSH(privateData) 1855 var privateKey interface{} 1856 1857 if passphrase == "" { 1858 privateKey, err = ssh.ParseRawPrivateKey([]byte(privateSSH)) 1859 } else { 1860 privateKey, err = ssh.ParseRawPrivateKeyWithPassphrase([]byte(privateSSH), []byte(passphrase)) 1861 } 1862 1863 if err != nil { 1864 return zero, fmt.Errorf("failed to parse private key from %s: %w", privateFile, err) 1865 } 1866 1867 // Parse public key 1868 publicSSH := format.SSH(publicData) 1869 sshPublicKey, _, _, _, err := ssh.ParseAuthorizedKey([]byte(publicSSH)) 1870 if err != nil { 1871 return zero, fmt.Errorf("failed to parse public key from %s: %w", publicFile, err) 1872 } 1873 1874 // Extract crypto.PublicKey 1875 var publicKey interface{} 1876 if cryptoKey, ok := sshPublicKey.(ssh.CryptoPublicKey); ok { 1877 publicKey = cryptoKey.CryptoPublicKey() 1878 } else { 1879 return zero, fmt.Errorf("cannot extract crypto public key from SSH key") 1880 } 1881 1882 // Reconstruct KeyPair based on private key type 1883 switch priv := privateKey.(type) { 1884 case *rsa.PrivateKey: 1885 if rsaPub, ok := publicKey.(*rsa.PublicKey); ok { 1886 keyPair := &algo.RSAKeyPair{ 1887 PrivateKey: priv, 1888 PublicKey: rsaPub, 1889 } 1890 if result, ok := any(keyPair).(K); ok { 1891 return result, nil 1892 } 1893 } 1894 case *ecdsa.PrivateKey: 1895 if ecdsaPub, ok := publicKey.(*ecdsa.PublicKey); ok { 1896 keyPair := &algo.ECDSAKeyPair{ 1897 PrivateKey: priv, 1898 PublicKey: ecdsaPub, 1899 } 1900 if result, ok := any(keyPair).(K); ok { 1901 return result, nil 1902 } 1903 } 1904 case ed25519.PrivateKey: 1905 if ed25519Pub, ok := publicKey.(ed25519.PublicKey); ok { 1906 keyPair := &algo.Ed25519KeyPair{ 1907 PrivateKey: priv, 1908 PublicKey: ed25519Pub, 1909 } 1910 if result, ok := any(keyPair).(K); ok { 1911 return result, nil 1912 } 1913 } 1914 } 1915 1916 return zero, fmt.Errorf("key type mismatch or unsupported key type") 1917 } 1918 1919 // GetPrivateKeyFromKeyPair extracts the private key from a KeyPair with type safety. 1920 // This function works with all supported KeyPair types and maintains type relationships. 1921 // 1922 // Type parameters: 1923 // - K: KeyPair type (*algo.RSAKeyPair, *algo.ECDSAKeyPair, or *algo.Ed25519KeyPair) 1924 // - T: Expected private key type (*rsa.PrivateKey, *ecdsa.PrivateKey, or ed25519.PrivateKey) 1925 // 1926 // Parameters: 1927 // - keyPair: The key pair from which to extract the private key 1928 // 1929 // Returns the corresponding private key or an error if extraction fails or type mismatch occurs. 1930 // 1931 // Examples: 1932 // 1933 // // Extract RSA private key with explicit types 1934 // rsaPriv, err := GetPrivateKeyFromKeyPair[*algo.RSAKeyPair, *rsa.PrivateKey](rsaKeyPair) 1935 // 1936 // // Extract ECDSA private key with type inference 1937 // ecdsaPriv, err := GetPrivateKeyFromKeyPair[*algo.ECDSAKeyPair, *ecdsa.PrivateKey](ecdsaKeyPair) 1938 // 1939 // // Extract Ed25519 private key 1940 // ed25519Priv, err := GetPrivateKeyFromKeyPair[*algo.Ed25519KeyPair, ed25519.PrivateKey](ed25519KeyPair) 1941 func GetPrivateKeyFromKeyPair[K KeyPair, T PrivateKey](keyPair K) (T, error) { 1942 var zero T 1943 1944 switch kp := any(keyPair).(type) { 1945 case *algo.RSAKeyPair: 1946 if priv, ok := any(kp.PrivateKey).(T); ok { 1947 return priv, nil 1948 } 1949 case *algo.ECDSAKeyPair: 1950 if priv, ok := any(kp.PrivateKey).(T); ok { 1951 return priv, nil 1952 } 1953 case *algo.Ed25519KeyPair: 1954 if priv, ok := any(kp.PrivateKey).(T); ok { 1955 return priv, nil 1956 } 1957 } 1958 1959 return zero, fmt.Errorf("unsupported key pair type or type mismatch") 1960 } 1961 1962 // GetPublicKeyFromKeyPair extracts the public key from a KeyPair with type safety. 1963 // This function works with all supported KeyPair types and maintains type relationships. 1964 // 1965 // Type parameters: 1966 // - K: KeyPair type (*algo.RSAKeyPair, *algo.ECDSAKeyPair, or *algo.Ed25519KeyPair) 1967 // - T: Expected public key type (*rsa.PublicKey, *ecdsa.PublicKey, or ed25519.PublicKey) 1968 // 1969 // Parameters: 1970 // - keyPair: The key pair from which to extract the public key 1971 // 1972 // Returns the corresponding public key or an error if extraction fails or type mismatch occurs. 1973 // 1974 // Examples: 1975 // 1976 // // Extract RSA public key with explicit types 1977 // rsaPub, err := GetPublicKeyFromKeyPair[*algo.RSAKeyPair, *rsa.PublicKey](rsaKeyPair) 1978 // 1979 // // Extract ECDSA public key with type inference 1980 // ecdsaPub, err := GetPublicKeyFromKeyPair[*algo.ECDSAKeyPair, *ecdsa.PublicKey](ecdsaKeyPair) 1981 // 1982 // // Extract Ed25519 public key 1983 // ed25519Pub, err := GetPublicKeyFromKeyPair[*algo.Ed25519KeyPair, ed25519.PublicKey](ed25519KeyPair) 1984 func GetPublicKeyFromKeyPair[K KeyPair, T PublicKey](keyPair K) (T, error) { 1985 var zero T 1986 1987 switch kp := any(keyPair).(type) { 1988 case *algo.RSAKeyPair: 1989 if pub, ok := any(kp.PublicKey).(T); ok { 1990 return pub, nil 1991 } 1992 case *algo.ECDSAKeyPair: 1993 if pub, ok := any(kp.PublicKey).(T); ok { 1994 return pub, nil 1995 } 1996 case *algo.Ed25519KeyPair: 1997 if pub, ok := any(kp.PublicKey).(T); ok { 1998 return pub, nil 1999 } 2000 } 2001 2002 return zero, fmt.Errorf("unsupported key pair type or type mismatch") 2003 } 2004 2005 // saveDERToFile saves DER-encoded data to a file with secure permissions. 2006 // This is an internal helper function that handles directory creation and file permissions. 2007 // 2008 // Parameters: 2009 // - derData: DER-encoded data to save 2010 // - filename: Target file path 2011 // 2012 // The function: 2013 // - Creates parent directories with 0700 permissions 2014 // - Checks write permissions for existing files 2015 // - Saves files with 0600 permissions (owner read/write only) 2016 // 2017 // Returns an error if file operations fail. 2018 func saveDERToFile(derData format.DER, filename string) error { 2019 dir := filepath.Dir(filename) 2020 2021 if err := os.MkdirAll(dir, 0700); err != nil { 2022 return fmt.Errorf("failed to create directory %s: %w", dir, err) 2023 } 2024 2025 if _, err := os.Stat(filename); err == nil { 2026 file, err := os.OpenFile(filename, os.O_WRONLY, 0600) 2027 if err != nil { 2028 return fmt.Errorf("no write permission for existing file %s: %w", filename, err) 2029 } 2030 file.Close() 2031 } else if !os.IsNotExist(err) { 2032 return fmt.Errorf("failed to check file status %s: %w", filename, err) 2033 } 2034 2035 if err := os.WriteFile(filename, derData, 0600); err != nil { 2036 return fmt.Errorf("failed to write file %s: %w", filename, err) 2037 } 2038 2039 return nil 2040 } 2041 2042 // saveSSHToFile saves SSH-encoded data to a file with secure permissions. 2043 // This is an internal helper function that handles directory creation and file permissions. 2044 // 2045 // Parameters: 2046 // - sshData: SSH-encoded data to save 2047 // - filename: Target file path 2048 // 2049 // The function: 2050 // - Creates parent directories with 0700 permissions 2051 // - Checks write permissions for existing files 2052 // - Saves files with 0600 permissions (owner read/write only) 2053 // 2054 // Returns an error if file operations fail. 2055 func saveSSHToFile(sshData format.SSH, filename string) error { 2056 dir := filepath.Dir(filename) 2057 2058 if err := os.MkdirAll(dir, 0700); err != nil { 2059 return fmt.Errorf("failed to create directory %s: %w", dir, err) 2060 } 2061 2062 if _, err := os.Stat(filename); err == nil { 2063 file, err := os.OpenFile(filename, os.O_WRONLY, 0600) 2064 if err != nil { 2065 return fmt.Errorf("no write permission for existing file %s: %w", filename, err) 2066 } 2067 file.Close() 2068 } else if !os.IsNotExist(err) { 2069 return fmt.Errorf("failed to check file status %s: %w", filename, err) 2070 } 2071 2072 if err := os.WriteFile(filename, []byte(sshData), 0600); err != nil { 2073 return fmt.Errorf("failed to write file %s: %w", filename, err) 2074 } 2075 2076 return nil 2077 } 2078 2079 // savePEMToFile saves PEM-encoded data to a file with secure permissions. 2080 // This is an internal helper function that handles directory creation and file permissions. 2081 // 2082 // Parameters: 2083 // - pemData: PEM-encoded data to save 2084 // - filename: Target file path 2085 // 2086 // The function: 2087 // - Creates parent directories with 0700 permissions 2088 // - Checks write permissions for existing files 2089 // - Saves files with 0600 permissions (owner read/write only) 2090 // 2091 // Returns an error if file operations fail. 2092 func savePEMToFile(pemData format.PEM, filename string) error { 2093 dir := filepath.Dir(filename) 2094 2095 if err := os.MkdirAll(dir, 0700); err != nil { 2096 return fmt.Errorf("failed to create directory %s: %w", dir, err) 2097 } 2098 2099 if _, err := os.Stat(filename); err == nil { 2100 file, err := os.OpenFile(filename, os.O_WRONLY, 0600) 2101 if err != nil { 2102 return fmt.Errorf("no write permission for existing file %s: %w", filename, err) 2103 } 2104 file.Close() 2105 } else if !os.IsNotExist(err) { 2106 return fmt.Errorf("failed to check file status %s: %w", filename, err) 2107 } 2108 2109 if err := os.WriteFile(filename, pemData, 0600); err != nil { 2110 return fmt.Errorf("failed to write file %s: %w", filename, err) 2111 } 2112 2113 return nil 2114 }