github.com/jasoet/gopki@v1.15.0/signing/signer.go (about) 1 package signing 2 3 import ( 4 "crypto" 5 "crypto/ecdsa" 6 "crypto/ed25519" 7 "crypto/rand" 8 "crypto/rsa" 9 "crypto/x509" 10 "encoding/asn1" 11 "fmt" 12 "io" 13 "os" 14 15 "github.com/jasoet/gopki/cert" 16 internalcrypto "github.com/jasoet/gopki/internal/crypto" 17 "github.com/jasoet/gopki/keypair" 18 "github.com/jasoet/gopki/keypair/algo" 19 "github.com/smallstep/pkcs7" 20 ) 21 22 // SignDocument signs a document using the provided key pair and certificate. 23 // This is the primary function for creating digital signatures with full control 24 // over signing options and formats. 25 // 26 // The function supports all major cryptographic algorithms: 27 // - RSA with PKCS#1 v1.5 padding 28 // - ECDSA with ASN.1 DER encoding 29 // - Ed25519 with native signature format 30 // 31 // Type parameter: 32 // - T: Key pair type (*algo.RSAKeyPair, *algo.ECDSAKeyPair, or *algo.Ed25519KeyPair) 33 // 34 // Parameters: 35 // - data: The data to be signed (must not be empty) 36 // - keyPair: The cryptographic key pair for signing 37 // - certificate: The X.509 certificate associated with the signing key 38 // - opts: Signing options (format, hash algorithm, certificate inclusion, etc.) 39 // 40 // Returns a Signature containing the signature data, metadata, and certificate information, 41 // or an error if signing fails. 42 // 43 // The function automatically selects the appropriate hash algorithm if not specified 44 // in the options, based on the key type and size for optimal security. 45 // 46 // Supported formats: 47 // - FormatPKCS7: PKCS#7/CMS signature container (default) 48 // - FormatPKCS7Detached: Detached PKCS#7/CMS signature 49 // 50 // Example: 51 // 52 // opts := DefaultSignOptions() 53 // opts.Format = FormatPKCS7 54 // opts.IncludeChain = true 55 // 56 // signature, err := SignDocument(document, rsaKeyPair, certificate, opts) 57 // if err != nil { 58 // log.Printf("Signing failed: %v", err) 59 // return 60 // } 61 // 62 // fmt.Printf("Created %s signature using %s\n", signature.Format, signature.Algorithm) 63 func SignDocument[T keypair.KeyPair](data []byte, keyPair T, certificate *cert.Certificate, opts SignOptions) (*Signature, error) { 64 if len(data) == 0 { 65 return nil, fmt.Errorf("cannot sign empty data") 66 } 67 68 if certificate == nil || certificate.Certificate == nil { 69 return nil, ErrMissingCertificate 70 } 71 72 // Determine the algorithm and extract private key 73 var privateKey crypto.Signer 74 var algorithm SignatureAlgorithm 75 76 switch kp := any(keyPair).(type) { 77 case *algo.RSAKeyPair: 78 privateKey = kp.PrivateKey 79 algorithm = AlgorithmRSA 80 case *algo.ECDSAKeyPair: 81 privateKey = kp.PrivateKey 82 algorithm = AlgorithmECDSA 83 case *algo.Ed25519KeyPair: 84 privateKey = kp.PrivateKey 85 algorithm = AlgorithmEd25519 86 default: 87 return nil, ErrUnsupportedAlgorithm 88 } 89 90 // Use default options if hash algorithm not specified 91 if opts.HashAlgorithm == 0 { 92 opts.HashAlgorithm = getDefaultHashAlgorithm(algorithm, privateKey) 93 } 94 95 var signatureData []byte 96 97 // Use PKCS#7 for all algorithms including Ed25519 (now supported via internal implementation) 98 if algorithm == AlgorithmEd25519 { 99 // Use our custom Ed25519 PKCS#7 implementation (RFC 8419) 100 ed25519PrivKey, ok := privateKey.(ed25519.PrivateKey) 101 if !ok { 102 return nil, fmt.Errorf("invalid Ed25519 private key type") 103 } 104 105 // Use RFC 8419 ASN.1 Ed25519 PKCS#7 format 106 pkcs7Data, err := internalcrypto.CreateEd25519PKCS7Signature(data, ed25519PrivKey, certificate.Certificate, opts.Detached) 107 if err != nil { 108 return nil, fmt.Errorf("failed to create Ed25519 PKCS#7 signature: %w", err) 109 } 110 signatureData = pkcs7Data 111 } else { 112 // Use PKCS#7 for RSA and ECDSA 113 signedData, err := pkcs7.NewSignedData(data) 114 if err != nil { 115 return nil, fmt.Errorf("failed to create signed data: %w", err) 116 } 117 118 // Set digest algorithm if specified 119 if opts.HashAlgorithm != 0 { 120 digestOID, err := getDigestAlgorithmOID(opts.HashAlgorithm) 121 if err != nil { 122 return nil, fmt.Errorf("unsupported hash algorithm: %w", err) 123 } 124 signedData.SetDigestAlgorithm(digestOID) 125 } 126 127 // Add signer 128 signerConfig := pkcs7.SignerInfoConfig{} 129 err = signedData.AddSigner(certificate.Certificate, privateKey, signerConfig) 130 if err != nil { 131 return nil, fmt.Errorf("failed to add signer: %w", err) 132 } 133 134 // Add certificates if requested 135 if opts.IncludeCertificate { 136 signedData.AddCertificate(certificate.Certificate) 137 } 138 139 // Add extra certificates 140 for _, extraCert := range opts.ExtraCertificates { 141 signedData.AddCertificate(extraCert) 142 } 143 144 // Create detached signature if requested 145 if opts.Format == FormatPKCS7Detached { 146 signedData.Detach() 147 } 148 149 // Finalize and get signature data 150 signatureData, err = signedData.Finish() 151 if err != nil { 152 return nil, fmt.Errorf("failed to finalize signature: %w", err) 153 } 154 } 155 156 // Compute digest for metadata (some formats may need this separately) 157 var digest []byte 158 if algorithm == AlgorithmEd25519 { 159 // For Ed25519, we still compute the digest for metadata purposes 160 hasher := opts.HashAlgorithm.New() 161 if _, err := hasher.Write(data); err != nil { 162 return nil, fmt.Errorf("failed to hash data for metadata: %w", err) 163 } 164 digest = hasher.Sum(nil) 165 } else { 166 // For other algorithms, compute the digest normally 167 hasher := opts.HashAlgorithm.New() 168 if _, err := hasher.Write(data); err != nil { 169 return nil, fmt.Errorf("failed to hash data: %w", err) 170 } 171 digest = hasher.Sum(nil) 172 } 173 174 // Create the signature object 175 sig := &Signature{ 176 Format: opts.Format, 177 Algorithm: algorithm, 178 HashAlgorithm: opts.HashAlgorithm, 179 Data: signatureData, 180 Digest: digest, 181 Metadata: opts.Attributes, 182 } 183 184 // Include certificate if requested (format may have already included it) 185 if opts.IncludeCertificate { 186 sig.Certificate = certificate.Certificate 187 } 188 189 // Include certificate chain if requested 190 if opts.IncludeChain && len(certificate.Certificate.Raw) > 0 { 191 // For now, just include the signing certificate 192 // In a full implementation, we would build the complete chain 193 sig.CertificateChain = []*x509.Certificate{certificate.Certificate} 194 } 195 196 return sig, nil 197 } 198 199 // SignData is a convenience function for signing data with default options. 200 // This function provides a simple interface for common signing scenarios where 201 // default settings are sufficient. 202 // 203 // The function uses DefaultSignOptions() which provides: 204 // - PKCS#7/CMS signature format 205 // - Auto-selected hash algorithm 206 // - Certificate inclusion enabled 207 // - Non-detached signature 208 // 209 // Type parameter: 210 // - T: Key pair type (*algo.RSAKeyPair, *algo.ECDSAKeyPair, or *algo.Ed25519KeyPair) 211 // 212 // Parameters: 213 // - data: The data to be signed 214 // - keyPair: The cryptographic key pair for signing 215 // - certificate: The X.509 certificate associated with the signing key 216 // 217 // Returns a Signature with default options applied, or an error if signing fails. 218 // 219 // For more control over signing parameters, use SignDocument() with custom options. 220 // 221 // Example: 222 // 223 // signature, err := SignData(document, rsaKeyPair, certificate) 224 // if err != nil { 225 // log.Printf("Signing failed: %v", err) 226 // return 227 // } 228 // 229 // // Verify the signature 230 // err = VerifySignature(document, signature, DefaultVerifyOptions()) 231 func SignData[T keypair.KeyPair](data []byte, keyPair T, certificate *cert.Certificate) (*Signature, error) { 232 return SignDocument(data, keyPair, certificate, DefaultSignOptions()) 233 } 234 235 // SignFile signs a file and returns the signature. 236 // This convenience function reads a file from disk and signs its contents 237 // using the specified options. 238 // 239 // The function reads the entire file into memory, so it may not be suitable 240 // for very large files. For streaming large files, use SignStream() instead. 241 // 242 // Type parameter: 243 // - T: Key pair type (*algo.RSAKeyPair, *algo.ECDSAKeyPair, or *algo.Ed25519KeyPair) 244 // 245 // Parameters: 246 // - filePath: Path to the file to be signed 247 // - keyPair: The cryptographic key pair for signing 248 // - certificate: The X.509 certificate associated with the signing key 249 // - opts: Signing options (format, hash algorithm, certificate inclusion, etc.) 250 // 251 // Returns a Signature for the file contents, or an error if reading or signing fails. 252 // 253 // Example: 254 // 255 // opts := DefaultSignOptions() 256 // opts.Format = FormatPKCS7Detached 257 // 258 // signature, err := SignFile("/path/to/document.pdf", rsaKeyPair, certificate, opts) 259 // if err != nil { 260 // log.Printf("File signing failed: %v", err) 261 // return 262 // } 263 // 264 // // Save signature to a separate file 265 // err = os.WriteFile("/path/to/document.pdf.sig", signature.Data, 0644) 266 func SignFile[T keypair.KeyPair](filePath string, keyPair T, certificate *cert.Certificate, opts SignOptions) (*Signature, error) { 267 data, err := readFile(filePath) 268 if err != nil { 269 return nil, fmt.Errorf("failed to read file: %w", err) 270 } 271 272 return SignDocument(data, keyPair, certificate, opts) 273 } 274 275 // SignStream signs data from a reader, supporting streaming for large data. 276 // This function is optimized for processing large amounts of data that may not 277 // fit comfortably in memory. 278 // 279 // Algorithm-specific behavior: 280 // - RSA/ECDSA: Stream data through hash function, then sign the digest 281 // - Ed25519: Must read entire data into memory (Ed25519 requirement) 282 // 283 // This function is ideal for signing large files, network streams, or any 284 // data source where memory usage needs to be controlled. 285 // 286 // Type parameter: 287 // - T: Key pair type (*algo.RSAKeyPair, *algo.ECDSAKeyPair, or *algo.Ed25519KeyPair) 288 // 289 // Parameters: 290 // - reader: io.Reader providing the data to be signed 291 // - keyPair: The cryptographic key pair for signing 292 // - certificate: The X.509 certificate associated with the signing key 293 // - opts: Signing options (format, hash algorithm, certificate inclusion, etc.) 294 // 295 // Returns a Signature for the streamed data, or an error if reading or signing fails. 296 // 297 // Note: For Ed25519 signatures, the entire stream will be read into memory due to 298 // algorithm requirements. For memory-constrained environments with large data, 299 // consider using RSA or ECDSA algorithms instead. 300 // 301 // Example: 302 // 303 // file, err := os.Open("/path/to/large-file.bin") 304 // if err != nil { 305 // log.Fatal(err) 306 // } 307 // defer file.Close() 308 // 309 // opts := DefaultSignOptions() 310 // opts.HashAlgorithm = crypto.SHA256 311 // 312 // signature, err := SignStream(file, ecdsaKeyPair, certificate, opts) 313 // if err != nil { 314 // log.Printf("Stream signing failed: %v", err) 315 // return 316 // } 317 func SignStream[T keypair.KeyPair](reader io.Reader, keyPair T, certificate *cert.Certificate, opts SignOptions) (*Signature, error) { 318 // Determine the algorithm and extract private key 319 var privateKey crypto.Signer 320 var algorithm SignatureAlgorithm 321 322 switch kp := any(keyPair).(type) { 323 case *algo.RSAKeyPair: 324 privateKey = kp.PrivateKey 325 algorithm = AlgorithmRSA 326 case *algo.ECDSAKeyPair: 327 privateKey = kp.PrivateKey 328 algorithm = AlgorithmECDSA 329 case *algo.Ed25519KeyPair: 330 privateKey = kp.PrivateKey 331 algorithm = AlgorithmEd25519 332 default: 333 return nil, ErrUnsupportedAlgorithm 334 } 335 336 // Use default options if hash algorithm not specified 337 if opts.HashAlgorithm == 0 { 338 opts.HashAlgorithm = getDefaultHashAlgorithm(algorithm, privateKey) 339 } 340 341 var digest []byte 342 var signatureData []byte 343 var err error 344 345 if algorithm == AlgorithmEd25519 { 346 // Ed25519 needs the full message, so we need to read it all into memory 347 data, err := io.ReadAll(reader) 348 if err != nil { 349 return nil, fmt.Errorf("failed to read stream data: %w", err) 350 } 351 352 // Compute digest for metadata 353 hasher := opts.HashAlgorithm.New() 354 hasher.Write(data) 355 digest = hasher.Sum(nil) 356 357 // Sign the message directly 358 signatureData, err = privateKey.Sign(rand.Reader, data, crypto.Hash(0)) 359 } else { 360 // For RSA/ECDSA, stream and hash the data 361 hasher := opts.HashAlgorithm.New() 362 if _, err := io.Copy(hasher, reader); err != nil { 363 return nil, fmt.Errorf("failed to read and hash stream: %w", err) 364 } 365 digest = hasher.Sum(nil) 366 367 // Sign the digest 368 signatureData, err = privateKey.Sign(rand.Reader, digest, opts.HashAlgorithm) 369 } 370 371 if err != nil { 372 return nil, fmt.Errorf("failed to sign data: %w", err) 373 } 374 375 // Create the signature object 376 sig := &Signature{ 377 Format: opts.Format, 378 Algorithm: algorithm, 379 HashAlgorithm: opts.HashAlgorithm, 380 Data: signatureData, 381 Digest: digest, 382 Certificate: certificate.Certificate, 383 Metadata: opts.Attributes, 384 } 385 386 return sig, nil 387 } 388 389 // getDefaultHashAlgorithm returns the default hash algorithm for a given signing algorithm 390 func getDefaultHashAlgorithm(algo SignatureAlgorithm, signer crypto.Signer) crypto.Hash { 391 switch algo { 392 case AlgorithmRSA: 393 if rsaKey, ok := signer.(*rsa.PrivateKey); ok { 394 if rsaKey.N.BitLen() >= 3072 { 395 return crypto.SHA384 396 } 397 } 398 return crypto.SHA256 399 case AlgorithmECDSA: 400 if ecdsaKey, ok := signer.(*ecdsa.PrivateKey); ok { 401 switch ecdsaKey.Curve.Params().BitSize { 402 case 521: 403 return crypto.SHA512 404 case 384: 405 return crypto.SHA384 406 default: 407 return crypto.SHA256 408 } 409 } 410 return crypto.SHA256 411 case AlgorithmEd25519: 412 // Ed25519 always uses SHA-512 internally 413 return crypto.SHA512 414 default: 415 return crypto.SHA256 416 } 417 } 418 419 // readFile reads a file and returns its contents 420 func readFile(path string) ([]byte, error) { 421 return os.ReadFile(path) 422 } 423 424 // Utility functions for working with signatures 425 426 // GetSignatureAlgorithm determines the signature algorithm from a public key. 427 // This function examines the type of the public key and returns the corresponding 428 // signature algorithm identifier. 429 // 430 // Supported key types: 431 // - *rsa.PublicKey: Returns AlgorithmRSA 432 // - *ecdsa.PublicKey: Returns AlgorithmECDSA 433 // - ed25519.PublicKey: Returns AlgorithmEd25519 434 // 435 // Parameters: 436 // - publicKey: The public key to analyze (crypto.PublicKey interface) 437 // 438 // Returns the corresponding SignatureAlgorithm, or an error if the key type 439 // is not supported. 440 // 441 // This function is commonly used when verifying signatures where the algorithm 442 // needs to be determined from certificate or key material. 443 // 444 // Example: 445 // 446 // cert, err := x509.ParseCertificate(certDER) 447 // if err != nil { 448 // log.Fatal(err) 449 // } 450 // 451 // algorithm, err := GetSignatureAlgorithm(cert.PublicKey) 452 // if err != nil { 453 // log.Printf("Unsupported key algorithm: %v", err) 454 // return 455 // } 456 // 457 // fmt.Printf("Certificate uses %s algorithm\n", algorithm) 458 func GetSignatureAlgorithm(publicKey crypto.PublicKey) (SignatureAlgorithm, error) { 459 switch publicKey.(type) { 460 case *rsa.PublicKey: 461 return AlgorithmRSA, nil 462 case *ecdsa.PublicKey: 463 return AlgorithmECDSA, nil 464 case ed25519.PublicKey: 465 return AlgorithmEd25519, nil 466 default: 467 return "", ErrUnsupportedAlgorithm 468 } 469 } 470 471 // ComputeDigest computes the hash of data using the specified algorithm. 472 // This utility function provides a convenient way to compute cryptographic 473 // hashes with proper error handling and availability checking. 474 // 475 // Supported hash algorithms include: 476 // - crypto.SHA256: 256-bit SHA-2 (most common) 477 // - crypto.SHA384: 384-bit SHA-2 478 // - crypto.SHA512: 512-bit SHA-2 479 // - crypto.SHA224: 224-bit SHA-2 480 // - And other algorithms supported by the Go crypto package 481 // 482 // Parameters: 483 // - data: The data to hash 484 // - hashAlgo: The cryptographic hash algorithm to use 485 // 486 // Returns the computed hash digest as a byte slice, or an error if the 487 // hash algorithm is not available or hashing fails. 488 // 489 // The function verifies that the requested hash algorithm is available 490 // before attempting to use it, preventing runtime panics. 491 // 492 // Example: 493 // 494 // data := []byte("Hello, world!") 495 // digest, err := ComputeDigest(data, crypto.SHA256) 496 // if err != nil { 497 // log.Printf("Hashing failed: %v", err) 498 // return 499 // } 500 // 501 // fmt.Printf("SHA-256 digest: %x\n", digest) 502 func ComputeDigest(data []byte, hashAlgo crypto.Hash) ([]byte, error) { 503 if !hashAlgo.Available() { 504 return nil, fmt.Errorf("hash algorithm %v is not available", hashAlgo) 505 } 506 507 hasher := hashAlgo.New() 508 if _, err := hasher.Write(data); err != nil { 509 return nil, fmt.Errorf("failed to hash data: %w", err) 510 } 511 512 return hasher.Sum(nil), nil 513 } 514 515 // HashAlgorithmFromString converts a string to a crypto.Hash. 516 // This function provides a convenient way to parse hash algorithm names 517 // from configuration files, command-line arguments, or API parameters. 518 // 519 // Supported algorithm names (case-sensitive): 520 // - "SHA256": crypto.SHA256 (default if unknown) 521 // - "SHA384": crypto.SHA384 522 // - "SHA512": crypto.SHA512 523 // - "SHA224": crypto.SHA224 524 // 525 // Parameters: 526 // - name: The hash algorithm name as a string 527 // 528 // Returns the corresponding crypto.Hash constant, or crypto.SHA256 529 // as a safe default for unrecognized names. 530 // 531 // Example: 532 // 533 // algorithm := HashAlgorithmFromString("SHA384") 534 // digest, err := ComputeDigest(data, algorithm) 535 func HashAlgorithmFromString(name string) crypto.Hash { 536 switch name { 537 case "SHA256": 538 return crypto.SHA256 539 case "SHA384": 540 return crypto.SHA384 541 case "SHA512": 542 return crypto.SHA512 543 case "SHA224": 544 return crypto.SHA224 545 default: 546 return crypto.SHA256 547 } 548 } 549 550 // HashAlgorithmToString converts a crypto.Hash to a string representation. 551 // This function provides a convenient way to display hash algorithm names 552 // in logs, error messages, or API responses. 553 // 554 // Supported hash algorithms: 555 // - crypto.SHA256: Returns "SHA256" 556 // - crypto.SHA384: Returns "SHA384" 557 // - crypto.SHA512: Returns "SHA512" 558 // - crypto.SHA224: Returns "SHA224" 559 // - Others: Returns "Unknown" 560 // 561 // Parameters: 562 // - hash: The crypto.Hash constant to convert 563 // 564 // Returns the string representation of the hash algorithm, or "Unknown" 565 // for unrecognized algorithms. 566 // 567 // Example: 568 // 569 // fmt.Printf("Using hash algorithm: %s\n", HashAlgorithmToString(crypto.SHA256)) 570 // // Output: Using hash algorithm: SHA256 571 func HashAlgorithmToString(hash crypto.Hash) string { 572 switch hash { 573 case crypto.SHA256: 574 return "SHA256" 575 case crypto.SHA384: 576 return "SHA384" 577 case crypto.SHA512: 578 return "SHA512" 579 case crypto.SHA224: 580 return "SHA224" 581 default: 582 return "Unknown" 583 } 584 } 585 586 // getDigestAlgorithmOID returns the ASN.1 OID for the given hash algorithm 587 // to be used with the Mozilla PKCS#7 library. 588 func getDigestAlgorithmOID(hash crypto.Hash) (asn1.ObjectIdentifier, error) { 589 switch hash { 590 case crypto.SHA256: 591 return asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1}, nil // sha256 592 case crypto.SHA384: 593 return asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 2}, nil // sha384 594 case crypto.SHA512: 595 return asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3}, nil // sha512 596 case crypto.SHA224: 597 return asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 4}, nil // sha224 598 default: 599 return nil, fmt.Errorf("unsupported hash algorithm: %v", hash) 600 } 601 }