CodeSampleX

Exemplo

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

Amostra verificada para golang github.com/smallstep/pkcs7 v0.0.0-20231024181729-3b98ecc1ca81: SignerInfoConfig. O contrato rodou em go 1.26 · linux…

sha256:4e914d1140de796668577760aa584c42ed97b59f5274054f5108bb6352bbee92

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
2
Chaves de assinatura que o compilaram
1
Ambiente declarado linux 24 · ubuntu · glibc 2.39 x64 go

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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

Caso

HOW
Objetivo
verify github.com/smallstep/pkcs7.SignerInfoConfig in pkg:golang/github.com/smallstep/pkcs7@v0.0.0-20231024181729-3b98ecc1ca81
Pacotes
Símbolos
  • github.com/smallstep/pkcs7.SignerInfoConfig
Criado
2026-08-26T12:14:17Z

Contrato

  1. AddSigner accepts SignerInfoConfig with ExtraSignedAttributes and preserves custom signed attributes in DER output
  2. UnmarshalSignedAttribute decodes custom signed attributes added via SignerInfoConfig from parsed PKCS7
  3. UnmarshalSignedAttribute returns error when requested attribute is not present in SignerInfo
  4. Verify validates SignedData signature containing ExtraSignedAttributes configured through SignerInfoConfig
  5. AddSignerChain accepts SignerInfoConfig and includes parent certificate chain alongside custom signed attributes
  6. SignWithoutAttr accepts SignerInfoConfig with ExtraUnsignedAttributes to sign payload without authenticated attributes

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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.SignerInfoConfig 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.SignerInfoConfig
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:5cba7e9b385018c821761ade9516cc62c34f00882a38f8516af00b17d8f3c905","contract":["AddSigner accepts SignerInfoConfig with ExtraSignedAttributes and preserves custom signed attributes in DER output","UnmarshalSignedAttribute decodes custom signed attributes added via SignerInfoConfig from parsed PKCS7","UnmarshalSignedAttribute returns error when requested attribute is not present in SignerInfo","Verify validates SignedData signature containing ExtraSignedAttributes configured through SignerInfoConfig","AddSignerChain accepts SignerInfoConfig and includes parent certificate chain alongside custom signed attributes","SignWithoutAttr accepts SignerInfoConfig with ExtraUnsignedAttributes to sign payload without authenticated attributes"],"goal":"verify github.com/smallstep/pkcs7.SignerInfoConfig 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.SignerInfoConfig"]},"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.SignerInfoConfig"],"verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.26.6

require github.com/smallstep/pkcs7 v0.2.3
go.sum
github.com/smallstep/pkcs7 v0.2.3 h1:bhoQ3TeZmdoXTatcwxCbk+FMcdsyr0gYrrW2Xq2qr+s=
github.com/smallstep/pkcs7 v0.2.3/go.mod h1:7STkdKhZaZe4xNEXTtY4j1NGeST1gYM4GA40kC5iqr8=
main.go
package main

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

	"github.com/smallstep/pkcs7"
)

var (
	oidCustomMetadata = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 999, 1}
	oidCustomNote     = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 999, 2}
)

func generateSigningCertificate(commonName string) (*x509.Certificate, *rsa.PrivateKey, error) {
	priv, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to generate RSA key: %w", err)
	}

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

	der, err := x509.CreateCertificate(rand.Reader, template, template, &priv.PublicKey, priv)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to create certificate: %w", err)
	}

	cert, err := x509.ParseCertificate(der)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to parse certificate: %w", err)
	}

	return cert, priv, nil
}

