Пример
github.com/cloudflare/circl v1.6.0: Hybrid Public Key Encryption setup seal and open
Проверенный пример — golang github.com/cloudflare/circl v1.6.0: Hybrid Public Key Encryption setup seal and open. Контракт выполнен на go 1.26 · linux…
sha256:4a8c605a20bdafe79c654fdd929c53b7b05c14157eaecce5d8c07b1ea3a4f466
Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла.
Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди.
MIT-0
Свидетельства выполнения
Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.
- Основа свидетельства
- Подписанный контракт пройден
- Квитанции проверки
- 2
- Ключи подписи, собравшие его
- 1
Заявленная среда
go 1.26 linux 24 · ubuntu · glibc 2.39 x64 go 1.26 go 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-23 |
| 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- Цель
- Hybrid Public Key Encryption setup seal and open
- Символы
-
- hpke.Suite
- hpke.Suite.NewReceiver
- hpke.Suite.NewSender
- Окружение
- go 1.26.6
- Создан
- 2026-08-23T17:39:05Z
Контракт
- hpke.NewSuite initializes an HPKE cipher suite combining KEM, KDF, and AEAD identifiers.
- hpke.Suite.NewSender creates a Sender bound to a recipient public key and optional context info.
- hpke.Sender.Setup generates encapsulated key bytes and returns a Sealer for AEAD encryption.
- hpke.Suite.NewReceiver creates a Receiver bound to a recipient private key and matching context info.
- hpke.Receiver.Setup decapsulates key material using received encapsulated bytes and returns an Opener.
- hpke.Sealer.Seal encrypts plaintext with additional authenticated data, and hpke.Opener.Open decrypts the ciphertext back to the original plaintext.
- hpke.Opener.Open fails when ciphertext or additional authenticated data is tampered with.
Файлы
- PROMPT.md
- csx.json
- go.mod
- go.sum
- hpke_crypto.go
- spec.json
- test/contract_test.go
Исходный код
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: Hybrid Public Key Encryption setup seal and open
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:golang/github.com/cloudflare/circl@v1.6.0
Demonstrate these symbols/APIs:
- hpke.Suite
- hpke.Suite.NewReceiver
- hpke.Suite.NewSender
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.
{"case":{"caseId":"case:sha256:b887c732783201f0d0611d6ca846ef51e599521f22085168993c81ece462e1a7","contract":["hpke.NewSuite initializes an HPKE cipher suite combining KEM, KDF, and AEAD identifiers.","hpke.Suite.NewSender creates a Sender bound to a recipient public key and optional context info.","hpke.Sender.Setup generates encapsulated key bytes and returns a Sealer for AEAD encryption.","hpke.Suite.NewReceiver creates a Receiver bound to a recipient private key and matching context info.","hpke.Receiver.Setup decapsulates key material using received encapsulated bytes and returns an Opener.","hpke.Sealer.Seal encrypts plaintext with additional authenticated data, and hpke.Opener.Open decrypts the ciphertext back to the original plaintext.","hpke.Opener.Open fails when ciphertext or additional authenticated data is tampered with."],"goal":"Hybrid Public Key Encryption setup seal and open","kind":"HOW","packages":["pkg:golang/github.com/cloudflare/circl@v1.6.0"],"schemaVersion":1,"symbols":["hpke.Suite","hpke.Suite.NewReceiver","hpke.Suite.NewSender"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","language":"go","libc":"glibc","libcVersion":"2.39","moduleSystem":"gomod","os":"linux","osVersionBucket":"24","packageManager":"go","runtime":"go","runtimeVersion":"1.26.6","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/cloudflare/circl@v1.6.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/cloudflare/circl@v1.6.0","symbols":["hpke.Suite","hpke.Suite.NewReceiver","hpke.Suite.NewSender"],"verifierAdapter":"golang@1"}
module sample
go 1.22.0
require github.com/cloudflare/circl v1.6.0
require (
golang.org/x/crypto v0.11.1-0.20230711161743-2e82bdd1719d // indirect
golang.org/x/sys v0.10.0 // indirect
)
github.com/cloudflare/circl v1.6.0 h1:cr5JKic4HI+LkINy2lg3W2jF8sHCVTBncJr5gIIq7qk=
github.com/cloudflare/circl v1.6.0/go.mod h1:uddAzsPgqdMAYatqJ0lsjX1oECcQLIlRpzZh3pJrofs=
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=
package sample
import (
"crypto/rand"
"errors"
"io"
"github.com/cloudflare/circl/hpke"
"github.com/cloudflare/circl/kem"
)
// EncryptedMessage holds encapsulated key bytes and ciphertext.
type EncryptedMessage struct {
EncapsulatedKey []byte
Ciphertext []byte
}
// HPKECipher handles HPKE operations using a configured suite.
type HPKECipher struct {
Suite hpke.Suite
}
// NewHPKECipher creates an HPKECipher with the given KEM, KDF, and AEAD algorithms.
func NewHPKECipher(kemID hpke.KEM, kdfID hpke.KDF, aeadID hpke.AEAD) HPKECipher {
return HPKECipher{
Suite: hpke.NewSuite(kemID, kdfID, aeadID),
}
}
// GenerateKeyPair generates a new public/private key pair for the suite's KEM.
func (c HPKECipher) GenerateKeyPair() (kem.PublicKey, kem.PrivateKey, error) {
kemID, _, _ := c.Suite.Params()
return kemID.Scheme().GenerateKeyPair()
}
// Encrypt encrypts a plaintext message for a receiver public key with optional info and additional authenticated data.
func (c HPKECipher) Encrypt(pkR kem.PublicKey, info, plaintext, aad []byte, rnd io.Reader) (*EncryptedMessage, error) {
if rnd == nil {
rnd = rand.Reader
}
sender, err := c.Suite.NewSender(pkR, info)
if err != nil {
return nil, err
}
enc, sealer, err := sender.Setup(rnd)
if err != nil {
return nil, err
}
ciphertext, err := sealer.Seal(plaintext, aad)
if err != nil {
return nil, err
}
return &EncryptedMessage{
EncapsulatedKey: enc,
Ciphertext: ciphertext,
}, nil
}
// Decrypt decrypts an encrypted message using a receiver private key with matching info and additional authenticated data.
func (c HPKECipher) Decrypt(skR kem.PrivateKey, info []byte, msg *EncryptedMessage, aad []byte) ([]byte, error) {
if msg == nil {
return nil, errors.New("nil message")
}
receiver, err := c.Suite.NewReceiver(skR, info)
if err != nil {
return nil, err
}
opener, err := receiver.Setup(msg.EncapsulatedKey)
if err != nil {
return nil, err
}
return opener.Open(msg.Ciphertext, aad)
}
{
"schemaVersion": 1,
"goal": "Hybrid Public Key Encryption setup seal and open",
"kind": "HOW",
"packages": [
"pkg:golang/github.com/cloudflare/circl@v1.6.0"
],
"symbols": [
"hpke.Suite",
"hpke.Suite.NewReceiver",
"hpke.Suite.NewSender"
],
"constraints": {
"executionContext": "node"
},
"runtimeConditions": {
"ecosystem": "npm",
"language": "javascript",
"moduleSystem": "cjs",
"packageManager": "npm@10.9.8",
"runtime": "node@22.23.2"
}
}
package test
import (
"bytes"
"crypto/rand"
"testing"
"sample"
"github.com/cloudflare/circl/hpke"
)
func TestContract_HPKE(t *testing.T) {
// Assertion 1: hpke.NewSuite initializes an HPKE cipher suite combining KEM, KDF, and AEAD identifiers.
kemID := hpke.KEM_P256_HKDF_SHA256
kdfID := hpke.KDF_HKDF_SHA256
aeadID := hpke.AEAD_AES128GCM
suite := hpke.NewSuite(kemID, kdfID, aeadID)
k, f, a := suite.Params()
if k != kemID || f != kdfID || a != aeadID {
t.Fatalf("suite params mismatch: got (%v, %v, %v), want (%v, %v, %v)", k, f, a, kemID, kdfID, aeadID)
}
// Keypair generation for recipient
pkR, skR, err := kemID.Scheme().GenerateKeyPair()
if err != nil {
t.Fatalf("failed to generate key pair: %v", err)
}
info := []byte("sample-hpke-context-info")
// Assertion 2: hpke.Suite.NewSender creates a Sender bound to a recipient public key and optional context info.
sender, err := suite.NewSender(pkR, info)
if err != nil {
t.Fatalf("suite.NewSender failed: %v", err)
}
// Assertion 3: hpke.Sender.Setup generates encapsulated key bytes and returns a Sealer for AEAD encryption.
enc, sealer, err := sender.Setup(rand.Reader)
if err != nil {
t.Fatalf("sender.Setup failed: %v", err)
}
if len(enc) == 0 {
t.Fatalf("encapsulated key is empty")
}
// Assertion 4: hpke.Suite.NewReceiver creates a Receiver bound to a recipient private key and matching context info.
receiver, err := suite.NewReceiver(skR, info)
if err != nil {
t.Fatalf("suite.NewReceiver failed: %v", err)
}
// Assertion 5: hpke.Receiver.Setup decapsulates key material using received encapsulated bytes and returns an Opener.
opener, err := receiver.Setup(enc)
if err != nil {
t.Fatalf("receiver.Setup failed: %v", err)
}
// Assertion 6: hpke.Sealer.Seal encrypts plaintext with additional authenticated data, and hpke.Opener.Open decrypts the ciphertext back to the original plaintext.
plaintext := []byte("hybrid public key encryption verified payload")
aad := []byte("authenticated header 2026")
ciphertext, err := sealer.Seal(plaintext, aad)
if err != nil {
t.Fatalf("sealer.Seal failed: %v", err)
}
decrypted, err := opener.Open(ciphertext, aad)
if err != nil {
t.Fatalf("opener.Open failed: %v", err)
}
if !bytes.Equal(decrypted, plaintext) {
t.Fatalf("decrypted payload mismatch: got %q, want %q", decrypted, plaintext)
}
// Assertion 7: hpke.Opener.Open fails when ciphertext or additional authenticated data is tampered with.
tamperedCiphertext := append([]byte(nil), ciphertext...)
tamperedCiphertext[0] ^= 0xFF
if _, err := opener.Open(tamperedCiphertext, aad); err == nil {
t.Fatalf("expected Open failure with tampered ciphertext")
}
tamperedAAD := []byte("corrupted header")
if _, err := opener.Open(ciphertext, tamperedAAD); err == nil {
t.Fatalf("expected Open failure with tampered AAD")
}
// Also verify via HPKECipher wrapper
cipher := sample.NewHPKECipher(kemID, kdfID, aeadID)
msg, err := cipher.Encrypt(pkR, info, plaintext, aad, rand.Reader)
if err != nil {
t.Fatalf("cipher.Encrypt failed: %v", err)
}
recovered, err := cipher.Decrypt(skR, info, msg, aad)
if err != nil {
t.Fatalf("cipher.Decrypt failed: %v", err)
}
if !bytes.Equal(recovered, plaintext) {
t.Fatalf("cipher.Decrypt payload mismatch: got %q, want %q", recovered, plaintext)
}
}
Исходный сидер
аноним