CodeSampleX

Пример

golang.org/x/crypto v0.11.1-0.20230711161743-2e82bdd1719d: chacha20poly1305.New, chacha20poly1305.NewX

Проверенный пример — golang golang.org/x/crypto v0.11.1-0.20230711161743-2e82bdd1719d: chacha20poly1305.New, chacha20poly1305.NewX. Контракт выполнен на go…

sha256:ce7c98a1bfa0b47b97607ce11c32ea711dbe1f32e15b5f95738bc6ce6bc001f0

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда go 1.26 linux 24 · ubuntu · glibc 2.39 x64 go 1.26 go go 1

Среды запусков проверки

Окружение Контракт Этапы Запуск
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-28

Кейс

HOW
Цель
verify pkg:golang/golang.org/x/crypto@v0.11.1-0.20230711161743-2e82bdd1719d
Пакеты
Символы
  • chacha20poly1305.New
  • chacha20poly1305.NewX
Окружение
go 1.26.6
Создан
2026-08-28T09:16:22Z

Контракт

  1. chacha20poly1305.New creates an AEAD cipher with standard 12-byte NonceSize and 16-byte Overhead
  2. chacha20poly1305.New rejects invalid key lengths not matching 32 bytes
  3. chacha20poly1305.NewX creates an AEAD cipher with extended 24-byte NonceSize and 16-byte Overhead
  4. chacha20poly1305.NewX rejects invalid key lengths not matching 32 bytes
  5. aead.Seal and aead.Open correctly encrypt and decrypt plaintext with additional authenticated data
  6. aead.Open rejects tampered ciphertext or corrupted authentication tag
  7. aead.Open rejects mismatched additional authenticated data
  8. aeadX.Seal and aeadX.Open round-trip plaintext with 24-byte extended nonce

Файлы

  • 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 pkg:golang/golang.org/x/crypto@v0.11.1-0.20230711161743-2e82bdd1719d
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/golang.org/x/crypto@v0.11.1-0.20230711161743-2e82bdd1719d
Demonstrate these symbols/APIs:
  - chacha20poly1305.New
  - chacha20poly1305.NewX

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:831fba910d327f2540d55be53c7263217dacb7df50f8b6c7df833a0ed99a2b4d","contract":["chacha20poly1305.New creates an AEAD cipher with standard 12-byte NonceSize and 16-byte Overhead","chacha20poly1305.New rejects invalid key lengths not matching 32 bytes","chacha20poly1305.NewX creates an AEAD cipher with extended 24-byte NonceSize and 16-byte Overhead","chacha20poly1305.NewX rejects invalid key lengths not matching 32 bytes","aead.Seal and aead.Open correctly encrypt and decrypt plaintext with additional authenticated data","aead.Open rejects tampered ciphertext or corrupted authentication tag","aead.Open rejects mismatched additional authenticated data","aeadX.Seal and aeadX.Open round-trip plaintext with 24-byte extended nonce"],"goal":"verify pkg:golang/golang.org/x/crypto@v0.11.1-0.20230711161743-2e82bdd1719d","kind":"HOW","packages":["pkg:golang/golang.org/x/crypto@v0.11.1-0.20230711161743-2e82bdd1719d"],"schemaVersion":1,"symbols":["chacha20poly1305.New","chacha20poly1305.NewX"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","packageManagerVersion":"1.26.6","runtime":"go","runtimeVersion":"1.26.6","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/golang.org/x/crypto@v0.11.1-0.20230711161743-2e82bdd1719d"],"schemaVersion":1,"subject":"pkg:golang/golang.org/x/crypto@v0.11.1-0.20230711161743-2e82bdd1719d","symbols":["chacha20poly1305.New","chacha20poly1305.NewX"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require golang.org/x/crypto v0.11.1-0.20230711161743-2e82bdd1719d

require golang.org/x/sys v0.10.0 // indirect
go.sum
golang.org/x/crypto v0.11.1-0.20230711161743-2e82bdd1719d h1:LiA25/KWKuXfIq5pMIBq1s5hz3HQxhJJSu/SUGlD+SM=
golang.org/x/crypto v0.11.1-0.20230711161743-2e82bdd1719d/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio=
golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA=
golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
main.go
package main

import (
	"crypto/rand"
	"encoding/hex"
	"fmt"
	"io"
	"log"

	"golang.org/x/crypto/chacha20poly1305"
)

func main() {
	// 32-byte key for ChaCha20-Poly1305
	key := make([]byte, chacha20poly1305.KeySize)
	if _, err := io.ReadFull(rand.Reader, key); err != nil {
		log.Fatalf("failed to generate random key: %v", err)
	}

	// Create a new ChaCha20-Poly1305 AEAD cipher
	aead, err := chacha20poly1305.New(key)
	if err != nil {
		log.Fatalf("failed to create cipher: %v", err)
	}

	plaintext := []byte("Hello, authenticated encryption with ChaCha20-Poly1305!")
	additionalData := []byte("metadata-id-42")

	// Standard nonce (12 bytes)
	nonce := make([]byte, aead.NonceSize())
	if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
		log.Fatalf("failed to generate nonce: %v", err)
	}

	// Encrypt and authenticate (Seal)
	ciphertext := aead.Seal(nil, nonce, plaintext, additionalData)
	fmt.Printf("Ciphertext (hex): %s\n", hex.EncodeToString(ciphertext))

	// Decrypt and verify (Open)
	decrypted, err := aead.Open(nil, nonce, ciphertext, additionalData)
	if err != nil {
		log.Fatalf("failed to decrypt: %v", err)
	}
	fmt.Printf("Decrypted plaintext: %s\n", string(decrypted))

	// Create XChaCha20-Poly1305 AEAD cipher with extended 24-byte nonce
	aeadX, err := chacha20poly1305.NewX(key)
	if err != nil {
		log.Fatalf("failed to create XChaCha20 cipher: %v", err)
	}

	nonceX := make([]byte, aeadX.NonceSize())
	if _, err := io.ReadFull(rand.Reader, nonceX); err != nil {
		log.Fatalf("failed to generate extended nonce: %v", err)
	}

	ciphertextX := aeadX.Seal(nil, nonceX, plaintext, additionalData)
	decryptedX, err := aeadX.Open(nil, nonceX, ciphertextX, additionalData)
	if err != nil {
		log.Fatalf("failed to decrypt with XChaCha20: %v", err)
	}
	fmt.Printf("Decrypted with XChaCha20: %s\n", string(decryptedX))
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/golang.org/x/crypto@v0.11.1-0.20230711161743-2e82bdd1719d",
  "kind": "HOW",
  "packages": [
    "pkg:golang/golang.org/x/crypto@v0.11.1-0.20230711161743-2e82bdd1719d"
  ],
  "symbols": [
    "chacha20poly1305.New",
    "chacha20poly1305.NewX"
  ]
}
test/contract.go
package main