func main() {
	cert, privKey, err := generateSigningCertificate("signer.example.com")
	if err != nil {
		fmt.Printf("Initialization error: %v\n", err)
		return
	}

	payload := []byte("PKCS#7 payload with custom signer info configuration")

	signedData, err := pkcs7.NewSignedData(payload)
	if err != nil {
		fmt.Printf("Failed to initialize SignedData: %v\n", err)
		return
	}

	// Configure extra signed and unsigned attributes via SignerInfoConfig
	signerConfig := pkcs7.SignerInfoConfig{
		ExtraSignedAttributes: []pkcs7.Attribute{
			{
				Type:  oidCustomMetadata,
				Value: "custom-signer-signed-attribute",
			},
		},
		ExtraUnsignedAttributes: []pkcs7.Attribute{
			{
				Type:  oidCustomNote,
				Value: "custom-signer-unsigned-note",
			},
		},
	}

	if err := signedData.AddSigner(cert, privKey, signerConfig); err != nil {
		fmt.Printf("Failed to add signer with config: %v\n", err)
		return
	}

	signedDER, err := signedData.Finish()
	if err != nil {
		fmt.Printf("Failed to finish SignedData: %v\n", err)
		return
	}

	p7, err := pkcs7.Parse(signedDER)
	if err != nil {
		fmt.Printf("Failed to parse signed DER: %v\n", err)
		return
	}

	if err := p7.Verify(); err != nil {
		fmt.Printf("Signature verification failed: %v\n", err)
		return
	}

	var metadata string
	if err := p7.UnmarshalSignedAttribute(oidCustomMetadata, &metadata); err != nil {
		fmt.Printf("Failed to unmarshal signed attribute: %v\n", err)
		return
	}

	fmt.Printf("Successfully verified signature and unmarshaled attribute: %s\n", metadata)
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/smallstep/pkcs7.SignerInfoConfig 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.SignerInfoConfig"
  ]
}
test/contract.go
package main

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

	"github.com/smallstep/pkcs7"
)

var (
	oidSignedCustomAttr   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 999, 1}
	oidUnsignedCustomAttr = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 999, 2}
	oidNonExistentAttr    = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 999, 999}
)

func createCACertificate(commonName string) (*x509.Certificate, *rsa.PrivateKey, error) {
	priv, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return nil, nil, fmt.Errorf("generate CA key: %w", err)
	}

	template := &x509.Certificate{
		SerialNumber: big.NewInt(100),
		Subject: pkix.Name{
			CommonName: commonName,
		},
		NotBefore:             time.Now().Add(-1 * time.Hour),
		NotAfter:              time.Now().Add(24 * time.Hour),
		KeyUsage:              x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
		BasicConstraintsValid: true,
		IsCA:                  true,
	}

	der, err := x509.CreateCertificate(rand.Reader, template, template, &priv.PublicKey, priv)
	if err != nil {
		return nil, nil, fmt.Errorf("create CA cert: %w", err)
	}

	cert, err := x509.ParseCertificate(der)
	if err != nil {
		return nil, nil, fmt.Errorf("parse CA cert: %w", err)
	}

	return cert, priv, nil
}

func createEndEntityCertificate(commonName string, parent *x509.Certificate, parentKey *rsa.PrivateKey) (*x509.Certificate, *rsa.PrivateKey, error) {
	priv, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return nil, nil, fmt.Errorf("generate leaf key: %w", err)
	}

	template := &x509.Certificate{
		SerialNumber: big.NewInt(101),
		Subject: pkix.Name{
			CommonName: commonName,
		},
		NotBefore:             time.Now().Add(-1 * time.Hour),
		NotAfter:              time.Now().Add(24 * time.Hour),
		KeyUsage:              x509.KeyUsageDigitalSignature,
		BasicConstraintsValid: true,
		IsCA:                  false,
	}

	der, err := x509.CreateCertificate(rand.Reader, template, parent, &priv.PublicKey, parentKey)
	if err != nil {
		return nil, nil, fmt.Errorf("create leaf cert: %w", err)
	}

	cert, err := x509.ParseCertificate(der)
	if err != nil {
		return nil, nil, fmt.Errorf("parse leaf cert: %w", err)
	}

	return cert, priv, nil
}

