github.com/jasoet/gopki@v1.15.0/signing/signing.go (about)

     1  // Package signing provides document signing and signature verification functionality
     2  // using certificates and various cryptographic algorithms (RSA, ECDSA, Ed25519).
     3  package signing
     4  
     5  import (
     6  	"crypto"
     7  	"crypto/x509"
     8  	"errors"
     9  	"time"
    10  )
    11  
    12  // SignatureFormat represents the format of a digital signature
    13  type SignatureFormat string
    14  
    15  const (
    16  	// FormatPKCS7 represents a PKCS#7/CMS signature format (attached)
    17  	FormatPKCS7 SignatureFormat = "pkcs7"
    18  	// FormatPKCS7Detached represents a detached PKCS#7/CMS signature
    19  	FormatPKCS7Detached SignatureFormat = "pkcs7-detached"
    20  )
    21  
    22  // SignatureAlgorithm represents the algorithm used for signing
    23  type SignatureAlgorithm string
    24  
    25  const (
    26  	AlgorithmRSA     SignatureAlgorithm = "RSA"
    27  	AlgorithmECDSA   SignatureAlgorithm = "ECDSA"
    28  	AlgorithmEd25519 SignatureAlgorithm = "Ed25519"
    29  )
    30  
    31  // Signature represents a digital signature with its metadata
    32  type Signature struct {
    33  	// Format of the signature (PKCS#7, CMS, etc.)
    34  	Format SignatureFormat
    35  	// Algorithm used for signing
    36  	Algorithm SignatureAlgorithm
    37  	// Hash algorithm used (SHA256, SHA384, SHA512)
    38  	HashAlgorithm crypto.Hash
    39  	// The actual signature bytes
    40  	Data []byte
    41  	// Original data digest (hash)
    42  	Digest []byte
    43  	// Signer's certificate
    44  	Certificate *x509.Certificate
    45  	// Certificate chain (optional)
    46  	CertificateChain []*x509.Certificate
    47  	// Timestamp information (optional)
    48  	Timestamp *Timestamp
    49  	// Additional metadata
    50  	Metadata map[string]interface{}
    51  }
    52  
    53  // Timestamp represents a cryptographic timestamp from a Time Stamping Authority
    54  type Timestamp struct {
    55  	// Time when the signature was created
    56  	Time time.Time
    57  	// TSA certificate
    58  	Certificate *x509.Certificate
    59  	// Timestamp token (RFC 3161)
    60  	Token []byte
    61  	// Hash algorithm used by TSA
    62  	HashAlgorithm crypto.Hash
    63  }
    64  
    65  // SignatureInfo contains parsed signature information from PKCS#7 signatures
    66  type SignatureInfo struct {
    67  	// Signature algorithm used (e.g., "PKCS#7")
    68  	Algorithm string
    69  	// Hash algorithm used
    70  	HashAlgorithm crypto.Hash
    71  	// Signer's certificate
    72  	Certificate *x509.Certificate
    73  	// Certificate chain
    74  	CertificateChain []*x509.Certificate
    75  	// Timestamp information
    76  	Timestamp *Timestamp
    77  	// Additional attributes
    78  	Attributes map[string]interface{}
    79  	// Whether this is a detached signature
    80  	Detached bool
    81  }
    82  
    83  // SignOptions configures the signing operation
    84  type SignOptions struct {
    85  	// Hash algorithm to use (default: SHA256)
    86  	HashAlgorithm crypto.Hash
    87  	// Signature format (default: FormatPKCS7)
    88  	Format SignatureFormat
    89  	// Include signer's certificate in signature
    90  	IncludeCertificate bool
    91  	// Include certificate chain in signature
    92  	IncludeChain bool
    93  	// Create detached signature (data not included)
    94  	Detached bool
    95  	// Timestamp server URL (optional)
    96  	TimestampURL string
    97  	// Additional attributes to include
    98  	Attributes map[string]interface{}
    99  	// Additional certificates to include
   100  	ExtraCertificates []*x509.Certificate
   101  }
   102  
   103  // VerifyOptions configures the verification operation
   104  type VerifyOptions struct {
   105  	// Required certificate purposes (e.g., digitalSignature)
   106  	RequiredKeyUsage x509.KeyUsage
   107  	// Required extended key usage (e.g., codeSignature)
   108  	RequiredExtKeyUsage []x509.ExtKeyUsage
   109  	// Verify certificate chain
   110  	VerifyChain bool
   111  	// Root certificates for chain verification
   112  	Roots *x509.CertPool
   113  	// Intermediate certificates for chain verification
   114  	Intermediates *x509.CertPool
   115  	// Time to verify certificate validity (default: now)
   116  	VerifyTime time.Time
   117  }
   118  
   119  // Common errors
   120  var (
   121  	ErrInvalidSignature       = errors.New("invalid signature")
   122  	ErrCertificateExpired     = errors.New("certificate has expired")
   123  	ErrCertificateNotYetValid = errors.New("certificate is not yet valid")
   124  	ErrInvalidCertificate     = errors.New("invalid certificate")
   125  	ErrUnsupportedAlgorithm   = errors.New("unsupported algorithm")
   126  	ErrUnsupportedFormat      = errors.New("unsupported signature format")
   127  	ErrMissingPrivateKey      = errors.New("missing private key")
   128  	ErrMissingCertificate     = errors.New("missing certificate")
   129  	ErrVerificationFailed     = errors.New("signature verification failed")
   130  	ErrInvalidTimestamp       = errors.New("invalid timestamp")
   131  )
   132  
   133  // DefaultSignOptions returns default signing options with secure defaults.
   134  // These options are suitable for most signing scenarios and provide a good
   135  // balance between security and compatibility.
   136  //
   137  // Default values:
   138  //   - HashAlgorithm: 0 (auto-selected based on key algorithm and size)
   139  //   - Format: FormatPKCS7 (industry-standard PKCS#7/CMS format)
   140  //   - IncludeCertificate: true (includes signer's certificate)
   141  //   - IncludeChain: false (certificate chain not included)
   142  //   - Detached: false (signature includes the data)
   143  //
   144  // Returns SignOptions with secure default values.
   145  //
   146  // Example:
   147  //
   148  //	opts := DefaultSignOptions()
   149  //	opts.Format = FormatPKCS7  // Override format if needed
   150  //	signature, err := SignDocument(data, keyPair, cert, opts)
   151  func DefaultSignOptions() SignOptions {
   152  	return SignOptions{
   153  		HashAlgorithm:      0, // Let the algorithm determine the default
   154  		Format:             FormatPKCS7,
   155  		IncludeCertificate: true,
   156  		IncludeChain:       false,
   157  		Detached:           false,
   158  	}
   159  }
   160  
   161  // DefaultVerifyOptions returns default verification options with secure defaults.
   162  // These options provide basic signature verification without requiring complex
   163  // certificate chain validation, making them suitable for simple use cases.
   164  //
   165  // Default values:
   166  //   - RequiredKeyUsage: x509.KeyUsageDigitalSignature (requires digital signature capability)
   167  //   - VerifyChain: false (skips certificate chain verification for self-signed certificates)
   168  //   - VerifyTime: time.Now() (verifies certificate validity at current time)
   169  //
   170  // For production environments with proper PKI infrastructure, consider enabling
   171  // chain verification and providing root/intermediate certificate pools.
   172  //
   173  // Returns VerifyOptions with secure default values.
   174  //
   175  // Example:
   176  //
   177  //	opts := DefaultVerifyOptions()
   178  //	opts.VerifyChain = true              // Enable chain verification
   179  //	opts.Roots = rootCertPool            // Add trusted root certificates
   180  //	err := VerifySignature(data, signature, opts)
   181  func DefaultVerifyOptions() VerifyOptions {
   182  	return VerifyOptions{
   183  		RequiredKeyUsage: x509.KeyUsageDigitalSignature,
   184  		VerifyChain:      false, // Skip chain verification for self-signed certs
   185  		VerifyTime:       time.Now(),
   186  	}
   187  }
   188  
   189  // GetHashAlgorithm returns the appropriate hash algorithm for the signature algorithm.
   190  // It selects the hash algorithm based on the signing algorithm and key size for optimal security.
   191  //
   192  // Algorithm recommendations:
   193  //   - RSA: SHA-256 for keys < 3072 bits, SHA-384 for keys >= 3072 bits
   194  //   - ECDSA: SHA-256 for P-256/P-224, SHA-384 for P-384, SHA-512 for P-521
   195  //   - Ed25519: SHA-512 (used internally by Ed25519)
   196  //
   197  // Parameters:
   198  //   - algo: The signature algorithm (RSA, ECDSA, or Ed25519)
   199  //   - keySize: The key size in bits
   200  //
   201  // Returns the recommended crypto.Hash for the given algorithm and key size.
   202  //
   203  // Example:
   204  //
   205  //	hash := GetHashAlgorithm(AlgorithmRSA, 2048)  // Returns crypto.SHA256
   206  //	hash = GetHashAlgorithm(AlgorithmRSA, 4096)   // Returns crypto.SHA384
   207  func GetHashAlgorithm(algo SignatureAlgorithm, keySize int) crypto.Hash {
   208  	switch algo {
   209  	case AlgorithmRSA:
   210  		if keySize >= 3072 {
   211  			return crypto.SHA384
   212  		}
   213  		return crypto.SHA256
   214  	case AlgorithmECDSA:
   215  		if keySize >= 384 {
   216  			return crypto.SHA384
   217  		}
   218  		return crypto.SHA256
   219  	case AlgorithmEd25519:
   220  		// Ed25519 uses SHA-512 internally
   221  		return crypto.SHA512
   222  	default:
   223  		return crypto.SHA256
   224  	}
   225  }