github.com/jasoet/gopki@v1.15.0/internal/crypto/ed25519_pkcs7.go (about)

     1  package crypto
     2  
     3  import (
     4  	"crypto/ed25519"
     5  	"crypto/x509"
     6  	"encoding/asn1"
     7  	"fmt"
     8  	"math/big"
     9  	"time"
    10  )
    11  
    12  // RFC 8419: Edwards-Curve Digital Signature Algorithm (EdDSA) Signatures in CMS
    13  // https://tools.ietf.org/rfc/rfc8419.txt
    14  
    15  // Ed25519 OIDs as defined in RFC 8419
    16  var (
    17  	// OID for Ed25519 signature algorithm
    18  	oidEd25519 = asn1.ObjectIdentifier{1, 3, 101, 112}
    19  
    20  	// OID for SHA-512 digest algorithm (though Ed25519 doesn't use traditional hashing)
    21  	oidSHA512 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3}
    22  
    23  	// OID for PKCS#7 signedData
    24  	oidSignedData = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 7, 2}
    25  
    26  	// OID for PKCS#7 data
    27  	oidData = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 7, 1}
    28  )
    29  
    30  // algorithmIdentifier represents an algorithm identifier
    31  type algorithmIdentifier struct {
    32  	Algorithm  asn1.ObjectIdentifier
    33  	Parameters asn1.RawValue `asn1:"optional"`
    34  }
    35  
    36  // issuerAndSerialNumber represents the IssuerAndSerialNumber structure
    37  type issuerAndSerialNumber struct {
    38  	IssuerName   asn1.RawValue
    39  	SerialNumber *big.Int
    40  }
    41  
    42  // signerInfo represents a SignerInfo structure
    43  type signerInfo struct {
    44  	Version                   int
    45  	Sid                       issuerAndSerialNumber
    46  	DigestAlgorithm           algorithmIdentifier
    47  	AuthenticatedAttributes   []attribute `asn1:"optional,tag:0"`
    48  	DigestEncryptionAlgorithm algorithmIdentifier
    49  	EncryptedDigest           []byte
    50  	UnauthenticatedAttributes []attribute `asn1:"optional,tag:1"`
    51  }
    52  
    53  // attribute represents an Attribute
    54  type attribute struct {
    55  	Type   asn1.ObjectIdentifier
    56  	Values []asn1.RawValue `asn1:"set"`
    57  }
    58  
    59  // signedData represents the SignedData structure
    60  type signedData struct {
    61  	Version          int
    62  	DigestAlgorithms []algorithmIdentifier `asn1:"set"`
    63  	ContentInfo      contentInfo
    64  	Certificates     []asn1.RawValue `asn1:"optional,tag:0"`
    65  	Crls             []asn1.RawValue `asn1:"optional,tag:1"`
    66  	SignerInfos      []signerInfo    `asn1:"set"`
    67  }
    68  
    69  // contentInfo represents the ContentInfo structure
    70  type contentInfo struct {
    71  	ContentType asn1.ObjectIdentifier
    72  	Content     asn1.RawValue `asn1:"optional,explicit,tag:0"`
    73  }
    74  
    75  // CreateEd25519PKCS7Signature creates a PKCS#7 signature for Ed25519
    76  func CreateEd25519PKCS7Signature(data []byte, privateKey ed25519.PrivateKey, certificate *x509.Certificate, detached bool) ([]byte, error) {
    77  	if len(privateKey) != ed25519.PrivateKeySize {
    78  		return nil, fmt.Errorf("invalid Ed25519 private key size: expected %d, got %d", ed25519.PrivateKeySize, len(privateKey))
    79  	}
    80  
    81  	if certificate == nil {
    82  		return nil, fmt.Errorf("certificate is required for PKCS#7 signatures")
    83  	}
    84  
    85  	// Sign the data with Ed25519
    86  	signature := ed25519.Sign(privateKey, data)
    87  	if len(signature) != ed25519.SignatureSize {
    88  		return nil, fmt.Errorf("invalid Ed25519 signature size: expected %d, got %d", ed25519.SignatureSize, len(signature))
    89  	}
    90  
    91  	// Create digest algorithm identifier (Ed25519 doesn't use separate hashing, but PKCS#7 requires it)
    92  	digestAlg := algorithmIdentifier{
    93  		Algorithm: oidSHA512, // Use SHA-512 as placeholder per RFC 8419 recommendations
    94  	}
    95  
    96  	// Create signature algorithm identifier
    97  	sigAlg := algorithmIdentifier{
    98  		Algorithm: oidEd25519,
    99  	}
   100  
   101  	// Create issuer and serial number
   102  	issuerAndSerial := issuerAndSerialNumber{
   103  		IssuerName:   asn1.RawValue{FullBytes: certificate.RawIssuer},
   104  		SerialNumber: certificate.SerialNumber,
   105  	}
   106  
   107  	// Create signer info
   108  	signer := signerInfo{
   109  		Version:                   1, // PKCS#7 version 1
   110  		Sid:                       issuerAndSerial,
   111  		DigestAlgorithm:           digestAlg,
   112  		DigestEncryptionAlgorithm: sigAlg,
   113  		EncryptedDigest:           signature, // Ed25519 signature goes here
   114  	}
   115  
   116  	// Create content info
   117  	var ci contentInfo
   118  	if detached {
   119  		// For detached signatures, don't include the content
   120  		ci = contentInfo{
   121  			ContentType: oidData,
   122  		}
   123  	} else {
   124  		// For attached signatures, include the content
   125  		// Wrap data in OCTET STRING for PKCS#7 data content
   126  		contentData, err := asn1.Marshal(data)
   127  		if err != nil {
   128  			return nil, fmt.Errorf("failed to marshal content: %w", err)
   129  		}
   130  		ci = contentInfo{
   131  			ContentType: oidData,
   132  			Content:     asn1.RawValue{Tag: 0, Class: 2, IsCompound: true, Bytes: contentData},
   133  		}
   134  	}
   135  
   136  	// Include certificate in the PKCS#7 structure
   137  	certRaw := asn1.RawValue{FullBytes: certificate.Raw}
   138  
   139  	// Create signed data
   140  	sd := signedData{
   141  		Version:          1, // PKCS#7 version 1
   142  		DigestAlgorithms: []algorithmIdentifier{digestAlg},
   143  		ContentInfo:      ci,
   144  		Certificates:     []asn1.RawValue{certRaw},
   145  		SignerInfos:      []signerInfo{signer},
   146  	}
   147  
   148  	// Marshal signed data
   149  	signedDataBytes, err := asn1.Marshal(sd)
   150  	if err != nil {
   151  		return nil, fmt.Errorf("failed to marshal signed data: %w", err)
   152  	}
   153  
   154  	// Create final content info wrapper with proper explicit tag
   155  	// The Content field needs to be properly wrapped as explicit tag 0
   156  	finalContentInfo := contentInfo{
   157  		ContentType: oidSignedData,
   158  		Content:     asn1.RawValue{Tag: 0, Class: 2, IsCompound: true, Bytes: signedDataBytes},
   159  	}
   160  
   161  	// Marshal final PKCS#7 structure
   162  	pkcs7Bytes, err := asn1.Marshal(finalContentInfo)
   163  	if err != nil {
   164  		return nil, fmt.Errorf("failed to marshal PKCS#7 structure: %w", err)
   165  	}
   166  
   167  	return pkcs7Bytes, nil
   168  }
   169  
   170  // VerifyEd25519PKCS7Signature verifies an Ed25519 PKCS#7 signature
   171  func VerifyEd25519PKCS7Signature(data []byte, pkcs7Data []byte) (*Ed25519PKCS7Info, error) {
   172  	// Parse the PKCS#7 structure
   173  	var ci contentInfo
   174  	rest, err := asn1.Unmarshal(pkcs7Data, &ci)
   175  	if err != nil {
   176  		return nil, fmt.Errorf("failed to parse PKCS#7 content info: %w", err)
   177  	}
   178  	if len(rest) != 0 {
   179  		return nil, fmt.Errorf("trailing data after PKCS#7 content info")
   180  	}
   181  
   182  	// Verify this is signed data
   183  	if !ci.ContentType.Equal(oidSignedData) {
   184  		return nil, fmt.Errorf("not a signed data PKCS#7 structure")
   185  	}
   186  
   187  	// Parse signed data - the content is wrapped in explicit tag, so use Bytes
   188  	var sd signedData
   189  	_, err = asn1.Unmarshal(ci.Content.Bytes, &sd)
   190  	if err != nil {
   191  		return nil, fmt.Errorf("failed to parse signed data: %w", err)
   192  	}
   193  
   194  	// Verify we have exactly one signer
   195  	if len(sd.SignerInfos) != 1 {
   196  		return nil, fmt.Errorf("expected exactly one signer, got %d", len(sd.SignerInfos))
   197  	}
   198  
   199  	signer := sd.SignerInfos[0]
   200  
   201  	// Verify this is Ed25519
   202  	if !signer.DigestEncryptionAlgorithm.Algorithm.Equal(oidEd25519) {
   203  		return nil, fmt.Errorf("not an Ed25519 signature")
   204  	}
   205  
   206  	// Verify signature size
   207  	if len(signer.EncryptedDigest) != ed25519.SignatureSize {
   208  		return nil, fmt.Errorf("invalid Ed25519 signature size: expected %d, got %d",
   209  			ed25519.SignatureSize, len(signer.EncryptedDigest))
   210  	}
   211  
   212  	// Extract certificate
   213  	if len(sd.Certificates) != 1 {
   214  		return nil, fmt.Errorf("expected exactly one certificate, got %d", len(sd.Certificates))
   215  	}
   216  
   217  	cert, err := x509.ParseCertificate(sd.Certificates[0].FullBytes)
   218  	if err != nil {
   219  		return nil, fmt.Errorf("failed to parse certificate: %w", err)
   220  	}
   221  
   222  	// Verify certificate has Ed25519 public key
   223  	ed25519PubKey, ok := cert.PublicKey.(ed25519.PublicKey)
   224  	if !ok {
   225  		return nil, fmt.Errorf("certificate does not contain Ed25519 public key")
   226  	}
   227  
   228  	// Verify the signature
   229  	if !ed25519.Verify(ed25519PubKey, data, signer.EncryptedDigest) {
   230  		return nil, fmt.Errorf("Ed25519 signature verification failed")
   231  	}
   232  
   233  	// Return verification info
   234  	info := &Ed25519PKCS7Info{
   235  		Certificate: cert,
   236  		Signature:   signer.EncryptedDigest,
   237  		Verified:    true,
   238  		SignedAt:    time.Now(), // PKCS#7 doesn't include timestamp by default
   239  	}
   240  
   241  	return info, nil
   242  }
   243  
   244  // Ed25519PKCS7Info contains information about a verified Ed25519 PKCS#7 signature
   245  type Ed25519PKCS7Info struct {
   246  	Certificate *x509.Certificate
   247  	Signature   []byte
   248  	Verified    bool
   249  	SignedAt    time.Time
   250  }
   251  
   252  // IsEd25519PKCS7 checks if the given PKCS#7 data contains an Ed25519 signature
   253  func IsEd25519PKCS7(pkcs7Data []byte) (bool, error) {
   254  	var ci contentInfo
   255  	_, err := asn1.Unmarshal(pkcs7Data, &ci)
   256  	if err != nil {
   257  		return false, fmt.Errorf("failed to parse PKCS#7 content info: %w", err)
   258  	}
   259  
   260  	if !ci.ContentType.Equal(oidSignedData) {
   261  		return false, nil
   262  	}
   263  
   264  	var sd signedData
   265  	_, err = asn1.Unmarshal(ci.Content.Bytes, &sd)
   266  	if err != nil {
   267  		return false, fmt.Errorf("failed to parse signed data: %w", err)
   268  	}
   269  
   270  	// Check if any signer uses Ed25519
   271  	for _, signer := range sd.SignerInfos {
   272  		if signer.DigestEncryptionAlgorithm.Algorithm.Equal(oidEd25519) {
   273  			return true, nil
   274  		}
   275  	}
   276  
   277  	return false, nil
   278  }
   279  
   280  // ValidateEd25519PKCS7Structure validates the structure of an Ed25519 PKCS#7 signature without verifying the signature
   281  func ValidateEd25519PKCS7Structure(pkcs7Data []byte) error {
   282  	isEd25519, err := IsEd25519PKCS7(pkcs7Data)
   283  	if err != nil {
   284  		return fmt.Errorf("failed to check PKCS#7 type: %w", err)
   285  	}
   286  
   287  	if !isEd25519 {
   288  		return fmt.Errorf("not an Ed25519 PKCS#7 signature")
   289  	}
   290  
   291  	// Parse and validate structure
   292  	var ci contentInfo
   293  	_, err = asn1.Unmarshal(pkcs7Data, &ci)
   294  	if err != nil {
   295  		return fmt.Errorf("failed to parse PKCS#7 content info: %w", err)
   296  	}
   297  
   298  	var sd signedData
   299  	_, err = asn1.Unmarshal(ci.Content.Bytes, &sd)
   300  	if err != nil {
   301  		return fmt.Errorf("failed to parse signed data: %w", err)
   302  	}
   303  
   304  	// Basic structure validation
   305  	if len(sd.SignerInfos) == 0 {
   306  		return fmt.Errorf("no signers found")
   307  	}
   308  
   309  	if len(sd.Certificates) == 0 {
   310  		return fmt.Errorf("no certificates found")
   311  	}
   312  
   313  	// Validate Ed25519 signer
   314  	for _, signer := range sd.SignerInfos {
   315  		if signer.DigestEncryptionAlgorithm.Algorithm.Equal(oidEd25519) {
   316  			if len(signer.EncryptedDigest) != ed25519.SignatureSize {
   317  				return fmt.Errorf("invalid Ed25519 signature size: expected %d, got %d",
   318  					ed25519.SignatureSize, len(signer.EncryptedDigest))
   319  			}
   320  		}
   321  	}
   322  
   323  	return nil
   324  }