func main() {
	caCert, caKey, err := createCACertificate("root-ca.example.com")
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: CA certificate generation failed: %v\n", err)
		os.Exit(1)
	}

	leafCert, leafKey, err := createEndEntityCertificate("signer.example.com", caCert, caKey)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: Leaf certificate generation failed: %v\n", err)
		os.Exit(1)
	}

	rawPayload := []byte("Verified PKCS#7 SignerInfoConfig contract test payload")

	// Assertion 1: AddSigner accepts SignerInfoConfig with ExtraSignedAttributes and preserves custom signed attributes in DER output
	var signedDER []byte
	{
		sd, err := pkcs7.NewSignedData(rawPayload)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: NewSignedData failed: %v\n", err)
			os.Exit(1)
		}

		config := pkcs7.SignerInfoConfig{
			ExtraSignedAttributes: []pkcs7.Attribute{
				{
					Type:  oidSignedCustomAttr,
					Value: "custom-signed-payload-attribute",
				},
			},
			ExtraUnsignedAttributes: []pkcs7.Attribute{
				{
					Type:  oidUnsignedCustomAttr,
					Value: "custom-unsigned-attribute-data",
				},
			},
		}

		if err := sd.AddSigner(leafCert, leafKey, config); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: AddSigner with SignerInfoConfig failed: %v\n", err)
			os.Exit(1)
		}

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

		if len(signedDER) == 0 {
			fmt.Fprintf(os.Stderr, "FAIL: Finish returned empty DER byte slice\n")
			os.Exit(1)
		}
	}

	// Assertion 2: UnmarshalSignedAttribute decodes custom signed attributes added via SignerInfoConfig from parsed PKCS7
	p7Signed, err := pkcs7.Parse(signedDER)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: Parse signed DER failed: %v\n", err)
		os.Exit(1)
	}

	{
		var decodedValue string
		if err := p7Signed.UnmarshalSignedAttribute(oidSignedCustomAttr, &decodedValue); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: UnmarshalSignedAttribute failed: %v\n", err)
			os.Exit(1)
		}

		if decodedValue != "custom-signed-payload-attribute" {
			fmt.Fprintf(os.Stderr, "FAIL: Unmarshaled attribute mismatch: got %q, want %q\n", decodedValue, "custom-signed-payload-attribute")
			os.Exit(1)
		}
	}

	// Assertion 3: UnmarshalSignedAttribute returns error when requested attribute is not present in SignerInfo
	{
		var missingValue string
		if err := p7Signed.UnmarshalSignedAttribute(oidNonExistentAttr, &missingValue); err == nil {
			fmt.Fprintf(os.Stderr, "FAIL: UnmarshalSignedAttribute should fail for missing attribute\n")
			os.Exit(1)
		}
	}

	// Assertion 4: Verify validates SignedData signature containing ExtraSignedAttributes configured through SignerInfoConfig
	{
		if err := p7Signed.Verify(); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: Verify signature failed on SignedData with ExtraSignedAttributes: %v\n", err)
			os.Exit(1)
		}
	}

	// Assertion 5: AddSignerChain accepts SignerInfoConfig and includes parent certificate chain alongside custom signed attributes
	{
		sdChain, err := pkcs7.NewSignedData(rawPayload)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: NewSignedData for chain failed: %v\n", err)
			os.Exit(1)
		}

		chainConfig := pkcs7.SignerInfoConfig{
			ExtraSignedAttributes: []pkcs7.Attribute{
				{
					Type:  oidSignedCustomAttr,
					Value: "custom-chain-signed-attr",
				},
			},
		}

		if err := sdChain.AddSignerChain(leafCert, leafKey, []*x509.Certificate{caCert}, chainConfig); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: AddSignerChain with SignerInfoConfig failed: %v\n", err)
			os.Exit(1)
		}

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

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

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

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

		var chainVal string
		if err := p7Chain.UnmarshalSignedAttribute(oidSignedCustomAttr, &chainVal); err != nil || chainVal != "custom-chain-signed-attr" {
			fmt.Fprintf(os.Stderr, "FAIL: UnmarshalSignedAttribute on chain mismatch: got %q, err %v\n", chainVal, err)
			os.Exit(1)
		}
	}

	// Assertion 6: SignWithoutAttr accepts SignerInfoConfig with ExtraUnsignedAttributes to sign payload without authenticated attributes
	{
		sdNoAttr, err := pkcs7.NewSignedData(rawPayload)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: NewSignedData for SignWithoutAttr failed: %v\n", err)
			os.Exit(1)
		}

		noAttrConfig := pkcs7.SignerInfoConfig{
			ExtraUnsignedAttributes: []pkcs7.Attribute{
				{
					Type:  oidUnsignedCustomAttr,
					Value: "unsigned-note-only",
				},
			},
		}

		if err := sdNoAttr.SignWithoutAttr(leafCert, leafKey, noAttrConfig); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: SignWithoutAttr with SignerInfoConfig failed: %v\n", err)
			os.Exit(1)
		}

		noAttrDER, err := sdNoAttr.Finish()
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: Finish on SignWithoutAttr failed: %v\n", err)
			os.Exit(1)
		}

		p7NoAttr, err := pkcs7.Parse(noAttrDER)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: Parse no-attr DER failed: %v\n", err)
			os.Exit(1)
		}

		if err := p7NoAttr.Verify(); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: Verify on SignWithoutAttr payload failed: %v\n", err)
			os.Exit(1)
		}

		var notFound string
		if err := p7NoAttr.UnmarshalSignedAttribute(oidSignedCustomAttr, &notFound); err == nil {
			fmt.Fprintf(os.Stderr, "FAIL: UnmarshalSignedAttribute on SignWithoutAttr should return error\n")
			os.Exit(1)
		}
	}

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

Seeder de origem

anônimo