crypto

package
v1.7.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: MIT Imports: 17 Imported by: 9 modules, 8 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package crypto implements a simple convenience wrapper around golang.org/x/crypto/nacl/box. It ultimately models a situation where you don't care about authenticating the encryptor, so the nonce and encryption public key are prepended to the encrypted message.

Shared key precomputation is used when encrypting but not when decrypting. This is not an inherent limitation, but it would complicate the implementation a little bit to do precomputation during decryption also. If performance becomes an issue (highly unlikely), it's completely feasible to add.

Index

Examples

Constants

View Source
const (
	// SchemaVersionLegacy is the v1 NaCl box (X25519 + XSalsa20-Poly1305) schema.
	SchemaVersionLegacy = 1
	// SchemaVersionHybrid is the v2 post-quantum hybrid HPKE + session schema.
	SchemaVersionHybrid = 2

	// SchemeLegacy names the v1 Curve25519 NaCl box scheme.
	SchemeLegacy = "v1"
	// SchemeHybrid names the v2 hybrid ML-KEM-1024 + P-384 HPKE scheme.
	SchemeHybrid = "v2"

	// HybridSuiteID identifies the v2 HPKE ciphersuite (RFC 9180 / draft-ietf-hpke-pq).
	HybridSuiteID = "hpke-mlkem1024-p384-hkdf-sha384-export-only+aes256gcm"

	// HybridKeyIDPrefix distinguishes v2 key IDs (101 chars: "ejv2-" + 96 hex SHA-384)
	// from v1 64-hex public keys in keydirs, Secret Manager, and Kubernetes Secrets.
	HybridKeyIDPrefix = "ejv2-"

	// HybridPublicKeyPrefix marks v2 hybrid public keys in _public_key.
	HybridPublicKeyPrefix = "v2:"
)
View Source
const (
	// SessionFieldPrefix is the top-level JSON field prefix for v2 HPKE session
	// encapsulations: "_ejson_v2_session_<sid>".
	SessionFieldPrefix = "_ejson_v2_session_"
)

Variables

View Source
var ErrDecryptionFailed = errors.New("couldn't decrypt message")

ErrDecryptionFailed means the decryption didn't work. This normally indicates that the message was corrupted or the wrong keypair was used.

Functions

func BoxedMessageVersion added in v1.7.0

func BoxedMessageVersion(data []byte) (int, error)

BoxedMessageVersion returns the schema version of an EJ[...] value, or an error if data does not start with EJ[ and end with ].

func DeriveHybridKeypair added in v1.7.0

func DeriveHybridKeypair(ikm []byte) (HybridPublicKey, HybridPrivateKey, error)

DeriveHybridKeypair deterministically derives a v2 HPKE MLKEM1024-P384 keypair from input keying material using RFC 9180 DeriveKeyPair.

func GenerateHybridKeypair added in v1.7.0

func GenerateHybridKeypair() (HybridPublicKey, HybridPrivateKey, error)

GenerateHybridKeypair generates a v2 HPKE MLKEM1024-P384 keypair.

func GenerateKeypairForScheme added in v1.7.0

func GenerateKeypairForScheme(scheme string) (PublicKey, PrivateKey, error)

GenerateKeypairForScheme generates a v1 or v2 ejson keypair.

func HybridBoxedSessionID added in v1.7.0

func HybridBoxedSessionID(data []byte) (string, bool)

HybridBoxedSessionID returns the session ID of a structurally valid v2 EJ[2:<sid>:<n>:<ct>] value, or ("", false) if data is not one.

func IsBoxedMessage

func IsBoxedMessage(data []byte) bool

IsBoxedMessage tests whether a value is formatted using a supported boxed message format: the legacy v1 test, or a structurally valid v2 value.

func IsHybridBoxedMessage added in v1.7.0

func IsHybridBoxedMessage(data []byte) bool

IsHybridBoxedMessage tests whether a value is a structurally valid v2 EJ[2:<sid>:<n>:<ct>] value. It never overlaps with the legacy v1 test.

func OpenHybridSession added in v1.7.0

func OpenHybridSession(privateKey HybridPrivateKey, sess Session) ([]byte, error)

