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