CodeSampleX

Beispiel

github.com/smallstep/pkcs7 v0.0.0-20231024181729-3b98ecc1ca81: NewSignedData

Verifiziertes Beispiel für golang github.com/smallstep/pkcs7 v0.0.0-20231024181729-3b98ecc1ca81: NewSignedData. Der Vertrag lief auf go 1.26 · linux…

sha256:5e3911f41f57f836a6a1a4a6f8466eb722b52ce4d31fa5baeea322dcb100042a

Dieses Netzwerk bietet eine Sache: ein Sample, das baut. Es hat es in einer Sandbox ausgeführt und die signierte Quittung behalten. Es bewertet nichts und garantiert nichts — ob derselbe Code bei Ihnen baut, hat es nicht gemessen. Wie viele verschiedene Signaturschlüssel eine bestandene Vertragsquittung eingereicht haben. Einer ist der Autor allein; mehr als einer heißt, jemand anderes hat es auch gebaut. Ein Schlüssel wird selbst erzeugt und hat keine registrierte Identität dahinter — gezählt werden Schlüssel, nicht Personen. MIT-0

Ausführungsbelege

Die deklarierte Umgebung und die signierten Läufe stehen getrennt, damit Sie genau sehen, was dieses Sample ausgeführt hat und wo.

Beleggrundlage
Signierter Vertrag bestanden
Verifizierungsbelege
2
Signaturschlüssel, die es gebaut haben
1
Deklarierte Umgebung linux 24 · ubuntu · glibc 2.39 x64 go

Umgebungen der Verifizierungsläufe

Umgebung Contract Stufen Lauf
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-26
go 1.26 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a…
2026-09-07

Fall

HOW
Ziel
verify github.com/smallstep/pkcs7.NewSignedData in pkg:golang/github.com/smallstep/pkcs7@v0.0.0-20231024181729-3b98ecc1ca81
Pakete
Symbole
  • github.com/smallstep/pkcs7.NewSignedData
Erstellt
2026-08-26T12:04:29Z

Contract

  1. pkcs7.NewSignedData creates signed data payload verifiable with Parse and Verify
  2. SignedData.Detach produces detached signature with empty content verifiable when original data is provided
  3. SignedData.AddSignerChain includes intermediate certificates in SignedData and verifies against a root cert pool
  4. SignedData with custom signed attributes embeds attributes unmarshable by PKCS7.UnmarshalSignedAttribute
  5. PKCS7.Verify fails when payload data is tampered or corrupted

Dateien

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.go
  • spec.json
  • test/contract.go

Quellartefakt herunterladen (tar.gz)

Quelltext

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify github.com/smallstep/pkcs7.NewSignedData in pkg:golang/github.com/smallstep/pkcs7@v0.0.0-20231024181729-3b98ecc1ca81
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/smallstep/pkcs7@v0.0.0-20231024181729-3b98ecc1ca81
Demonstrate these symbols/APIs:
  - github.com/smallstep/pkcs7.NewSignedData

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:11fdbd6a0630b30b31f1650cc7b87f92430c1b75210ea4b3b9d18304e1e29a02","contract":["pkcs7.NewSignedData creates signed data payload verifiable with Parse and Verify","SignedData.Detach produces detached signature with empty content verifiable when original data is provided","SignedData.AddSignerChain includes intermediate certificates in SignedData and verifies against a root cert pool","SignedData with custom signed attributes embeds attributes unmarshable by PKCS7.UnmarshalSignedAttribute","PKCS7.Verify fails when payload data is tampered or corrupted"],"goal":"verify github.com/smallstep/pkcs7.NewSignedData in pkg:golang/github.com/smallstep/pkcs7@v0.0.0-20231024181729-3b98ecc1ca81","kind":"HOW","packages":["pkg:golang/github.com/smallstep/pkcs7@v0.0.0-20231024181729-3b98ecc1ca81"],"schemaVersion":1,"symbols":["github.com/smallstep/pkcs7.NewSignedData"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/smallstep/pkcs7@v0.0.0-20231024181729-3b98ecc1ca81"],"schemaVersion":1,"subject":"pkg:golang/github.com/smallstep/pkcs7@v0.0.0-20231024181729-3b98ecc1ca81","symbols":["github.com/smallstep/pkcs7.NewSignedData"],"verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.26.6