OpenHybridSession opens a Session using privateKey and exports its 32-byte AES-256-GCM data key.

func SessionIDFromEnc added in v1.7.0

func SessionIDFromEnc(enc []byte) string

SessionIDFromEnc computes the 32-hex session identifier from an HPKE encapsulation: lowercase hex of SHA-384(enc)[:16].

Types

type Decrypter

type Decrypter struct {
	Keypair *Keypair
}

Decrypter is generated from a keypair (a fixed keypair, generally, whose private key is stored in configuration management or otherwise), and used to decrypt messages. It should normally be obtained by calling Decrypter() on a Keypair instance.

func (*Decrypter) Decrypt

func (d *Decrypter) Decrypt(message []byte) ([]byte, error)

Decrypt is passed an encrypted message or a particular format (the format generated by (*Encrypter)Encrypt(), which includes the nonce and public key used to create the ciphertext. It returns the decrypted string. Note that, unlike with encryption, Shared-key-precomputation is not used for decryption.

Example
var ephemeral, recipient Keypair
if err := ephemeral.Generate(); err != nil {
	panic(err)
}
if err := recipient.Generate(); err != nil {
	panic(err)
}

encrypter := ephemeral.Encrypter(recipient.Public)
encrypted, err := encrypter.Encrypt([]byte("this is my message"))
if err != nil {
	panic(err)
}

decrypter := recipient.Decrypter()
plaintext, err := decrypter.Decrypt(encrypted)
fmt.Println(string(plaintext), err)
Output:
this is my message <nil>

type Encrypter

type Encrypter struct {
	Keypair    *Keypair
	PeerPublic [32]byte
	SharedKey  [32]byte
}

Encrypter is generated from a keypair (typically a newly-generated ephemeral keypair, used only for this session) with the public key of an authorized decrypter. It is then capable of encrypting messages to that decrypter's private key. An instance should normally be obtained only by calling Encrypter() on a Keypair instance.

func NewEncrypter

func NewEncrypter(kp *Keypair, peerPublic [32]byte) *Encrypter

NewEncrypter instantiates an Encrypter after pre-computing the shared key for the owned keypair and the given decrypter public key.

func (*Encrypter) Encrypt

func (e *Encrypter) Encrypt(message []byte) ([]byte, error)

Encrypt takes a plaintext message and returns an encrypted message. Unlike raw nacl/box encryption, this message is decryptable without passing the nonce or public key out-of-band, as it includes both. This is not less secure, it just doesn't allow for authorizing the encryptor. That's fine, since authorization isn't a desired property of this particular cryptosystem.

A message that already looks like a v1 boxed message is returned unchanged, which is what makes encrypting a file idempotent.

Example
var ephemeral, recipient Keypair
if err := ephemeral.Generate(); err != nil {
	panic(err)
}
if err := recipient.Generate(); err != nil {
	panic(err)
}

encrypter := ephemeral.Encrypter(recipient.Public)
boxed, err := encrypter.Encrypt([]byte("this is my message"))
fmt.Println(err == nil, len(boxed) > 0)
Output:
true true

func (*Encrypter) EncryptPlaintext added in v1.7.0

func (e *Encrypter) EncryptPlaintext(message []byte) ([]byte, error)

EncryptPlaintext always seals message, even when its bytes look like a boxed message. Use it for values known to be plaintext, such as the output of decryption during re-encryption.

type HybridDecrypter added in v1.7.0

type HybridDecrypter struct {
	// contains filtered or unexported fields
}

HybridDecrypter decrypts v2 EJ[2:<sid>:<n>:<ct>] values using the document's _ejson_v2_session_<sid> fields and a v2 private key. Each session is opened at most once, and duplicate (sid, n) pairs (reused nonces) are rejected.

func NewHybridDecrypter added in v1.7.0

func NewHybridDecrypter(privateKey HybridPrivateKey, sessions []Session) (*HybridDecrypter, error)

NewHybridDecrypter creates a v2 decrypter for privateKey and sessions.

func (*HybridDecrypter) Decrypt added in v1.7.0

func (d *HybridDecrypter) Decrypt(message []byte) ([]byte, error)

Decrypt decrypts a v2 EJ[2:<sid>:<n>:<ct>] boxed value. Refuses EJ[1:...] values, missing sessions, tampered ciphertexts, and reused (sid, n) nonces.

type HybridEncrypter added in v1.7.0

type HybridEncrypter struct {
	// contains filtered or unexported fields
}

HybridEncrypter lazily creates one session key and seals each new value with a distinct counter nonce. Encrypt is safe for concurrent use by json.Walker.

func NewHybridEncrypter added in v1.7.0

func NewHybridEncrypter(peerPublic HybridPublicKey) (*HybridEncrypter, error)

NewHybridEncrypter returns a session encrypter for peerPublic.

func (*HybridEncrypter) Encrypt added in v1.7.0

func (e *HybridEncrypter) Encrypt(message []byte) ([]byte, error)

Encrypt seals plaintext and retains structurally valid v2 values.

func (*HybridEncrypter) EncryptPlaintext added in v1.7.0

func (e *HybridEncrypter) EncryptPlaintext(message []byte) ([]byte, error)

EncryptPlaintext always encrypts message under the session key (used by Reencrypt after decryption).

func (*HybridEncrypter) ReferencedSessions added in v1.7.0

func (e *HybridEncrypter) ReferencedSessions() map[string]struct{}

ReferencedSessions returns the set of all session IDs referenced by values in the resulting document (both pre-existing EJ[2:...] values and the new session).

func (*HybridEncrypter) Session added in v1.7.0

func (e *HybridEncrypter) Session() (Session, bool)

Session returns the newly created HPKE Session, and true if at least one plaintext value was encrypted in this edit session.

type HybridPrivateKey added in v1.7.0

type HybridPrivateKey struct {
	Public HybridPublicKey
	// contains filtered or unexported fields
}

HybridPrivateKey is a v2 HPKE MLKEM1024-P384 private key represented by its compact 32-byte RFC 9180 seed (64 lowercase hex characters).

func (HybridPrivateKey) Seed added in v1.7.0

func (k HybridPrivateKey) Seed() []byte

Seed returns a copy of the 32-byte RFC 9180 HPKE seed.

func (HybridPrivateKey) String added in v1.7.0

func (k HybridPrivateKey) String() string

func (HybridPrivateKey) Version added in v1.7.0

func (k HybridPrivateKey) Version() int

type HybridPublicKey added in v1.7.0

type HybridPublicKey struct {
	// contains filtered or unexported fields
}

HybridPublicKey is a v2 HPKE MLKEM1024-P384 public key (1,665 bytes).

func NewHybridPublicKey added in v1.7.0

func NewHybridPublicKey(payload []byte) (HybridPublicKey, error)

NewHybridPublicKey validates and constructs a v2 hybrid public key from serialized RFC 9180 MLKEM1024-P384 public key bytes.

func ParseHybridPublicKeyString added in v1.7.0

func ParseHybridPublicKeyString(s string) (HybridPublicKey, error)

ParseHybridPublicKeyString parses a v2 hybrid public key ("v2:<base64>").

func (HybridPublicKey) Bytes added in v1.7.0

func (k HybridPublicKey) Bytes() []byte

Bytes returns a copy of the serialized RFC 9180 MLKEM1024-P384 public key bytes.

func (HybridPublicKey) KeyID added in v1.7.0

func (k HybridPublicKey) KeyID() string

KeyID returns "ejv2-" + lowercase hex SHA-384 of the 1,665 public-key bytes (101 characters: fits Secret Manager <=255, Kubernetes Secret keys <=253, and Linux keydir filenames <=255, and stays distinct from v1 64-hex keys).

func (HybridPublicKey) String added in v1.7.0

func (k HybridPublicKey) String() string

func (HybridPublicKey) Version added in v1.7.0

func (k HybridPublicKey) Version() int

type Keypair

type Keypair struct {
	Public  [32]byte
	Private [32]byte
}

Keypair models a Curve25519 keypair. To generate a new Keypair, declare an empty one and call Generate() on it.

func (*Keypair) Decrypter

func (k *Keypair) Decrypter() *Decrypter

Decrypter returns a Decrypter instance, used to decrypt properly formatted messages from arbitrary encrypters.

func (*Keypair) Encrypter

func (k *Keypair) Encrypter(peerPublic [32]byte) *Encrypter

Encrypter returns an Encrypter instance, given a public key, to encrypt messages to the paired, unknown, private key.

func (*Keypair) Generate

func (k *Keypair) Generate() (err error)

Generate generates a new Curve25519 keypair into a (presumably) empty Keypair structure.

func (*Keypair) PrivateString

func (k *Keypair) PrivateString() string

PrivateString returns the private key in the canonical hex-encoded printable form.

func (*Keypair) PublicString

func (k *Keypair) PublicString() string

PublicString returns the public key in the canonical hex-encoded printable form.

type LegacyPrivateKey added in v1.7.0

type LegacyPrivateKey struct {
	Key [32]byte
}

LegacyPrivateKey is the v1 32-byte Curve25519 private key.

func (LegacyPrivateKey) String added in v1.7.0

func (k LegacyPrivateKey) String() string

func (LegacyPrivateKey) Version added in v1.7.0

func (k LegacyPrivateKey) Version() int

type LegacyPublicKey added in v1.7.0

type LegacyPublicKey struct {
	Key [32]byte
}

LegacyPublicKey is the v1 32-byte Curve25519 public key.

func ParseLegacyPublicKeyString added in v1.7.0

func ParseLegacyPublicKeyString(s string) (LegacyPublicKey, error)

ParseLegacyPublicKeyString parses a legacy v1 public key.

func (LegacyPublicKey) KeyID added in v1.7.0

func (k LegacyPublicKey) KeyID() string

func (LegacyPublicKey) String added in v1.7.0

func (k LegacyPublicKey) String() string

func (LegacyPublicKey) Version added in v1.7.0

func (k LegacyPublicKey) Version() int

type MessageDecrypter added in v1.7.0

type MessageDecrypter interface {
	Decrypt([]byte) ([]byte, error)
}

MessageDecrypter decrypts individual JSON string values.

type MessageEncrypter added in v1.7.0

type MessageEncrypter interface {
	Encrypt([]byte) ([]byte, error)
}

MessageEncrypter encrypts individual JSON string values.

type PrivateKey added in v1.7.0

type PrivateKey interface {
	Version() int
	String() string
}

PrivateKey is a schema-aware ejson private key.

func ParsePrivateKeyForPublic added in v1.7.0

func ParsePrivateKeyForPublic(pub PublicKey, data []byte) (PrivateKey, error)

ParsePrivateKeyForPublic parses private key material for the corresponding public key. For v2 keys, the 32-byte seed is expanded and verified against the expected public key so a mismatched key fails closed immediately.

type PublicKey added in v1.7.0

type PublicKey interface {
	Version() int
	String() string
	KeyID() string
}

PublicKey is a schema-aware ejson public key.

func ParsePublicKeyString added in v1.7.0

func ParsePublicKeyString(s string) (PublicKey, error)

ParsePublicKeyString parses a public key in ejson document form. Legacy v1 keys are bare 64-character hex strings. Hybrid v2 keys are v2:<base64>.

type Session added in v1.7.0

type Session struct {
	ID  string
	Enc []byte
}

Session is one edit session's HPKE encapsulation stored in a v2 EJSON document as `"_ejson_v2_session_<sid>": "<base64(enc)>"`.

func NewHybridSession added in v1.7.0

func NewHybridSession(recipientPublic HybridPublicKey) (Session, []byte, error)

NewHybridSession creates one HPKE export-only session for recipientPublic using MLKEM1024-P384 / HKDF-SHA384 / ExportOnly, returning the Session and its 32-byte AES-256-GCM data key.

func ParseSession added in v1.7.0

func ParseSession(id, encB64 string) (Session, error)

ParseSession parses a session ID and its base64-encoded encapsulation and verifies that the ID matches SHA-384(enc)[:16].

func (Session) EncBase64 added in v1.7.0

func (s Session) EncBase64() string

EncBase64 returns the standard base64 encoding of the HPKE encapsulation.

func (Session) FieldName added in v1.7.0

func (s Session) FieldName() string

FieldName returns the top-level JSON key name for this session.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL