CodeSampleX

サンプル

golang.org/x/crypto v0.36.0: chacha20poly1305.NewX

検証済みサンプル — golang golang.org/x/crypto v0.36.0: chacha20poly1305.NewX. go 1.26 · linux alpine/x64 · docker で contract を実行し、成功しました.

sha256:5d5b7593a07e5220a5b00881562532303da8f969ddf367a5e5c0cac7c9862654

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
1
ビルドした署名鍵
1
宣言された環境 go 1.26 linux 24 · ubuntu · glibc 2.39 amd64 go 1.26 go 1.26 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-26

ケース

HOW
ゴール
verify chacha20poly1305.NewX in pkg:golang/golang.org/x/crypto@v0.36.0
パッケージ
シンボル
  • chacha20poly1305.NewX
環境
go 1.26.6
作成日
2026-08-26T01:22:17Z

コントラクト

  1. chacha20poly1305.NewX creates an XChaCha20-Poly1305 AEAD cipher with a 32-byte key
  2. chacha20poly1305.NewX rejects keys not equal to 32 bytes with an error
  3. aead.NonceSize returns 24 bytes for XChaCha20-Poly1305
  4. aead.Overhead returns 16 bytes for Poly1305 tag
  5. aead.Seal encrypts plaintext with 24-byte nonce and additional data
  6. aead.Open decrypts ciphertext and authenticates additional data
  7. aead.Open rejects tampered ciphertext, wrong nonce, or mismatched additional data

ファイル

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.go
  • spec.json
  • test/contract_test.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 chacha20poly1305.NewX in pkg:golang/golang.org/x/crypto@v0.36.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/golang.org/x/crypto@v0.36.0
Demonstrate these symbols/APIs:
  - chacha20poly1305.NewX
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:d62cfdd058427dcd3642b6fc3a9fee941eab57373c900115573e17601b52563c","contract":["chacha20poly1305.NewX creates an XChaCha20-Poly1305 AEAD cipher with a 32-byte key","chacha20poly1305.NewX rejects keys not equal to 32 bytes with an error","aead.NonceSize returns 24 bytes for XChaCha20-Poly1305","aead.Overhead returns 16 bytes for Poly1305 tag","aead.Seal encrypts plaintext with 24-byte nonce and additional data","aead.Open decrypts ciphertext and authenticates additional data","aead.Open rejects tampered ciphertext, wrong nonce, or mismatched additional data"],"goal":"verify chacha20poly1305.NewX in pkg:golang/golang.org/x/crypto@v0.36.0","kind":"HOW","packages":["pkg:golang/golang.org/x/crypto@v0.36.0"],"schemaVersion":1,"symbols":["chacha20poly1305.NewX"]},"contractCommand":["go","test","./..."],"environment":{"arch":"amd64","distro":"ubuntu","ecosystem":"golang","language":"go","languageVersion":"1.26.6","libc":"glibc","libcVersion":"2.39","moduleSystem":"go-mod","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.36.0"],"schemaVersion":1,"subject":"pkg:golang/golang.org/x/crypto@v0.36.0","symbols":["chacha20poly1305.NewX"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require golang.org/x/crypto v0.36.0

require golang.org/x/sys v0.31.0 // indirect
go.sum
golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34=
golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc=
golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=
golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
main.go
package main

import (
	"crypto/rand"
	"errors"
	"fmt"
	"io"

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

// Encrypt encrypts plaintext using XChaCha20-Poly1305 with a randomly generated 24-byte nonce.
// The nonce is prepended to the ciphertext.
func Encrypt(key, plaintext, additionalData []byte) ([]byte, error) {
	aead, err := chacha20poly1305.NewX(key)
	if err != nil {
		return nil, fmt.Errorf("failed to create cipher: %w", err)
	}

	nonce := make([]byte, aead.NonceSize())
	if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
		return nil, fmt.Errorf("failed to generate nonce: %w", err)
	}

	// Seal appends the ciphertext (with overhead) to the nonce
	ciphertext := aead.Seal(nonce, nonce, plaintext, additionalData)
	return ciphertext, nil
}

// Decrypt extracts the 24-byte nonce and decrypts the ciphertext using XChaCha20-Poly1305.
func Decrypt(key, ciphertext, additionalData []byte) ([]byte, error) {
	aead, err := chacha20poly1305.NewX(key)
	if err != nil {
		return nil, fmt.Errorf("failed to create cipher: %w", err)
	}

	nonceSize := aead.NonceSize()
	if len(ciphertext) < nonceSize+aead.Overhead() {
		return nil, errors.New("ciphertext too short")
	}

	nonce := ciphertext[:nonceSize]
	encryptedData := ciphertext[nonceSize:]

	plaintext, err := aead.Open(nil, nonce, encryptedData, additionalData)
	if err != nil {
		return nil, fmt.Errorf("failed to decrypt: %w", err)
	}

	return plaintext, nil
}