require github.com/smallstep/pkcs7 v0.0.0-20231024181729-3b98ecc1ca81
go.sum
github.com/smallstep/pkcs7 v0.0.0-20231024181729-3b98ecc1ca81 h1:B6cED3iLJTgxpdh4tuqByDjRRKan2EvtnOfHr2zHJVg=
github.com/smallstep/pkcs7 v0.0.0-20231024181729-3b98ecc1ca81/go.mod h1:SoUAr/4M46rZ3WaLstHxGhLEgoYIDRqxQEXLOmOEB0Y=
main.go
package main

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"crypto/x509/pkix"
	"fmt"
	"math/big"
	"os"
	"time"

	"github.com/smallstep/pkcs7"
)

func generateTestCert() (*x509.Certificate, *rsa.PrivateKey, error) {
	priv, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return nil, nil, err
	}

	tmpl := &x509.Certificate{
		SerialNumber: big.NewInt(1),
		Subject: pkix.Name{
			CommonName: "example.com",
		},
		NotBefore:             time.Now().Add(-1 * time.Hour),
		NotAfter:              time.Now().Add(24 * time.Hour),
		KeyUsage:              x509.KeyUsageDigitalSignature,
		BasicConstraintsValid: true,
	}

	certDER, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &priv.PublicKey, priv)
	if err != nil {
		return nil, nil, err
	}

	cert, err := x509.ParseCertificate(certDER)
	if err != nil {
		return nil, nil, err
	}

	return cert, priv, nil
}

// SignPayload signs data using pkcs7.NewSignedData and returns the DER encoded PKCS#7 structure.
func SignPayload(data []byte, cert *x509.Certificate, priv *rsa.PrivateKey) ([]byte, error) {
	sd, err := pkcs7.NewSignedData(data)
	if err != nil {
		return nil, fmt.Errorf("failed to create signed data: %w", err)
	}

	if err := sd.AddSigner(cert, priv, pkcs7.SignerInfoConfig{}); err != nil {
		return nil, fmt.Errorf("failed to add signer: %w", err)
	}

	return sd.Finish()
}

// VerifySignature parses and verifies the PKCS#7 signed structure, returning the content.
func VerifySignature(p7DER []byte) ([]byte, error) {
	p7, err := pkcs7.Parse(p7DER)
	if err != nil {
		return nil, fmt.Errorf("failed to parse pkcs7: %w", err)
	}

	if err := p7.Verify(); err != nil {
		return nil, fmt.Errorf("failed to verify pkcs7: %w", err)
	}

	return p7.Content, nil
}

func main() {
	cert, priv, err := generateTestCert()
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error generating certificate: %v\n", err)
		os.Exit(1)
	}

	message := []byte("Hello, CodeSampleX PKCS#7 signed message!")
	signedDER, err := SignPayload(message, cert, priv)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error signing payload: %v\n", err)
		os.Exit(1)
	}

	fmt.Printf("Generated PKCS#7 signed data: %d bytes\n", len(signedDER))

	recovered, err := VerifySignature(signedDER)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error verifying signature: %v\n", err)
		os.Exit(1)
	}

	fmt.Printf("Successfully verified payload: %s\n", string(recovered))
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/smallstep/pkcs7.NewSignedData in pkg:golang/github.com/smallstep/pkcs7@v0.0.0-20231024181729-3b98ecc1ca81",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/smallstep/pkcs7@v0.0.0-20231024181729-3b98ecc1ca81"
  ],
  "symbols": [
    "github.com/smallstep/pkcs7.NewSignedData"
  ]
}
test/contract.go
package main

import (
	"bytes"
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/asn1"
	"fmt"
	"math/big"
	"os"
	"time"

	"github.com/smallstep/pkcs7"
)

func createTestKeyPair(cn string) (*x509.Certificate, *rsa.PrivateKey, error) {
	priv, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return nil, nil, err
	}

	tmpl := &x509.Certificate{
		SerialNumber: big.NewInt(time.Now().UnixNano()),
		Subject: pkix.Name{
			CommonName: cn,
		},
		NotBefore:             time.Now().Add(-1 * time.Hour),
		NotAfter:              time.Now().Add(24 * time.Hour),
		KeyUsage:              x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
		BasicConstraintsValid: true,
	}

	certDER, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &priv.PublicKey, priv)
	if err != nil {
		return nil, nil, err
	}

	cert, err := x509.ParseCertificate(certDER)
	if err != nil {
		return nil, nil, err
	}

	return cert, priv, nil
}

