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

     1  package crypto
     2  
     3  import (
     4  	"crypto/ed25519"
     5  	"crypto/x509"
     6  	"encoding/asn1"
     7  	"encoding/hex"
     8  	"fmt"
     9  )
    10  
    11  // DebugCreateEd25519PKCS7Signature creates a debuggable Ed25519 PKCS#7 signature
    12  func DebugCreateEd25519PKCS7Signature(data []byte, privateKey ed25519.PrivateKey, certificate *x509.Certificate, detached bool) ([]byte, error) {
    13  	fmt.Printf("🐛 DEBUG: Starting Ed25519 PKCS#7 creation\n")
    14  	fmt.Printf("   Data length: %d bytes\n", len(data))
    15  	fmt.Printf("   Private key length: %d bytes\n", len(privateKey))
    16  	fmt.Printf("   Detached: %v\n", detached)
    17  
    18  	if len(privateKey) != ed25519.PrivateKeySize {
    19  		return nil, fmt.Errorf("invalid Ed25519 private key size: expected %d, got %d", ed25519.PrivateKeySize, len(privateKey))
    20  	}
    21  
    22  	if certificate == nil {
    23  		return nil, fmt.Errorf("certificate is required for PKCS#7 signatures")
    24  	}
    25  
    26  	// Sign the data with Ed25519
    27  	fmt.Printf("🐛 DEBUG: Creating Ed25519 signature\n")
    28  	signature := ed25519.Sign(privateKey, data)
    29  	fmt.Printf("   Signature length: %d bytes\n", len(signature))
    30  	fmt.Printf("   Signature hex: %s\n", hex.EncodeToString(signature[:32])+"...")
    31  
    32  	// RFC 8419: For Ed25519, no separate hashing is needed
    33  	// The digest algorithm in SignerInfo should be absent or set to a placeholder
    34  	fmt.Printf("🐛 DEBUG: Creating algorithm identifiers\n")
    35  
    36  	// According to RFC 8419, for Ed25519, the digestAlgorithm can be omitted
    37  	// or set to id-sha512 as a placeholder
    38  	digestAlg := algorithmIdentifier{
    39  		Algorithm: oidSHA512, // RFC 8419 recommends this as placeholder
    40  	}
    41  
    42  	// Ed25519 signature algorithm
    43  	sigAlg := algorithmIdentifier{
    44  		Algorithm: oidEd25519,
    45  		// Ed25519 has no parameters - they should be absent
    46  	}
    47  
    48  	fmt.Printf("   DigestAlg OID: %v\n", digestAlg.Algorithm)
    49  	fmt.Printf("   SignatureAlg OID: %v\n", sigAlg.Algorithm)
    50  
    51  	// Create issuer and serial number
    52  	fmt.Printf("🐛 DEBUG: Creating issuer and serial number\n")
    53  	fmt.Printf("   Certificate subject: %s\n", certificate.Subject)
    54  	fmt.Printf("   Certificate serial: %v\n", certificate.SerialNumber)
    55  	fmt.Printf("   RawIssuer length: %d bytes\n", len(certificate.RawIssuer))
    56  
    57  	issuerAndSerial := issuerAndSerialNumber{
    58  		IssuerName:   asn1.RawValue{FullBytes: certificate.RawIssuer},
    59  		SerialNumber: certificate.SerialNumber,
    60  	}
    61  
    62  	// Test marshal issuerAndSerial
    63  	issuerBytes, err := asn1.Marshal(issuerAndSerial)
    64  	if err != nil {
    65  		return nil, fmt.Errorf("failed to marshal issuerAndSerialNumber: %w", err)
    66  	}
    67  	fmt.Printf("   IssuerAndSerial marshaled: %d bytes\n", len(issuerBytes))
    68  
    69  	// Create signer info
    70  	fmt.Printf("🐛 DEBUG: Creating signer info\n")
    71  	signer := signerInfo{
    72  		Version:                   1, // PKCS#7 version 1
    73  		Sid:                       issuerAndSerial,
    74  		DigestAlgorithm:           digestAlg,
    75  		DigestEncryptionAlgorithm: sigAlg,
    76  		EncryptedDigest:           signature,
    77  		// No authenticated attributes for Ed25519
    78  	}
    79  
    80  	// Test marshal signerInfo
    81  	signerBytes, err := asn1.Marshal(signer)
    82  	if err != nil {
    83  		return nil, fmt.Errorf("failed to marshal signerInfo: %w", err)
    84  	}
    85  	fmt.Printf("   SignerInfo marshaled: %d bytes\n", len(signerBytes))
    86  
    87  	// Create content info
    88  	fmt.Printf("🐛 DEBUG: Creating content info\n")
    89  	var ci contentInfo
    90  	if detached {
    91  		// For detached signatures, content is omitted
    92  		ci = contentInfo{
    93  			ContentType: oidData,
    94  			// Content field is omitted for detached
    95  		}
    96  	} else {
    97  		// For attached signatures, include the content as OCTET STRING
    98  		contentData, err := asn1.Marshal(data)
    99  		if err != nil {
   100  			return nil, fmt.Errorf("failed to marshal content data: %w", err)
   101  		}
   102  		fmt.Printf("   Content data marshaled: %d bytes\n", len(contentData))
   103  
   104  		ci = contentInfo{
   105  			ContentType: oidData,
   106  			Content:     asn1.RawValue{Tag: 0, Class: 2, IsCompound: true, Bytes: contentData},
   107  		}
   108  	}
   109  
   110  	// Test marshal contentInfo
   111  	ciBytes, err := asn1.Marshal(ci)
   112  	if err != nil {
   113  		return nil, fmt.Errorf("failed to marshal contentInfo: %w", err)
   114  	}
   115  	fmt.Printf("   ContentInfo marshaled: %d bytes\n", len(ciBytes))
   116  
   117  	// Include certificate in the PKCS#7 structure
   118  	fmt.Printf("🐛 DEBUG: Including certificate\n")
   119  	fmt.Printf("   Certificate length: %d bytes\n", len(certificate.Raw))
   120  	certRaw := asn1.RawValue{FullBytes: certificate.Raw}
   121  
   122  	// Create signed data
   123  	fmt.Printf("🐛 DEBUG: Creating signed data structure\n")
   124  	sd := signedData{
   125  		Version:          1, // PKCS#7 version 1
   126  		DigestAlgorithms: []algorithmIdentifier{digestAlg},
   127  		ContentInfo:      ci,
   128  		Certificates:     []asn1.RawValue{certRaw},
   129  		SignerInfos:      []signerInfo{signer},
   130  		// CRLs are omitted
   131  	}
   132  
   133  	// Test marshal signedData - this is where the error likely occurs
   134  	fmt.Printf("🐛 DEBUG: Marshaling signed data structure\n")
   135  	signedDataBytes, err := asn1.Marshal(sd)
   136  	if err != nil {
   137  		return nil, fmt.Errorf("failed to marshal signed data: %w", err)
   138  	}
   139  	fmt.Printf("   SignedData marshaled: %d bytes\n", len(signedDataBytes))
   140  	fmt.Printf("   SignedData hex (first 64 bytes): %s\n", hex.EncodeToString(signedDataBytes[:min(64, len(signedDataBytes))]))
   141  
   142  	// Create final content info wrapper
   143  	fmt.Printf("🐛 DEBUG: Creating final PKCS#7 wrapper\n")
   144  	finalContentInfo := contentInfo{
   145  		ContentType: oidSignedData,
   146  		Content:     asn1.RawValue{Tag: 0, Class: 2, IsCompound: true, Bytes: signedDataBytes},
   147  	}
   148  
   149  	// Marshal final PKCS#7 structure
   150  	fmt.Printf("🐛 DEBUG: Marshaling final PKCS#7 structure\n")
   151  	pkcs7Bytes, err := asn1.Marshal(finalContentInfo)
   152  	if err != nil {
   153  		return nil, fmt.Errorf("failed to marshal final PKCS#7 structure: %w", err)
   154  	}
   155  
   156  	fmt.Printf("🐛 DEBUG: PKCS#7 creation successful!\n")
   157  	fmt.Printf("   Final PKCS#7 length: %d bytes\n", len(pkcs7Bytes))
   158  	fmt.Printf("   Final PKCS#7 hex (first 64 bytes): %s\n", hex.EncodeToString(pkcs7Bytes[:min(64, len(pkcs7Bytes))]))
   159  
   160  	return pkcs7Bytes, nil
   161  }
   162  
   163  // DebugVerifyEd25519PKCS7Signature verifies with detailed debugging
   164  func DebugVerifyEd25519PKCS7Signature(data []byte, pkcs7Data []byte) (*Ed25519PKCS7Info, error) {
   165  	fmt.Printf("🐛 DEBUG: Starting Ed25519 PKCS#7 verification\n")
   166  	fmt.Printf("   Data length: %d bytes\n", len(data))
   167  	fmt.Printf("   PKCS#7 length: %d bytes\n", len(pkcs7Data))
   168  	fmt.Printf("   PKCS#7 hex (first 64 bytes): %s\n", hex.EncodeToString(pkcs7Data[:min(64, len(pkcs7Data))]))
   169  
   170  	// Parse the PKCS#7 structure
   171  	fmt.Printf("🐛 DEBUG: Parsing outer contentInfo\n")
   172  	var ci contentInfo
   173  	rest, err := asn1.Unmarshal(pkcs7Data, &ci)
   174  	if err != nil {
   175  		fmt.Printf("   ERROR: Failed to parse outer contentInfo: %v\n", err)
   176  		return nil, fmt.Errorf("failed to parse PKCS#7 content info: %w", err)
   177  	}
   178  	if len(rest) != 0 {
   179  		fmt.Printf("   WARNING: %d bytes of trailing data\n", len(rest))
   180  		return nil, fmt.Errorf("trailing data after PKCS#7 content info")
   181  	}
   182  	fmt.Printf("   ContentType: %v\n", ci.ContentType)
   183  	fmt.Printf("   Content length: %d bytes\n", len(ci.Content.FullBytes))
   184  
   185  	// Verify this is signed data
   186  	if !ci.ContentType.Equal(oidSignedData) {
   187  		return nil, fmt.Errorf("not a signed data PKCS#7 structure, got OID: %v", ci.ContentType)
   188  	}
   189  
   190  	// Parse signed data - the content is wrapped in explicit tag, so use Bytes
   191  	fmt.Printf("🐛 DEBUG: Parsing signedData structure\n")
   192  	var sd signedData
   193  	rest, err = asn1.Unmarshal(ci.Content.Bytes, &sd)
   194  	if err != nil {
   195  		fmt.Printf("   ERROR: Failed to parse signedData: %v\n", err)
   196  		fmt.Printf("   SignedData hex (first 128 bytes): %s\n", hex.EncodeToString(ci.Content.Bytes[:min(128, len(ci.Content.Bytes))]))
   197  		return nil, fmt.Errorf("failed to parse signed data: %w", err)
   198  	}
   199  	fmt.Printf("   SignedData version: %d\n", sd.Version)
   200  	fmt.Printf("   DigestAlgorithms count: %d\n", len(sd.DigestAlgorithms))
   201  	fmt.Printf("   Certificates count: %d\n", len(sd.Certificates))
   202  	fmt.Printf("   SignerInfos count: %d\n", len(sd.SignerInfos))
   203  
   204  	// Verify we have exactly one signer
   205  	if len(sd.SignerInfos) != 1 {
   206  		return nil, fmt.Errorf("expected exactly one signer, got %d", len(sd.SignerInfos))
   207  	}
   208  
   209  	signer := sd.SignerInfos[0]
   210  	fmt.Printf("🐛 DEBUG: Analyzing signer info\n")
   211  	fmt.Printf("   Signer version: %d\n", signer.Version)
   212  	fmt.Printf("   DigestAlgorithm: %v\n", signer.DigestAlgorithm.Algorithm)
   213  	fmt.Printf("   SignatureAlgorithm: %v\n", signer.DigestEncryptionAlgorithm.Algorithm)
   214  	fmt.Printf("   Signature length: %d bytes\n", len(signer.EncryptedDigest))
   215  
   216  	// Verify this is Ed25519
   217  	if !signer.DigestEncryptionAlgorithm.Algorithm.Equal(oidEd25519) {
   218  		return nil, fmt.Errorf("not an Ed25519 signature, got OID: %v", signer.DigestEncryptionAlgorithm.Algorithm)
   219  	}
   220  
   221  	// Verify signature size
   222  	if len(signer.EncryptedDigest) != ed25519.SignatureSize {
   223  		return nil, fmt.Errorf("invalid Ed25519 signature size: expected %d, got %d",
   224  			ed25519.SignatureSize, len(signer.EncryptedDigest))
   225  	}
   226  
   227  	// Extract certificate
   228  	if len(sd.Certificates) != 1 {
   229  		return nil, fmt.Errorf("expected exactly one certificate, got %d", len(sd.Certificates))
   230  	}
   231  
   232  	fmt.Printf("🐛 DEBUG: Parsing certificate\n")
   233  	cert, err := x509.ParseCertificate(sd.Certificates[0].FullBytes)
   234  	if err != nil {
   235  		return nil, fmt.Errorf("failed to parse certificate: %w", err)
   236  	}
   237  	fmt.Printf("   Certificate subject: %s\n", cert.Subject)
   238  
   239  	// Verify certificate has Ed25519 public key
   240  	ed25519PubKey, ok := cert.PublicKey.(ed25519.PublicKey)
   241  	if !ok {
   242  		return nil, fmt.Errorf("certificate does not contain Ed25519 public key")
   243  	}
   244  	fmt.Printf("   Ed25519 public key length: %d bytes\n", len(ed25519PubKey))
   245  
   246  	// Verify the signature
   247  	fmt.Printf("🐛 DEBUG: Verifying Ed25519 signature\n")
   248  	if !ed25519.Verify(ed25519PubKey, data, signer.EncryptedDigest) {
   249  		return nil, fmt.Errorf("Ed25519 signature verification failed")
   250  	}
   251  
   252  	fmt.Printf("🐛 DEBUG: Verification successful!\n")
   253  	return &Ed25519PKCS7Info{
   254  		Certificate: cert,
   255  		Signature:   signer.EncryptedDigest,
   256  		Verified:    true,
   257  	}, nil
   258  }
   259  
   260  func min(a, b int) int {
   261  	if a < b {
   262  		return a
   263  	}
   264  	return b
   265  }