func main() {
	key := make([]byte, chacha20poly1305.KeySize)
	if _, err := io.ReadFull(rand.Reader, key); err != nil {
		panic(err)
	}

	plaintext := []byte("secret payload for XChaCha20-Poly1305")
	ad := []byte("metadata-context")

	encrypted, err := Encrypt(key, plaintext, ad)
	if err != nil {
		panic(err)
	}

	decrypted, err := Decrypt(key, encrypted, ad)
	if err != nil {
		panic(err)
	}

	fmt.Printf("Decrypted message: %s\n", string(decrypted))
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify chacha20poly1305.NewX in pkg:golang/golang.org/x/crypto@v0.36.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/golang.org/x/crypto@v0.36.0"
  ],
  "symbols": [
    "chacha20poly1305.NewX"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract_test.go
package contract_test

import (
	"bytes"
	"crypto/rand"
	"io"
	"testing"

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

func TestContract_ChaCha20Poly1305_NewX(t *testing.T) {
	// 1. chacha20poly1305.NewX creates an XChaCha20-Poly1305 AEAD cipher with 32-byte key
	validKey := make([]byte, chacha20poly1305.KeySize)
	if _, err := io.ReadFull(rand.Reader, validKey); err != nil {
		t.Fatalf("failed to generate random key: %v", err)
	}

	aead, err := chacha20poly1305.NewX(validKey)
	if err != nil {
		t.Fatalf("chacha20poly1305.NewX failed with valid 32-byte key: %v", err)
	}
	if aead == nil {
		t.Fatal("expected non-nil cipher.AEAD instance")
	}

	// 2. chacha20poly1305.NewX rejects keys not equal to 32 bytes with an error
	shortKey := make([]byte, 16)
	if _, err := chacha20poly1305.NewX(shortKey); err == nil {
		t.Fatal("expected error when initializing NewX with 16-byte key, got nil")
	}

	longKey := make([]byte, 64)
	if _, err := chacha20poly1305.NewX(longKey); err == nil {
		t.Fatal("expected error when initializing NewX with 64-byte key, got nil")
	}

	// 3. aead.NonceSize returns 24 bytes for XChaCha20-Poly1305
	if got := aead.NonceSize(); got != chacha20poly1305.NonceSizeX {
		t.Fatalf("expected NonceSize %d, got %d", chacha20poly1305.NonceSizeX, got)
	}
	if chacha20poly1305.NonceSizeX != 24 {
		t.Fatalf("expected NonceSizeX constant to be 24, got %d", chacha20poly1305.NonceSizeX)
	}

	// 4. aead.Overhead returns 16 bytes for Poly1305 tag
	if got := aead.Overhead(); got != chacha20poly1305.Overhead {
		t.Fatalf("expected Overhead %d, got %d", chacha20poly1305.Overhead, got)
	}
	if chacha20poly1305.Overhead != 16 {
		t.Fatalf("expected Overhead constant to be 16, got %d", chacha20poly1305.Overhead)
	}

	// 5. aead.Seal encrypts plaintext with 24-byte nonce and additional data
	nonce := make([]byte, chacha20poly1305.NonceSizeX)
	if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
		t.Fatalf("failed to generate random nonce: %v", err)
	}

	plaintext := []byte("XChaCha20-Poly1305 authenticated encryption verification")
	additionalData := []byte("associated-data-header")

	ciphertext := aead.Seal(nil, nonce, plaintext, additionalData)
	if len(ciphertext) != len(plaintext)+aead.Overhead() {
		t.Fatalf("expected ciphertext length %d, got %d", len(plaintext)+aead.Overhead(), len(ciphertext))
	}

	// 6. aead.Open decrypts ciphertext and authenticates additional data
	decrypted, err := aead.Open(nil, nonce, ciphertext, additionalData)
	if err != nil {
		t.Fatalf("aead.Open failed to decrypt: %v", err)
	}
	if !bytes.Equal(decrypted, plaintext) {
		t.Fatalf("decrypted text mismatch: got %q, want %q", string(decrypted), string(plaintext))
	}

	// 7. aead.Open rejects tampered ciphertext, wrong nonce, or mismatched additional data
	tamperedCiphertext := make([]byte, len(ciphertext))
	copy(tamperedCiphertext, ciphertext)
	tamperedCiphertext[0] ^= 0xff

	if _, err := aead.Open(nil, nonce, tamperedCiphertext, additionalData); err == nil {
		t.Fatal("expected error decrypting tampered ciphertext, got nil")
	}

	wrongAD := []byte("tampered-associated-data")
	if _, err := aead.Open(nil, nonce, ciphertext, wrongAD); err == nil {
		t.Fatal("expected error decrypting with mismatched additional data, got nil")
	}

	wrongNonce := make([]byte, chacha20poly1305.NonceSizeX)
	copy(wrongNonce, nonce)
	wrongNonce[0] ^= 0xff
	if _, err := aead.Open(nil, wrongNonce, ciphertext, additionalData); err == nil {
		t.Fatal("expected error decrypting with wrong nonce, got nil")
	}
}

オリジンシーダー

匿名