func main() {
	// Assertion 1: pkcs7.NewSignedData creates signed data payload verifiable with Parse and Verify
	cert, priv, err := createTestKeyPair("signer1.example.com")
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: Assertion 1 keygen error: %v\n", err)
		os.Exit(1)
	}

	payload := []byte("PKCS#7 standard payload content")
	sd, err := pkcs7.NewSignedData(payload)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: pkcs7.NewSignedData error: %v\n", err)
		os.Exit(1)
	}

	if err := sd.AddSigner(cert, priv, pkcs7.SignerInfoConfig{}); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: sd.AddSigner error: %v\n", err)
		os.Exit(1)
	}

	der, err := sd.Finish()
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: sd.Finish error: %v\n", err)
		os.Exit(1)
	}

	p7, err := pkcs7.Parse(der)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: pkcs7.Parse error: %v\n", err)
		os.Exit(1)
	}

	if !bytes.Equal(p7.Content, payload) {
		fmt.Fprintf(os.Stderr, "FAIL: parsed content does not match original\n")
		os.Exit(1)
	}

	if err := p7.Verify(); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: p7.Verify error: %v\n", err)
		os.Exit(1)
	}

	signerCert := p7.GetOnlySigner()
	if signerCert == nil || signerCert.Subject.CommonName != cert.Subject.CommonName {
		fmt.Fprintf(os.Stderr, "FAIL: p7.GetOnlySigner did not return expected signer certificate\n")
		os.Exit(1)
	}

	// Assertion 2: SignedData.Detach produces detached signature with empty content verifiable when original data is provided
	detachedPayload := []byte("Detached signature payload data")
	sdDetached, err := pkcs7.NewSignedData(detachedPayload)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: Assertion 2 NewSignedData error: %v\n", err)
		os.Exit(1)
	}

	if err := sdDetached.AddSigner(cert, priv, pkcs7.SignerInfoConfig{}); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: sdDetached.AddSigner error: %v\n", err)
		os.Exit(1)
	}

	sdDetached.Detach()

	detachedDER, err := sdDetached.Finish()
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: sdDetached.Finish error: %v\n", err)
		os.Exit(1)
	}

	p7Detached, err := pkcs7.Parse(detachedDER)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: pkcs7.Parse detached error: %v\n", err)
		os.Exit(1)
	}

	if len(p7Detached.Content) != 0 {
		fmt.Fprintf(os.Stderr, "FAIL: expected empty content for detached signature, got %d bytes\n", len(p7Detached.Content))
		os.Exit(1)
	}

	p7Detached.Content = detachedPayload
	if err := p7Detached.Verify(); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: p7Detached.Verify error: %v\n", err)
		os.Exit(1)
	}

	// Assertion 3: SignedData.AddSignerChain includes intermediate certificates in SignedData and verifies against a root cert pool
	rootPriv, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: rootPriv keygen error: %v\n", err)
		os.Exit(1)
	}
	rootTmpl := &x509.Certificate{
		SerialNumber:          big.NewInt(100),
		Subject:               pkix.Name{CommonName: "Root CA"},
		NotBefore:             time.Now().Add(-1 * time.Hour),
		NotAfter:              time.Now().Add(24 * time.Hour),
		IsCA:                  true,
		KeyUsage:              x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
		BasicConstraintsValid: true,
	}
	rootDER, err := x509.CreateCertificate(rand.Reader, rootTmpl, rootTmpl, &rootPriv.PublicKey, rootPriv)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: root cert creation error: %v\n", err)
		os.Exit(1)
	}
	rootCert, err := x509.ParseCertificate(rootDER)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: root cert parse error: %v\n", err)
		os.Exit(1)
	}

	interPriv, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: interPriv keygen error: %v\n", err)
		os.Exit(1)
	}
	interTmpl := &x509.Certificate{
		SerialNumber:          big.NewInt(101),
		Subject:               pkix.Name{CommonName: "Intermediate CA"},
		NotBefore:             time.Now().Add(-1 * time.Hour),
		NotAfter:              time.Now().Add(24 * time.Hour),
		IsCA:                  true,
		KeyUsage:              x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
		BasicConstraintsValid: true,
	}
	interDER, err := x509.CreateCertificate(rand.Reader, interTmpl, rootCert, &interPriv.PublicKey, rootPriv)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: inter cert creation error: %v\n", err)
		os.Exit(1)
	}
	interCert, err := x509.ParseCertificate(interDER)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: inter cert parse error: %v\n", err)
		os.Exit(1)
	}

	leafPriv, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: leafPriv keygen error: %v\n", err)
		os.Exit(1)
	}
	leafTmpl := &x509.Certificate{
		SerialNumber:          big.NewInt(102),
		Subject:               pkix.Name{CommonName: "Leaf Signer"},
		NotBefore:             time.Now().Add(-1 * time.Hour),
		NotAfter:              time.Now().Add(24 * time.Hour),
		KeyUsage:              x509.KeyUsageDigitalSignature,
		BasicConstraintsValid: true,
	}
	leafDER, err := x509.CreateCertificate(rand.Reader, leafTmpl, interCert, &leafPriv.PublicKey, interPriv)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: leaf cert creation error: %v\n", err)
		os.Exit(1)
	}
	leafCert, err := x509.ParseCertificate(leafDER)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: leaf cert parse error: %v\n", err)
		os.Exit(1)
	}

	sdChain, err := pkcs7.NewSignedData([]byte("Chained certificate verification"))
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: sdChain NewSignedData error: %v\n", err)
		os.Exit(1)
	}

	if err := sdChain.AddSignerChain(leafCert, leafPriv, []*x509.Certificate{interCert}, pkcs7.SignerInfoConfig{}); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: sdChain AddSignerChain error: %v\n", err)
		os.Exit(1)
	}

	chainDER, err := sdChain.Finish()
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: sdChain Finish error: %v\n", err)
		os.Exit(1)
	}

	p7Chain, err := pkcs7.Parse(chainDER)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: pkcs7.Parse chain error: %v\n", err)
		os.Exit(1)
	}

	trustPool := x509.NewCertPool()
	trustPool.AddCert(rootCert)

	if err := p7Chain.VerifyWithChain(trustPool); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: p7Chain.VerifyWithChain error: %v\n", err)
		os.Exit(1)
	}

	// Assertion 4: SignedData with custom signed attributes embeds attributes unmarshable by PKCS7.UnmarshalSignedAttribute
	customOID := asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 50}
	customVal := "CustomSignatureAttributeValue"
	rawVal, err := asn1.Marshal(customVal)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: asn1.Marshal customVal error: %v\n", err)
		os.Exit(1)
	}

	sdAttr, err := pkcs7.NewSignedData([]byte("Payload with custom signed attributes"))
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: sdAttr NewSignedData error: %v\n", err)
		os.Exit(1)
	}

	signerConfig := pkcs7.SignerInfoConfig{
		ExtraSignedAttributes: []pkcs7.Attribute{
			{
				Type:  customOID,
				Value: asn1.RawValue{FullBytes: rawVal},
			},
		},
	}

	if err := sdAttr.AddSigner(cert, priv, signerConfig); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: sdAttr AddSigner error: %v\n", err)
		os.Exit(1)
	}

	attrDER, err := sdAttr.Finish()
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: sdAttr Finish error: %v\n", err)
		os.Exit(1)
	}

	p7Attr, err := pkcs7.Parse(attrDER)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: p7Attr Parse error: %v\n", err)
		os.Exit(1)
	}

	if err := p7Attr.Verify(); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: p7Attr Verify error: %v\n", err)
		os.Exit(1)
	}

	var extractedVal string
	if err := p7Attr.UnmarshalSignedAttribute(customOID, &extractedVal); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: p7Attr UnmarshalSignedAttribute error: %v\n", err)
		os.Exit(1)
	}

	if extractedVal != customVal {
		fmt.Fprintf(os.Stderr, "FAIL: extracted signed attribute %q != %q\n", extractedVal, customVal)
		os.Exit(1)
	}

	// Assertion 5: PKCS7.Verify fails when payload data is tampered or corrupted
	p7Tampered, err := pkcs7.Parse(der)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: p7Tampered Parse error: %v\n", err)
		os.Exit(1)
	}

	p7Tampered.Content = []byte("Tampered payload content")
	if err := p7Tampered.Verify(); err == nil {
		fmt.Fprintf(os.Stderr, "FAIL: expected p7Tampered.Verify to fail on tampered content, but it succeeded\n")
		os.Exit(1)
	}

	fmt.Println("PASS: all github.com/smallstep/pkcs7.NewSignedData contract assertions passed")
}

Ursprungs-Seeder

anonym