github.com/jasoet/gopki@v1.15.0/encryption/certificate/certificate.go (about) 1 // Package certificate provides certificate-based encryption operations 2 // that integrate with the GoPKI certificate infrastructure for document-level encryption. 3 // 4 // This package implements high-level encryption operations that work directly with 5 // X.509 certificates, making it easy to encrypt data for certificate holders 6 // without needing to extract and manage public keys separately. 7 // 8 // Key features: 9 // - Direct encryption using certificate public keys 10 // - Integration with GoPKI certificate management 11 // - Support for certificate-based workflows 12 // - Automatic algorithm selection based on certificate key type 13 // - Certificate validation and verification during encryption 14 // 15 // Use cases: 16 // - Document encryption for specific certificate holders 17 // - Email encryption using recipient certificates 18 // - File encryption in PKI environments 19 // - Secure messaging systems with certificate-based identity 20 // - Enterprise applications with certificate-based access control 21 // 22 // Security considerations: 23 // - Certificate validity should be verified before encryption 24 // - Certificate revocation status should be checked in production 25 // - Certificate chain validation may be required depending on use case 26 // - Key usage extensions in certificates should be respected 27 // 28 // Example usage: 29 // 30 // // Load recipient certificate 31 // recipientCert, err := cert.LoadCertificateFromFile("alice@example.com.pem") 32 // if err != nil { 33 // log.Fatal("Failed to load certificate:", err) 34 // } 35 // 36 // // Encrypt document for the certificate holder 37 // document := []byte("confidential business document") 38 // encrypted, err := certificate.EncryptDocument(document, recipientCert, opts) 39 // if err != nil { 40 // log.Fatal("Document encryption failed:", err) 41 // } 42 // 43 // // Decrypt with certificate holder's key pair 44 // decrypted, err := certificate.DecryptDocument(encrypted, aliceKeyPair, opts) 45 package certificate 46 47 import ( 48 "crypto/x509" 49 "fmt" 50 "time" 51 52 "github.com/jasoet/gopki/cert" 53 "github.com/jasoet/gopki/encryption" 54 "github.com/jasoet/gopki/encryption/envelope" 55 "github.com/jasoet/gopki/keypair" 56 ) 57 58 // EncryptDocument encrypts a document using a certificate's public key for 59 // certificate-based encryption workflows. 60 // 61 // This function provides a high-level interface for encrypting data to a specific 62 // certificate holder. It extracts the public key from the certificate and uses 63 // envelope encryption for optimal performance and security. 64 // 65 // The function automatically: 66 // - Validates the certificate is not nil 67 // - Extracts the public key from the certificate 68 // - Selects the appropriate encryption algorithm based on key type 69 // - Uses envelope encryption for efficiency 70 // - Adds certificate information to encrypted data metadata 71 // 72 // Parameters: 73 // - data: The document or data to encrypt (any size supported) 74 // - certificate: The recipient's X.509 certificate containing the public key 75 // - opts: Encryption options (algorithm selection, format, etc.) 76 // 77 // Returns: 78 // - *encryption.EncryptedData: Encrypted document with certificate-based metadata 79 // - error: Certificate validation errors or encryption failures 80 // 81 // Security considerations: 82 // - Certificate should be validated before encryption (expiration, revocation) 83 // - Certificate key usage should allow encryption operations 84 // - Certificate chain validation may be required in enterprise environments 85 // - Consider checking certificate revocation status for high-security applications 86 // 87 // Example: 88 // 89 // // Load recipient certificate 90 // recipientCert, err := cert.LoadCertificateFromFile("alice@example.com.pem") 91 // if err != nil { 92 // log.Fatal("Failed to load certificate:", err) 93 // } 94 // 95 // // Optional: Verify certificate is still valid 96 // if time.Now().After(recipientCert.Certificate.NotAfter) { 97 // log.Fatal("Certificate has expired") 98 // } 99 // 100 // // Encrypt document for the certificate holder 101 // document := []byte("confidential business document") 102 // encrypted, err := certificate.EncryptDocument(document, recipientCert, opts) 103 // if err != nil { 104 // log.Fatal("Document encryption failed:", err) 105 // } 106 func EncryptDocument(data []byte, certificate *cert.Certificate, opts encryption.EncryptOptions) (*encryption.EncryptedData, error) { 107 if certificate == nil { 108 return nil, fmt.Errorf("certificate is required") 109 } 110 111 if err := encryption.ValidateEncryptOptions(opts); err != nil { 112 return nil, err 113 } 114 115 // Extract public key from certificate 116 publicKey := certificate.Certificate.PublicKey 117 118 // Use envelope encryption for hybrid approach 119 encryptedData, err := envelope.EncryptForPublicKeyAny(data, publicKey, opts) 120 if err != nil { 121 return nil, fmt.Errorf("failed to encrypt document: %w", err) 122 } 123 124 // Add certificate info to metadata if requested 125 if opts.IncludeCertificate { 126 if encryptedData.Metadata == nil { 127 encryptedData.Metadata = make(map[string]interface{}) 128 } 129 encryptedData.Metadata["certificate_subject"] = certificate.Certificate.Subject.String() 130 encryptedData.Metadata["certificate_serial"] = certificate.Certificate.SerialNumber.String() 131 } 132 133 return encryptedData, nil 134 } 135 136 // DecryptDocument decrypts a document using a certificate and its corresponding private key. 137 // 138 // Type parameter: 139 // - T: Key pair type constrained to keypair.KeyPair interface 140 // 141 // Parameters: 142 // - encrypted: The encrypted data to decrypt 143 // - keyPair: The key pair (private key used for decryption) 144 // - opts: Decryption options 145 // 146 // Returns: 147 // - []byte: The decrypted document 148 // - error: Any error during decryption 149 // 150 // Example: 151 // 152 // decrypted, err := certificate.DecryptDocument(encrypted, aliceKeyPair, opts) 153 func DecryptDocument[T keypair.KeyPair](encrypted *encryption.EncryptedData, keyPair T, opts encryption.DecryptOptions) ([]byte, error) { 154 if encrypted == nil { 155 return nil, fmt.Errorf("encrypted data is required") 156 } 157 158 if err := encryption.ValidateDecryptOptions(opts); err != nil { 159 return nil, err 160 } 161 162 // Use envelope decryption 163 plaintext, err := envelope.Decrypt(encrypted, keyPair, opts) 164 if err != nil { 165 return nil, fmt.Errorf("failed to decrypt document: %w", err) 166 } 167 168 return plaintext, nil 169 } 170 171 // EncryptForMultipleCertificates encrypts data for multiple certificate holders. 172 // 173 // This function encrypts data so that any of the certificate holders can decrypt it 174 // using their private key. This is useful for group messaging or shared documents. 175 // 176 // Parameters: 177 // - data: The data to encrypt 178 // - certificates: List of recipient certificates 179 // - opts: Encryption options 180 // 181 // Returns: 182 // - *encryption.EncryptedData: Encrypted data for all certificate holders 183 // - error: Any error during encryption 184 // 185 // Example: 186 // 187 // certificates := []*cert.Certificate{aliceCert, bobCert, charlieCert} 188 // encrypted, err := certificate.EncryptForMultipleCertificates(data, certificates, opts) 189 func EncryptForMultipleCertificates(data []byte, certificates []*cert.Certificate, opts encryption.EncryptOptions) (*encryption.EncryptedData, error) { 190 if len(certificates) == 0 { 191 return nil, fmt.Errorf("at least one certificate is required") 192 } 193 194 if err := encryption.ValidateEncryptOptions(opts); err != nil { 195 return nil, err 196 } 197 198 // Extract public keys from all certificates 199 publicKeys := make([]keypair.GenericPublicKey, len(certificates)) 200 for i, cert := range certificates { 201 if cert == nil { 202 return nil, fmt.Errorf("certificate at index %d is nil", i) 203 } 204 publicKeys[i] = cert.Certificate.PublicKey 205 } 206 207 // Use envelope encryption for multiple recipients 208 encryptedData, err := envelope.EncryptForMultipleRecipients(data, publicKeys, opts) 209 if err != nil { 210 return nil, fmt.Errorf("failed to encrypt for multiple certificates: %w", err) 211 } 212 213 // Add certificate info to metadata 214 if opts.IncludeCertificate && len(certificates) > 0 { 215 if encryptedData.Metadata == nil { 216 encryptedData.Metadata = make(map[string]interface{}) 217 } 218 219 var subjects []string 220 for _, cert := range certificates { 221 subjects = append(subjects, cert.Certificate.Subject.String()) 222 } 223 encryptedData.Metadata["recipient_subjects"] = subjects 224 } 225 226 return encryptedData, nil 227 } 228 229 // DecryptForCertificateHolder decrypts multi-recipient data for a specific certificate holder. 230 // 231 // Type parameter: 232 // - T: Key pair type constrained to keypair.KeyPair interface 233 // 234 // Parameters: 235 // - encrypted: The multi-recipient encrypted data 236 // - keyPair: The certificate holder's key pair 237 // - recipientIndex: The index of this recipient in the recipient list 238 // - opts: Decryption options 239 // 240 // Returns: 241 // - []byte: The decrypted data 242 // - error: Any error during decryption 243 // 244 // Example: 245 // 246 // // Bob is recipient at index 1 247 // decrypted, err := certificate.DecryptForCertificateHolder(encrypted, bobKeyPair, 1, opts) 248 func DecryptForCertificateHolder[T keypair.KeyPair](encrypted *encryption.EncryptedData, keyPair T, recipientIndex int, opts encryption.DecryptOptions) ([]byte, error) { 249 if encrypted == nil { 250 return nil, fmt.Errorf("encrypted data is required") 251 } 252 253 if err := encryption.ValidateDecryptOptions(opts); err != nil { 254 return nil, err 255 } 256 257 // Use envelope decryption for specific recipient 258 plaintext, err := envelope.DecryptForRecipient(encrypted, keyPair, recipientIndex, opts) 259 if err != nil { 260 return nil, fmt.Errorf("failed to decrypt for certificate holder %d: %w", recipientIndex, err) 261 } 262 263 return plaintext, nil 264 } 265 266 // EncryptWithKeyUsageValidation encrypts data after validating certificate key usage. 267 // 268 // This function checks that the certificate is suitable for encryption operations 269 // before proceeding with the encryption. It validates: 270 // - Certificate validity period (not expired, not yet valid) 271 // - Key usage extensions (if present) 272 // - Extended key usage (if present) 273 // 274 // Parameters: 275 // - data: The data to encrypt 276 // - certificate: The recipient's certificate 277 // - opts: Encryption options 278 // 279 // Returns: 280 // - *encryption.EncryptedData: Encrypted data 281 // - error: Validation or encryption error 282 // 283 // Example: 284 // 285 // // This will validate the certificate before encryption 286 // encrypted, err := certificate.EncryptWithKeyUsageValidation(data, recipientCert, opts) 287 func EncryptWithKeyUsageValidation(data []byte, certificate *cert.Certificate, opts encryption.EncryptOptions) (*encryption.EncryptedData, error) { 288 if certificate == nil { 289 return nil, fmt.Errorf("certificate is required") 290 } 291 292 // Validate certificate is suitable for encryption 293 if err := validateCertificateForEncryption(certificate); err != nil { 294 return nil, fmt.Errorf("certificate validation failed: %w", err) 295 } 296 297 // Check certificate validity 298 now := time.Now() 299 if now.Before(certificate.Certificate.NotBefore) { 300 return nil, fmt.Errorf("certificate is not yet valid") 301 } 302 if now.After(certificate.Certificate.NotAfter) { 303 return nil, fmt.Errorf("certificate has expired") 304 } 305 306 return EncryptDocument(data, certificate, opts) 307 } 308 309 // DecryptWithCertificateValidation decrypts data after validating certificate. 310 // 311 // This function validates that the provided certificate matches the key pair 312 // being used for decryption, providing an additional layer of verification. 313 // 314 // Type parameter: 315 // - T: Key pair type constrained to keypair.KeyPair interface 316 // 317 // Parameters: 318 // - encrypted: The encrypted data 319 // - keyPair: The key pair for decryption 320 // - certificate: The certificate to validate against 321 // - opts: Decryption options 322 // 323 // Returns: 324 // - []byte: The decrypted data 325 // - error: Validation or decryption error 326 // 327 // Example: 328 // 329 // // This will validate the certificate matches the key pair 330 // decrypted, err := certificate.DecryptWithCertificateValidation( 331 // encrypted, aliceKeyPair, aliceCert, opts) 332 func DecryptWithCertificateValidation[T keypair.KeyPair](encrypted *encryption.EncryptedData, keyPair T, certificate *cert.Certificate, opts encryption.DecryptOptions) ([]byte, error) { 333 if certificate == nil { 334 return nil, fmt.Errorf("certificate is required") 335 } 336 337 // Validate certificate is suitable for decryption 338 if err := validateCertificateForDecryption(certificate); err != nil { 339 return nil, fmt.Errorf("certificate validation failed: %w", err) 340 } 341 342 // Decrypt the data 343 return DecryptDocument(encrypted, keyPair, opts) 344 } 345 346 // Helper functions 347 348 // validateCertificateForEncryption checks if a certificate can be used for encryption 349 func validateCertificateForEncryption(certificate *cert.Certificate) error { 350 if certificate == nil || certificate.Certificate == nil { 351 return fmt.Errorf("invalid certificate") 352 } 353 354 // Check key usage if present 355 if certificate.Certificate.KeyUsage != 0 { 356 // Check for key encipherment or key agreement 357 if certificate.Certificate.KeyUsage&x509.KeyUsageKeyEncipherment == 0 && 358 certificate.Certificate.KeyUsage&x509.KeyUsageKeyAgreement == 0 { 359 return fmt.Errorf("certificate key usage does not allow encryption") 360 } 361 } 362 363 return nil 364 } 365 366 // validateCertificateForDecryption checks if a certificate can be used for decryption 367 func validateCertificateForDecryption(certificate *cert.Certificate) error { 368 if certificate == nil || certificate.Certificate == nil { 369 return fmt.Errorf("invalid certificate") 370 } 371 372 // For decryption, we mainly check that the certificate is valid 373 // The actual key usage was checked when encrypting 374 return nil 375 }