import (
	"bytes"
	"crypto/rand"
	"fmt"
	"io"
	"os"

	"golang.org/x/crypto/chacha20poly1305"
)

func main() {
	validKey := make([]byte, chacha20poly1305.KeySize)
	if _, err := io.ReadFull(rand.Reader, validKey); err != nil {
		fmt.Fprintf(os.Stderr, "failed to generate key: %v\n", err)
		os.Exit(1)
	}

	// 1. chacha20poly1305.New creates an AEAD cipher with standard 12-byte NonceSize and 16-byte Overhead
	aead, err := chacha20poly1305.New(validKey)
	if err != nil {
		fmt.Fprintf(os.Stderr, "chacha20poly1305.New failed with valid key: %v\n", err)
		os.Exit(1)
	}
	if aead.NonceSize() != 12 || aead.NonceSize() != chacha20poly1305.NonceSize {
		fmt.Fprintf(os.Stderr, "expected NonceSize 12, got %d\n", aead.NonceSize())
		os.Exit(1)
	}
	if aead.Overhead() != 16 || aead.Overhead() != chacha20poly1305.Overhead {
		fmt.Fprintf(os.Stderr, "expected Overhead 16, got %d\n", aead.Overhead())
		os.Exit(1)
	}

	// 2. chacha20poly1305.New rejects invalid key lengths not matching 32 bytes
	shortKey := make([]byte, 16)
	if _, err := chacha20poly1305.New(shortKey); err == nil {
		fmt.Fprintf(os.Stderr, "chacha20poly1305.New expected error for short key (16 bytes), got nil\n")
		os.Exit(1)
	}
	longKey := make([]byte, 64)
	if _, err := chacha20poly1305.New(longKey); err == nil {
		fmt.Fprintf(os.Stderr, "chacha20poly1305.New expected error for long key (64 bytes), got nil\n")
		os.Exit(1)
	}

	// 3. chacha20poly1305.NewX creates an AEAD cipher with extended 24-byte NonceSize and 16-byte Overhead
	aeadX, err := chacha20poly1305.NewX(validKey)
	if err != nil {
		fmt.Fprintf(os.Stderr, "chacha20poly1305.NewX failed with valid key: %v\n", err)
		os.Exit(1)
	}
	if aeadX.NonceSize() != 24 || aeadX.NonceSize() != chacha20poly1305.NonceSizeX {
		fmt.Fprintf(os.Stderr, "expected NonceSizeX 24, got %d\n", aeadX.NonceSize())
		os.Exit(1)
	}
	if aeadX.Overhead() != 16 || aeadX.Overhead() != chacha20poly1305.Overhead {
		fmt.Fprintf(os.Stderr, "expected Overhead 16, got %d\n", aeadX.Overhead())
		os.Exit(1)
	}

	// 4. chacha20poly1305.NewX rejects invalid key lengths not matching 32 bytes
	if _, err := chacha20poly1305.NewX(shortKey); err == nil {
		fmt.Fprintf(os.Stderr, "chacha20poly1305.NewX expected error for short key (16 bytes), got nil\n")
		os.Exit(1)
	}
	if _, err := chacha20poly1305.NewX(longKey); err == nil {
		fmt.Fprintf(os.Stderr, "chacha20poly1305.NewX expected error for long key (64 bytes), got nil\n")
		os.Exit(1)
	}

	// 5. aead.Seal and aead.Open correctly encrypt and decrypt plaintext with additional authenticated data
	plaintext := []byte("authenticated secret message payload")
	ad := []byte("context-header-v1")
	nonce := make([]byte, aead.NonceSize())
	if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
		fmt.Fprintf(os.Stderr, "failed to generate nonce: %v\n", err)
		os.Exit(1)
	}

	ciphertext := aead.Seal(nil, nonce, plaintext, ad)
	if len(ciphertext) != len(plaintext)+aead.Overhead() {
		fmt.Fprintf(os.Stderr, "expected ciphertext length %d, got %d\n", len(plaintext)+aead.Overhead(), len(ciphertext))
		os.Exit(1)
	}

	decrypted, err := aead.Open(nil, nonce, ciphertext, ad)
	if err != nil {
		fmt.Fprintf(os.Stderr, "aead.Open failed to decrypt: %v\n", err)
		os.Exit(1)
	}
	if !bytes.Equal(decrypted, plaintext) {
		fmt.Fprintf(os.Stderr, "decrypted plaintext does not match original: got %q, want %q\n", string(decrypted), string(plaintext))
		os.Exit(1)
	}

	// 6. aead.Open rejects tampered ciphertext or corrupted authentication tag
	tamperedCiphertext := make([]byte, len(ciphertext))
	copy(tamperedCiphertext, ciphertext)
	tamperedCiphertext[len(tamperedCiphertext)-1] ^= 0x01
	if _, err := aead.Open(nil, nonce, tamperedCiphertext, ad); err == nil {
		fmt.Fprintf(os.Stderr, "aead.Open expected authentication error on tampered tag, got nil\n")
		os.Exit(1)
	}

	// 7. aead.Open rejects mismatched additional authenticated data
	wrongAD := []byte("corrupted-header-v2")
	if _, err := aead.Open(nil, nonce, ciphertext, wrongAD); err == nil {
		fmt.Fprintf(os.Stderr, "aead.Open expected authentication error on mismatched AD, got nil\n")
		os.Exit(1)
	}

	// 8. aeadX.Seal and aeadX.Open round-trip plaintext with 24-byte extended nonce
	nonceX := make([]byte, aeadX.NonceSize())
	if _, err := io.ReadFull(rand.Reader, nonceX); err != nil {
		fmt.Fprintf(os.Stderr, "failed to generate nonceX: %v\n", err)
		os.Exit(1)
	}

	ciphertextX := aeadX.Seal(nil, nonceX, plaintext, ad)
	decryptedX, err := aeadX.Open(nil, nonceX, ciphertextX, ad)
	if err != nil {
		fmt.Fprintf(os.Stderr, "aeadX.Open failed to decrypt: %v\n", err)
		os.Exit(1)
	}
	if !bytes.Equal(decryptedX, plaintext) {
		fmt.Fprintf(os.Stderr, "aeadX decrypted plaintext does not match original: got %q, want %q\n", string(decryptedX), string(plaintext))
		os.Exit(1)
	}

	fmt.Println("All contract assertions passed.")
}

Исходный сидер

аноним