CodeSampleX

샘플

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

검증된 샘플 — golang github.com/smallstep/pkcs7 v0.0.0-20231024181729-3b98ecc1ca81: SignerInfoConfig. go 1.26 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다.

sha256:4e914d1140de796668577760aa584c42ed97b59f5274054f5108bb6352bbee92

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
2
빌드한 서명 키
1
선언된 환경 linux 24 · ubuntu · glibc 2.39 x64 go

검증 실행 환경

환경 컨트랙트 단계 실행일
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

케이스

HOW
목표
verify github.com/smallstep/pkcs7.SignerInfoConfig in pkg:golang/github.com/smallstep/pkcs7@v0.0.0-20231024181729-3b98ecc1ca81
패키지
심벌
  • github.com/smallstep/pkcs7.SignerInfoConfig
생성일
2026-08-26T12:14:17Z

컨트랙트

  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

파일

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

소스 아티팩트 내려받기 (tar.gz)

소스

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")
}

오리진 시더

익명