github.com/jasoet/gopki@v1.15.0/encryption/asymmetric/asymmetric.go (about) 1 // Package asymmetric provides asymmetric encryption operations using RSA, ECDSA, and Ed25519 algorithms. 2 // 3 // This package implements direct asymmetric encryption where data is encrypted directly 4 // using the recipient's public key. Due to the nature of asymmetric algorithms, there are 5 // practical size limitations for the data that can be encrypted: 6 // 7 // - RSA: Limited to key size minus padding overhead (e.g., ~190 bytes for 2048-bit RSA) 8 // - ECDSA: Uses ephemeral ECDH key agreement + AES-GCM for larger data support 9 // - Ed25519: Uses X25519 key agreement + AES-GCM for larger data support 10 // 11 // For encrypting large amounts of data, consider using the envelope encryption package 12 // which combines the benefits of symmetric and asymmetric encryption. 13 // 14 // Security considerations: 15 // - RSA-OAEP with SHA-256 for RSA operations 16 // - ECDH key agreement with ephemeral keys for ECDSA 17 // - X25519 key agreement with ephemeral keys for Ed25519 18 // - AES-256-GCM for symmetric encryption in key agreement scenarios 19 // - Cryptographically secure random number generation 20 // 21 // Example usage: 22 // 23 // // RSA encryption 24 // rsaKeys, _ := algo.GenerateRSAKeyPair(2048) 25 // encrypted, err := asymmetric.Encrypt(data, rsaKeys, opts) 26 // 27 // // ECDSA encryption 28 // ecdsaKeys, _ := algo.GenerateECDSAKeyPair(algo.P256) 29 // encrypted, err := asymmetric.Encrypt(data, ecdsaKeys, opts) 30 // 31 // // Ed25519 encryption 32 // ed25519Keys, _ := algo.GenerateEd25519KeyPair() 33 // encrypted, err := asymmetric.Encrypt(data, ed25519Keys, opts) 34 package asymmetric 35 36 import ( 37 "crypto/ecdh" 38 "crypto/ecdsa" 39 "crypto/ed25519" 40 "crypto/rand" 41 "crypto/rsa" 42 "crypto/sha256" 43 "fmt" 44 "io" 45 "time" 46 47 "golang.org/x/crypto/hkdf" 48 49 "github.com/jasoet/gopki/encryption" 50 "github.com/jasoet/gopki/internal/crypto" 51 "github.com/jasoet/gopki/keypair" 52 "github.com/jasoet/gopki/keypair/algo" 53 ) 54 55 // Encrypt encrypts data using asymmetric encryption with automatic algorithm selection 56 // based on the key pair type. This is the main entry point for asymmetric encryption. 57 // 58 // Type parameter: 59 // - T: Key pair type constrained to keypair.KeyPair interface 60 // 61 // Parameters: 62 // - data: The plaintext data to encrypt 63 // - keyPair: The key pair (public key used for encryption) 64 // - opts: Encryption options 65 // 66 // Returns: 67 // - *encryption.EncryptedData: The encrypted data 68 // - error: Any error that occurred during encryption 69 // 70 // Example: 71 // 72 // rsaKeys, _ := algo.GenerateRSAKeyPair(2048) 73 // opts := encryption.EncryptOptions{ 74 // Algorithm: encryption.AlgorithmRSAOAEP, 75 // Format: encryption.FormatCMS, 76 // } 77 // encrypted, err := asymmetric.Encrypt(data, rsaKeys, opts) 78 func Encrypt[T keypair.KeyPair](data []byte, keyPair T, opts encryption.EncryptOptions) (*encryption.EncryptedData, error) { 79 switch kp := any(keyPair).(type) { 80 case *algo.RSAKeyPair: 81 return EncryptWithRSA(data, kp, opts) 82 case *algo.ECDSAKeyPair: 83 return EncryptWithECDSA(data, kp, opts) 84 case *algo.Ed25519KeyPair: 85 return EncryptWithEd25519(data, kp, opts) 86 default: 87 return nil, fmt.Errorf("unsupported key pair type: %T", keyPair) 88 } 89 } 90 91 // Decrypt decrypts asymmetrically encrypted data with automatic algorithm selection 92 // based on the key pair type. 93 // 94 // Type parameter: 95 // - T: Key pair type constrained to keypair.KeyPair interface 96 // 97 // Parameters: 98 // - encrypted: The encrypted data to decrypt 99 // - keyPair: The key pair (private key used for decryption) 100 // - opts: Decryption options 101 // 102 // Returns: 103 // - []byte: The decrypted plaintext data 104 // - error: Any error that occurred during decryption 105 // 106 // Example: 107 // 108 // plaintext, err := asymmetric.Decrypt(encrypted, rsaKeys, opts) 109 func Decrypt[T keypair.KeyPair](encrypted *encryption.EncryptedData, keyPair T, opts encryption.DecryptOptions) ([]byte, error) { 110 switch kp := any(keyPair).(type) { 111 case *algo.RSAKeyPair: 112 return DecryptWithRSA(encrypted, kp, opts) 113 case *algo.ECDSAKeyPair: 114 return DecryptWithECDSA(encrypted, kp, opts) 115 case *algo.Ed25519KeyPair: 116 return DecryptWithEd25519(encrypted, kp, opts) 117 default: 118 return nil, fmt.Errorf("unsupported key pair type: %T", keyPair) 119 } 120 } 121 122 // EncryptForPublicKey encrypts data for a specific public key using the appropriate 123 // asymmetric algorithm. This is useful when you only have the public key available. 124 // 125 // Type parameter: 126 // - T: Public key type constrained to keypair.PublicKey interface 127 // 128 // Parameters: 129 // - data: The plaintext data to encrypt 130 // - publicKey: The recipient's public key 131 // - opts: Encryption options 132 // 133 // Returns: 134 // - *encryption.EncryptedData: The encrypted data 135 // - error: Any error that occurred during encryption 136 // 137 // Example: 138 // 139 // publicKey := rsaKeys.PublicKey() 140 // encrypted, err := asymmetric.EncryptForPublicKey(data, publicKey, opts) 141 func EncryptForPublicKey[T keypair.PublicKey](data []byte, publicKey T, opts encryption.EncryptOptions) (*encryption.EncryptedData, error) { 142 switch pk := any(publicKey).(type) { 143 case *rsa.PublicKey: 144 // For RSA, we can encrypt directly with the public key 145 maxDataSize := pk.Size() - 2*sha256.Size - 2 146 if len(data) > maxDataSize { 147 return nil, fmt.Errorf("%w: data size %d exceeds maximum %d for RSA key size %d", 148 encryption.ErrDataTooLarge, len(data), maxDataSize, pk.Size()*8) 149 } 150 151 encrypted, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, pk, data, nil) 152 if err != nil { 153 return nil, fmt.Errorf("RSA-OAEP encryption failed: %w", err) 154 } 155 156 return &encryption.EncryptedData{ 157 Algorithm: encryption.AlgorithmRSAOAEP, 158 Format: opts.Format, 159 Data: encrypted, 160 Timestamp: time.Now(), 161 Metadata: opts.Metadata, 162 }, nil 163 164 case *ecdsa.PublicKey: 165 // For ECDSA, use ephemeral ECDH key agreement + AES-GCM 166 return encryptForECDSAPublicKey(data, pk, opts) 167 168 case ed25519.PublicKey: 169 // For Ed25519, use ephemeral X25519 key agreement + AES-GCM 170 return encryptForEd25519PublicKey(data, pk, opts) 171 172 default: 173 return nil, fmt.Errorf("unsupported public key type: %T", publicKey) 174 } 175 } 176 177 // DecryptWithPrivateKey decrypts data using a private key. 178 // This function supports RSA-OAEP, ECDH, and X25519 algorithms by dispatching 179 // to the appropriate decryption method based on the private key type and algorithm. 180 // 181 // Type parameter: 182 // - T: Private key type constrained to keypair.PrivateKey interface 183 // 184 // Parameters: 185 // - encrypted: The encrypted data to decrypt 186 // - privateKey: The private key to use for decryption 187 // - opts: Decryption options 188 // 189 // Returns: 190 // - []byte: The decrypted plaintext data 191 // - error: Any error that occurred during decryption 192 func DecryptWithPrivateKey[T keypair.PrivateKey](encrypted *encryption.EncryptedData, privateKey T, opts encryption.DecryptOptions) ([]byte, error) { 193 switch pk := any(privateKey).(type) { 194 case *rsa.PrivateKey: 195 // For RSA, decrypt directly using OAEP 196 if encrypted.Algorithm != encryption.AlgorithmRSAOAEP { 197 return nil, fmt.Errorf("expected RSA-OAEP algorithm for RSA private key, got %s", encrypted.Algorithm) 198 } 199 200 plaintext, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, pk, encrypted.Data, nil) 201 if err != nil { 202 return nil, fmt.Errorf("RSA-OAEP decryption failed: %w", err) 203 } 204 return plaintext, nil 205 206 case *ecdsa.PrivateKey: 207 // For ECDSA, use ECDH key agreement 208 return decryptWithECDSAPrivateKey(encrypted, pk, opts) 209 210 case ed25519.PrivateKey: 211 // For Ed25519, use X25519 key agreement 212 return decryptWithEd25519PrivateKey(encrypted, pk, opts) 213 214 default: 215 return nil, fmt.Errorf("unsupported private key type: %T", privateKey) 216 } 217 } 218 219 // SupportedAlgorithms returns the encryption algorithms supported by this package. 220 func SupportedAlgorithms() []encryption.Algorithm { 221 return []encryption.Algorithm{ 222 encryption.AlgorithmRSAOAEP, 223 encryption.AlgorithmECDH, 224 encryption.AlgorithmX25519, 225 } 226 } 227 228 // EncryptForPublicKeyAny is a non-generic wrapper for EncryptForPublicKey that works with any public key type. 229 // This is used internally by the envelope package for dynamic dispatch. 230 func EncryptForPublicKeyAny(data []byte, publicKey keypair.GenericPublicKey, opts encryption.EncryptOptions) (*encryption.EncryptedData, error) { 231 switch pk := publicKey.(type) { 232 case *rsa.PublicKey: 233 return EncryptForPublicKey(data, pk, opts) 234 case *ecdsa.PublicKey: 235 return EncryptForPublicKey(data, pk, opts) 236 case ed25519.PublicKey: 237 return EncryptForPublicKey(data, pk, opts) 238 default: 239 return nil, fmt.Errorf("unsupported public key type: %T", publicKey) 240 } 241 } 242 243 // Ephemeral Key Generation Utilities 244 245 // generateEphemeralECDSAKey generates an ephemeral ECDSA key pair for the same curve as the recipient's key. 246 // This is used for ECDH key agreement in envelope encryption scenarios. 247 func generateEphemeralECDSAKey(recipientKey *ecdsa.PublicKey) (*ecdsa.PrivateKey, error) { 248 if recipientKey == nil { 249 return nil, fmt.Errorf("recipient key cannot be nil") 250 } 251 252 ephemeralKey, err := ecdsa.GenerateKey(recipientKey.Curve, rand.Reader) 253 if err != nil { 254 return nil, fmt.Errorf("failed to generate ephemeral ECDSA key: %w", err) 255 } 256 257 return ephemeralKey, nil 258 } 259 260 // generateEphemeralX25519Key generates an ephemeral X25519 key pair for key agreement. 261 // This is used for Ed25519-based envelope encryption. 262 func generateEphemeralX25519Key() (*ecdh.PrivateKey, error) { 263 x25519 := ecdh.X25519() 264 ephemeralKey, err := x25519.GenerateKey(rand.Reader) 265 if err != nil { 266 return nil, fmt.Errorf("failed to generate ephemeral X25519 key: %w", err) 267 } 268 269 return ephemeralKey, nil 270 } 271 272 // Key Agreement Functions 273 274 // performECDHKeyAgreement performs ECDH key agreement between private and public ECDSA keys. 275 // Returns the shared secret that can be used for key derivation. 276 func performECDHKeyAgreement(privateKey *ecdsa.PrivateKey, publicKey *ecdsa.PublicKey) ([]byte, error) { 277 if privateKey == nil || publicKey == nil { 278 return nil, fmt.Errorf("private key and public key cannot be nil") 279 } 280 281 if privateKey.Curve != publicKey.Curve { 282 return nil, fmt.Errorf("curve mismatch: private key uses %s, public key uses %s", 283 privateKey.Curve.Params().Name, publicKey.Curve.Params().Name) 284 } 285 286 // Perform ECDH key agreement 287 x, _ := publicKey.Curve.ScalarMult(publicKey.X, publicKey.Y, privateKey.D.Bytes()) 288 if x == nil { 289 return nil, fmt.Errorf("ECDH key agreement failed: invalid result") 290 } 291 292 sharedSecret := x.Bytes() 293 if len(sharedSecret) == 0 { 294 return nil, fmt.Errorf("ECDH key agreement failed: empty shared secret") 295 } 296 297 return sharedSecret, nil 298 } 299 300 // performX25519KeyAgreement performs X25519 key agreement. 301 // Returns the shared secret for key derivation. 302 func performX25519KeyAgreement(privateKey *ecdh.PrivateKey, publicKeyBytes []byte) ([]byte, error) { 303 if privateKey == nil { 304 return nil, fmt.Errorf("private key cannot be nil") 305 } 306 307 if len(publicKeyBytes) != 32 { 308 return nil, fmt.Errorf("invalid X25519 public key length: %d (expected 32)", len(publicKeyBytes)) 309 } 310 311 // Convert bytes to X25519 public key 312 x25519 := ecdh.X25519() 313 publicKey, err := x25519.NewPublicKey(publicKeyBytes) 314 if err != nil { 315 return nil, fmt.Errorf("failed to create X25519 public key: %w", err) 316 } 317 318 // Perform X25519 key agreement 319 sharedSecret, err := privateKey.ECDH(publicKey) 320 if err != nil { 321 return nil, fmt.Errorf("X25519 key agreement failed: %w", err) 322 } 323 324 if len(sharedSecret) == 0 { 325 return nil, fmt.Errorf("X25519 key agreement failed: empty shared secret") 326 } 327 328 return sharedSecret, nil 329 } 330 331 // Key Derivation Functions 332 333 // deriveAESKeyFromSharedSecret derives an AES-256 key from a shared secret using HKDF-SHA256. 334 // The info parameter provides application-specific context for the key derivation. 335 func deriveAESKeyFromSharedSecret(sharedSecret []byte, info []byte) ([]byte, error) { 336 if len(sharedSecret) == 0 { 337 return nil, fmt.Errorf("shared secret cannot be empty") 338 } 339 340 // Use HKDF-SHA256 to derive a 32-byte AES key 341 hkdfReader := hkdf.New(sha256.New, sharedSecret, nil, info) 342 aesKey := make([]byte, 32) // AES-256 key size 343 344 _, err := io.ReadFull(hkdfReader, aesKey) 345 if err != nil { 346 return nil, fmt.Errorf("failed to derive AES key: %w", err) 347 } 348 349 return aesKey, nil 350 } 351 352 // Key Conversion Functions - Ed25519 conversion removed due to incompatibility 353 354 // encryptForECDSAPublicKey encrypts data for an ECDSA public key using ephemeral ECDH key agreement. 355 // This function mirrors the logic from EncryptWithECDSA but works with just the public key. 356 func encryptForECDSAPublicKey(data []byte, publicKey *ecdsa.PublicKey, opts encryption.EncryptOptions) (*encryption.EncryptedData, error) { 357 // Convert ECDSA public key to ECDH format 358 ecdhPublicKey, err := publicKey.ECDH() 359 if err != nil { 360 return nil, fmt.Errorf("failed to convert ECDSA public key to ECDH: %w", err) 361 } 362 363 // Generate ephemeral key pair for sender 364 curve := ecdhPublicKey.Curve() 365 ephemeralPrivateKey, err := curve.GenerateKey(rand.Reader) 366 if err != nil { 367 return nil, fmt.Errorf("failed to generate ephemeral key: %w", err) 368 } 369 370 // Perform ECDH key agreement 371 sharedSecret, err := ephemeralPrivateKey.ECDH(ecdhPublicKey) 372 if err != nil { 373 return nil, fmt.Errorf("ECDH key agreement failed: %w", err) 374 } 375 376 // Derive AES key from shared secret using helper function 377 aesKey := deriveAESKey(sharedSecret) 378 379 // Encrypt data using AES-GCM 380 encryptedData, iv, tag, err := encryptAESGCM(data, aesKey) 381 if err != nil { 382 return nil, fmt.Errorf("AES-GCM encryption failed: %w", err) 383 } 384 385 // Include ephemeral public key for recipient 386 ephemeralPublicKeyBytes := ephemeralPrivateKey.PublicKey().Bytes() 387 388 return &encryption.EncryptedData{ 389 Algorithm: encryption.AlgorithmECDH, 390 Format: opts.Format, 391 Data: encryptedData, 392 EncryptedKey: ephemeralPublicKeyBytes, // Store ephemeral public key 393 IV: iv, 394 Tag: tag, 395 Timestamp: time.Now(), 396 Metadata: opts.Metadata, 397 }, nil 398 } 399 400 // convertEd25519ToX25519PublicKey is a helper function that wraps the internal crypto package 401 // conversion function. This provides a clean interface while isolating the complex algorithm. 402 func convertEd25519ToX25519PublicKey(ed25519Key ed25519.PublicKey) ([]byte, error) { 403 return crypto.Ed25519ToX25519PublicKey(ed25519Key) 404 } 405 406 // encryptForEd25519PublicKey encrypts data for an Ed25519 public key using ephemeral X25519 key agreement. 407 // This function mirrors the logic from EncryptWithEd25519 but works with just the public key. 408 // 409 // CURRENT STATUS: The RFC 7748 Ed25519 to X25519 conversion is implemented in internal/crypto 410 // but requires additional validation and compatibility work with Go's Ed25519 key format. 411 // The mathematical conversion works but Ed25519 keys have specific encoding requirements 412 // that need proper handling. 413 // 414 // For production use, this currently returns an error with guidance on alternatives. 415 // The implementation infrastructure is in place for future completion. 416 func encryptForEd25519PublicKey(data []byte, publicKey ed25519.PublicKey, opts encryption.EncryptOptions) (*encryption.EncryptedData, error) { 417 // Attempt conversion (implemented but may fail with certain key formats) 418 x25519PublicKeyBytes, err := convertEd25519ToX25519PublicKey(publicKey) 419 if err != nil { 420 return nil, fmt.Errorf("Ed25519 public-key-only encryption failed: %w - use EncryptWithEd25519 with full key pair or envelope.Encrypt for multi-recipient scenarios", err) 421 } 422 423 if err := encryption.ValidateEncryptOptions(opts); err != nil { 424 return nil, err 425 } 426 427 // Create X25519 public key for ECDH 428 curve := ecdh.X25519() 429 x25519PublicKey, err := curve.NewPublicKey(x25519PublicKeyBytes) 430 if err != nil { 431 return nil, fmt.Errorf("failed to create X25519 public key: %w", err) 432 } 433 434 // Generate ephemeral key pair for forward secrecy 435 ephemeralPrivateKey, err := curve.GenerateKey(rand.Reader) 436 if err != nil { 437 return nil, fmt.Errorf("failed to generate ephemeral X25519 key: %w", err) 438 } 439 440 // Perform X25519 key agreement between ephemeral key and converted X25519 public key 441 sharedSecret, err := ephemeralPrivateKey.ECDH(x25519PublicKey) 442 if err != nil { 443 return nil, fmt.Errorf("X25519 key agreement failed: %w", err) 444 } 445 446 // Derive AES key from shared secret 447 aesKey := deriveAESKey(sharedSecret) 448 449 // Encrypt data using AES-GCM 450 encryptedData, iv, tag, err := encryptAESGCM(data, aesKey) 451 if err != nil { 452 return nil, fmt.Errorf("AES-GCM encryption failed: %w", err) 453 } 454 455 return &encryption.EncryptedData{ 456 Algorithm: encryption.AlgorithmX25519, 457 Format: opts.Format, 458 Data: encryptedData, 459 EncryptedKey: ephemeralPrivateKey.PublicKey().Bytes(), // Store ephemeral public key 460 IV: iv, 461 Tag: tag, 462 Timestamp: time.Now(), 463 Metadata: opts.Metadata, 464 }, nil 465 } 466 467 // decryptWithECDSAPrivateKey decrypts ECDH encrypted data using an ECDSA private key. 468 // This function mirrors the logic from DecryptWithECDSA but works with just the private key. 469 func decryptWithECDSAPrivateKey(encrypted *encryption.EncryptedData, privateKey *ecdsa.PrivateKey, opts encryption.DecryptOptions) ([]byte, error) { 470 if encrypted.Algorithm != encryption.AlgorithmECDH { 471 return nil, fmt.Errorf("expected ECDH algorithm for ECDSA private key, got %s", encrypted.Algorithm) 472 } 473 474 // Convert ECDSA private key to ECDH 475 ecdhPrivateKey, err := privateKey.ECDH() 476 if err != nil { 477 return nil, fmt.Errorf("failed to convert ECDSA private key to ECDH: %w", err) 478 } 479 480 // Parse ephemeral public key from ECDH bytes 481 curve := ecdhPrivateKey.Curve() 482 ephemeralECDHKey, err := curve.NewPublicKey(encrypted.EncryptedKey) 483 if err != nil { 484 return nil, fmt.Errorf("failed to parse ephemeral public key: %w", err) 485 } 486 487 // Perform ECDH key agreement 488 sharedSecret, err := ecdhPrivateKey.ECDH(ephemeralECDHKey) 489 if err != nil { 490 return nil, fmt.Errorf("ECDH key agreement failed: %w", err) 491 } 492 493 // Derive AES key from shared secret using helper function 494 aesKey := deriveAESKey(sharedSecret) 495 496 // Decrypt data using AES-GCM 497 plaintext, err := decryptAESGCM(encrypted.Data, aesKey, encrypted.IV, encrypted.Tag) 498 if err != nil { 499 return nil, fmt.Errorf("AES-GCM decryption failed: %w", err) 500 } 501 502 return plaintext, nil 503 } 504 505 // decryptWithEd25519PrivateKey decrypts X25519 encrypted data using an Ed25519 private key. 506 // This function mirrors the logic from DecryptWithEd25519 but works with just the private key. 507 func decryptWithEd25519PrivateKey(encrypted *encryption.EncryptedData, privateKey ed25519.PrivateKey, opts encryption.DecryptOptions) ([]byte, error) { 508 if encrypted.Algorithm != encryption.AlgorithmX25519 { 509 return nil, fmt.Errorf("expected X25519 algorithm for Ed25519 private key, got %s", encrypted.Algorithm) 510 } 511 512 // Convert Ed25519 private key to X25519 format 513 curve := ecdh.X25519() 514 seed := privateKey.Seed() 515 x25519PrivateKey, err := curve.NewPrivateKey(seed) 516 if err != nil { 517 return nil, fmt.Errorf("failed to create X25519 private key from Ed25519 seed: %w", err) 518 } 519 520 // Parse ephemeral public key from encrypted data 521 ephemeralX25519Key, err := curve.NewPublicKey(encrypted.EncryptedKey) 522 if err != nil { 523 return nil, fmt.Errorf("failed to parse ephemeral X25519 public key: %w", err) 524 } 525 526 // Perform X25519 key agreement 527 sharedSecret, err := x25519PrivateKey.ECDH(ephemeralX25519Key) 528 if err != nil { 529 return nil, fmt.Errorf("X25519 key agreement failed: %w", err) 530 } 531 532 // Derive AES key from shared secret using helper function 533 aesKey := deriveAESKey(sharedSecret) 534 535 // Decrypt data using AES-GCM 536 plaintext, err := decryptAESGCM(encrypted.Data, aesKey, encrypted.IV, encrypted.Tag) 537 if err != nil { 538 return nil, fmt.Errorf("AES-GCM decryption failed: %w", err) 539 } 540 541 return plaintext, nil 542 }