You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@iceberg.apache.org by "hectar-glitches (via GitHub)" <gi...@apache.org> on 2026/07/30 20:45:03 UTC

[PR] feat(encryption): add StandardEncryptionManager [iceberg-go]

hectar-glitches opened a new pull request, #1620:
URL: https://github.com/apache/iceberg-go/pull/1620

   ## Summary
   Adds 'StandardEncryptionManager', a KMS-backed 'EncryptionManager' implementation for generic (format-agnostic) file envelope encryption, e.g. manifests, manifest lists, and Puffin statistics files. This follows on from #1447, which merged the 'EncryptionManager'/'KeyManagementClient' interfaces, 'PlaintextEncryptionManager', and the in-memory KMS, and #1493, which added the KMS catalog-property registry ('kms-type'). As discussed in #1289, this is the piece everything downstream ('EncryptingFileIO', Parquet native encryption, manifest/manifest-list encryption, Puffin blob encryption) needs before it can do real encryption, so it's the next slice in the proposed split.
   
   It uses a 'KeyManagementClient' to generate/wrap a fresh AES-256 data encryption key (DEK) per file, splits each file into fixed-size plaintext blocks (default 64KB), and seals each block independently with AES-GCM using a unique nonce (per-file random prefix combined with the block index). Since blocks are sealed independently, decrypted files support random access ('Seek'/'ReadAt') without decrypting the whole file, which is required since 'icebergio.File' mandates 'io.ReaderAt'/'io.Seeker'. Everything needed to decrypt (wrapped DEK, key ID, nonce prefix, block size, plaintext length) is persisted as a small JSON blob in the opaque per-file 'key_metadata' already carried by manifest entries. It fails closed, consistent with 'PlaintextEncryptionManager': it requires a non-empty 'keyID' on write ('ErrKeyIDRequired') and non-empty key metadata on read ('ErrKeyMetadataRequired'), rather than silently no-op'ing.
   
   Testing covers round trips (sub-block, multi-block, exact block-size multiple, empty file), random access ('ReadAt' spanning a block boundary, 'Seek' plus sequential read), tamper detection (a flipped ciphertext byte fails with 'ErrAuthenticationFailed'), and error paths (empty keyID, empty key metadata, unknown KMS key ID, malformed key metadata). Verified with 'go vet', 'go test -race -count=2', and 'golangci-lint' (0 issues).
   
   This PR is the standalone encryption engine only, it does not yet wire 'StandardEncryptionManager' into 'EncryptingFileIO' or any table/catalog code path, that follow-up work is tracked in #1289.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat(encryption): add StandardEncryptionManager [iceberg-go]

Posted by "zeroshade (via GitHub)" <gi...@apache.org>.
zeroshade commented on code in PR #1620:
URL: https://github.com/apache/iceberg-go/pull/1620#discussion_r3732078930


##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,511 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 {
+		return nil, fmt.Errorf("%w: block-size must be positive, got %d", ErrInvalidKeyMetadata, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}
+	if len(meta.NoncePrefix) != 4 {
+		return nil, fmt.Errorf("%w: nonce-prefix must be 4 bytes, got %d", ErrInvalidKeyMetadata, len(meta.NoncePrefix))
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	return &standardInputFile{
+		underlying:      file,
+		aead:            aead,
+		noncePrefix:     meta.NoncePrefix,
+		blockSize:       meta.BlockSize,
+		plaintextLength: meta.PlaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newStandardAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %v", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// standardBlockNonce derives the AES-GCM nonce for blockIndex: the 4-byte
+// per-file random prefix followed by the 8-byte big-endian block index. The
+// (key, nonce) pair is unique per block since the DEK is fresh per file and
+// no two blocks in the same file share an index.
+func standardBlockNonce(prefix []byte, blockIndex uint64) []byte {
+	nonce := make([]byte, 12)
+	copy(nonce, prefix)
+	binary.BigEndian.PutUint64(nonce[4:], blockIndex)
+
+	return nonce
+}
+
+// standardOutputFile is an [EncryptedOutputFile] that seals fixed-size
+// plaintext blocks with AES-GCM as they are written.
+type standardOutputFile struct {
+	icebergio.FileWriter
+
+	aead        cipher.AEAD
+	noncePrefix []byte
+	blockSize   int
+	keyID       string
+	wrappedKey  []byte
+
+	buf        []byte
+	blockIndex uint64
+	written    int64
+	closed     bool
+
+	keyMetadata EncryptionKeyMetadata
+}
+
+var _ EncryptedOutputFile = (*standardOutputFile)(nil)
+
+func (f *standardOutputFile) Write(p []byte) (int, error) {
+	total := len(p)
+	for len(p) > 0 {
+		space := f.blockSize - len(f.buf)
+		n := min(space, len(p))
+		f.buf = append(f.buf, p[:n]...)
+		p = p[n:]
+		f.written += int64(n)
+		if len(f.buf) == f.blockSize {
+			if err := f.flushBlock(); err != nil {
+				return total - len(p), err
+			}
+		}
+	}
+
+	return total, nil
+}
+
+func (f *standardOutputFile) flushBlock() error {
+	ciphertext := f.aead.Seal(nil, standardBlockNonce(f.noncePrefix, f.blockIndex), f.buf, nil)

Review Comment:
   **Blocking: no AAD means a file can be silently truncated.**
   
   `Seal` passes `nil` for additional data here, and `Open` does the same at line 424. Combined with `plaintext-length` living in unauthenticated key metadata, an attacker who can edit a manifest entry can shorten `plaintext-length` to a block boundary and truncate the ciphertext — every remaining block still authenticates, so decryption succeeds silently.
   
   I verified this: a 4-block file with `plaintext-length` edited to 32 and the ciphertext cut at a block boundary decrypted with `err = nil` and returned 32 bytes of valid plaintext. No error surfaced anywhere.
   
   The spec's AAD construction (`aadPrefix || blockSequenceNumber`) exists specifically to prevent this, along with block swapping within and between files.
   
   Suggested fix: bind an AAD prefix (file identifier) plus the block index into the AAD on both `Seal` and `Open`, and validate the ciphertext length against `plaintext-length` before the first `Open`.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,511 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {

Review Comment:
   The doc comment states that `kms` must not be nil, but it isn't checked — a nil KMS panics with a nil-pointer dereference at first use rather than failing at construction.
   
   Either return an error, or panic explicitly here with a clear message.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,511 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 {
+		return nil, fmt.Errorf("%w: block-size must be positive, got %d", ErrInvalidKeyMetadata, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}
+	if len(meta.NoncePrefix) != 4 {
+		return nil, fmt.Errorf("%w: nonce-prefix must be 4 bytes, got %d", ErrInvalidKeyMetadata, len(meta.NoncePrefix))
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	return &standardInputFile{
+		underlying:      file,
+		aead:            aead,
+		noncePrefix:     meta.NoncePrefix,
+		blockSize:       meta.BlockSize,
+		plaintextLength: meta.PlaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newStandardAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %v", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// standardBlockNonce derives the AES-GCM nonce for blockIndex: the 4-byte
+// per-file random prefix followed by the 8-byte big-endian block index. The
+// (key, nonce) pair is unique per block since the DEK is fresh per file and
+// no two blocks in the same file share an index.
+func standardBlockNonce(prefix []byte, blockIndex uint64) []byte {
+	nonce := make([]byte, 12)
+	copy(nonce, prefix)
+	binary.BigEndian.PutUint64(nonce[4:], blockIndex)
+
+	return nonce
+}
+
+// standardOutputFile is an [EncryptedOutputFile] that seals fixed-size
+// plaintext blocks with AES-GCM as they are written.
+type standardOutputFile struct {
+	icebergio.FileWriter
+
+	aead        cipher.AEAD
+	noncePrefix []byte
+	blockSize   int
+	keyID       string
+	wrappedKey  []byte
+
+	buf        []byte
+	blockIndex uint64
+	written    int64
+	closed     bool
+
+	keyMetadata EncryptionKeyMetadata
+}
+
+var _ EncryptedOutputFile = (*standardOutputFile)(nil)
+
+func (f *standardOutputFile) Write(p []byte) (int, error) {
+	total := len(p)
+	for len(p) > 0 {
+		space := f.blockSize - len(f.buf)
+		n := min(space, len(p))
+		f.buf = append(f.buf, p[:n]...)
+		p = p[n:]
+		f.written += int64(n)
+		if len(f.buf) == f.blockSize {
+			if err := f.flushBlock(); err != nil {
+				return total - len(p), err
+			}
+		}
+	}
+
+	return total, nil
+}
+
+func (f *standardOutputFile) flushBlock() error {
+	ciphertext := f.aead.Seal(nil, standardBlockNonce(f.noncePrefix, f.blockIndex), f.buf, nil)
+	if _, err := f.FileWriter.Write(ciphertext); err != nil {
+		return fmt.Errorf("encryption: failed to write encrypted block: %w", err)
+	}
+	f.blockIndex++
+	f.buf = f.buf[:0]
+
+	return nil
+}
+
+// ReadFrom copies from r, encrypting as data is written, satisfying
+// io.ReaderFrom (required by [icebergio.FileWriter]).
+func (f *standardOutputFile) ReadFrom(r io.Reader) (int64, error) {
+	buf := make([]byte, 32*1024)
+	var total int64
+	for {
+		n, err := r.Read(buf)
+		if n > 0 {
+			wn, werr := f.Write(buf[:n])
+			total += int64(wn)
+			if werr != nil {
+				return total, werr
+			}
+		}
+		if err == io.EOF {
+			break
+		}
+		if err != nil {
+			return total, err
+		}
+	}
+
+	return total, nil
+}
+
+func (f *standardOutputFile) Close() error {
+	if f.closed {
+		return nil
+	}
+	f.closed = true
+
+	if len(f.buf) > 0 {
+		if err := f.flushBlock(); err != nil {
+			_ = f.FileWriter.Close()
+
+			return err
+		}
+	}
+
+	meta := standardKeyMetadata{
+		Version:         standardKeyMetadataVersion,
+		KeyID:           f.keyID,
+		WrappedKey:      f.wrappedKey,
+		NoncePrefix:     f.noncePrefix,
+		BlockSize:       f.blockSize,
+		PlaintextLength: f.written,
+	}
+	encoded, err := json.Marshal(meta)
+	if err != nil {
+		_ = f.FileWriter.Close()
+
+		return fmt.Errorf("encryption: failed to encode key metadata: %w", err)
+	}
+	f.keyMetadata = encoded
+
+	return f.FileWriter.Close()
+}
+
+// KeyMetadata returns the finalized per-file key metadata. It is only
+// populated after Close has been called.
+func (f *standardOutputFile) KeyMetadata() EncryptionKeyMetadata { return f.keyMetadata }
+
+// standardInputFile is an [EncryptedInputFile] that decrypts fixed-size
+// AES-GCM blocks on demand, supporting random access via ReadAt/Seek.
+type standardInputFile struct {
+	underlying      icebergio.File
+	aead            cipher.AEAD
+	noncePrefix     []byte
+	blockSize       int
+	plaintextLength int64
+	keyMetadata     EncryptionKeyMetadata
+
+	pos int64
+}
+
+var _ EncryptedInputFile = (*standardInputFile)(nil)
+
+func (f *standardInputFile) numBlocks() int64 {
+	if f.plaintextLength == 0 {
+		return 0
+	}
+
+	return (f.plaintextLength + int64(f.blockSize) - 1) / int64(f.blockSize)
+}
+
+func (f *standardInputFile) blockPlainLen(idx int64) int64 {
+	if idx == f.numBlocks()-1 {
+		return f.plaintextLength - idx*int64(f.blockSize)
+	}
+
+	return int64(f.blockSize)
+}
+
+func (f *standardInputFile) physicalOffset(idx int64) int64 {
+	return idx * int64(f.blockSize+f.aead.Overhead())
+}
+
+func (f *standardInputFile) readBlock(idx int64) ([]byte, error) {
+	plainLen := f.blockPlainLen(idx)
+	ciphertext := make([]byte, plainLen+int64(f.aead.Overhead()))
+	if _, err := f.underlying.ReadAt(ciphertext, f.physicalOffset(idx)); err != nil && !errors.Is(err, io.EOF) {

Review Comment:
   Two small things here.
   
   The `ReadAt` byte count is discarded. A short read fails *safe* — authentication catches it — but it surfaces as `ErrAuthenticationFailed`, which sends anyone debugging a truncated file down the wrong path. Using `io.ReadFull` semantics and a distinct truncation error would be clearer.
   
   To be explicit, since an earlier review comment raised this: the discarded count does **not** break the final partial block. The buffer is sized to exactly the remaining bytes, and I confirmed against a real `os.File` that a multi-block-plus-tail round trip returns `err=nil, got=40, want=40`.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,511 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 {
+		return nil, fmt.Errorf("%w: block-size must be positive, got %d", ErrInvalidKeyMetadata, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}
+	if len(meta.NoncePrefix) != 4 {
+		return nil, fmt.Errorf("%w: nonce-prefix must be 4 bytes, got %d", ErrInvalidKeyMetadata, len(meta.NoncePrefix))
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	return &standardInputFile{
+		underlying:      file,
+		aead:            aead,
+		noncePrefix:     meta.NoncePrefix,
+		blockSize:       meta.BlockSize,
+		plaintextLength: meta.PlaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newStandardAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %v", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// standardBlockNonce derives the AES-GCM nonce for blockIndex: the 4-byte
+// per-file random prefix followed by the 8-byte big-endian block index. The
+// (key, nonce) pair is unique per block since the DEK is fresh per file and
+// no two blocks in the same file share an index.
+func standardBlockNonce(prefix []byte, blockIndex uint64) []byte {
+	nonce := make([]byte, 12)
+	copy(nonce, prefix)
+	binary.BigEndian.PutUint64(nonce[4:], blockIndex)
+
+	return nonce
+}
+
+// standardOutputFile is an [EncryptedOutputFile] that seals fixed-size
+// plaintext blocks with AES-GCM as they are written.
+type standardOutputFile struct {
+	icebergio.FileWriter
+
+	aead        cipher.AEAD
+	noncePrefix []byte
+	blockSize   int
+	keyID       string
+	wrappedKey  []byte
+
+	buf        []byte
+	blockIndex uint64
+	written    int64
+	closed     bool
+
+	keyMetadata EncryptionKeyMetadata
+}
+
+var _ EncryptedOutputFile = (*standardOutputFile)(nil)
+
+func (f *standardOutputFile) Write(p []byte) (int, error) {
+	total := len(p)
+	for len(p) > 0 {
+		space := f.blockSize - len(f.buf)
+		n := min(space, len(p))
+		f.buf = append(f.buf, p[:n]...)
+		p = p[n:]
+		f.written += int64(n)
+		if len(f.buf) == f.blockSize {
+			if err := f.flushBlock(); err != nil {
+				return total - len(p), err
+			}
+		}
+	}
+
+	return total, nil
+}
+
+func (f *standardOutputFile) flushBlock() error {
+	ciphertext := f.aead.Seal(nil, standardBlockNonce(f.noncePrefix, f.blockIndex), f.buf, nil)
+	if _, err := f.FileWriter.Write(ciphertext); err != nil {
+		return fmt.Errorf("encryption: failed to write encrypted block: %w", err)
+	}
+	f.blockIndex++
+	f.buf = f.buf[:0]
+
+	return nil
+}
+
+// ReadFrom copies from r, encrypting as data is written, satisfying
+// io.ReaderFrom (required by [icebergio.FileWriter]).
+func (f *standardOutputFile) ReadFrom(r io.Reader) (int64, error) {
+	buf := make([]byte, 32*1024)
+	var total int64
+	for {
+		n, err := r.Read(buf)
+		if n > 0 {
+			wn, werr := f.Write(buf[:n])
+			total += int64(wn)
+			if werr != nil {
+				return total, werr
+			}
+		}
+		if err == io.EOF {
+			break
+		}
+		if err != nil {
+			return total, err
+		}
+	}
+
+	return total, nil
+}
+
+func (f *standardOutputFile) Close() error {
+	if f.closed {
+		return nil
+	}
+	f.closed = true
+
+	if len(f.buf) > 0 {
+		if err := f.flushBlock(); err != nil {
+			_ = f.FileWriter.Close()
+
+			return err
+		}
+	}
+
+	meta := standardKeyMetadata{
+		Version:         standardKeyMetadataVersion,
+		KeyID:           f.keyID,
+		WrappedKey:      f.wrappedKey,
+		NoncePrefix:     f.noncePrefix,
+		BlockSize:       f.blockSize,
+		PlaintextLength: f.written,
+	}
+	encoded, err := json.Marshal(meta)
+	if err != nil {
+		_ = f.FileWriter.Close()
+
+		return fmt.Errorf("encryption: failed to encode key metadata: %w", err)
+	}
+	f.keyMetadata = encoded
+
+	return f.FileWriter.Close()
+}
+
+// KeyMetadata returns the finalized per-file key metadata. It is only
+// populated after Close has been called.
+func (f *standardOutputFile) KeyMetadata() EncryptionKeyMetadata { return f.keyMetadata }
+
+// standardInputFile is an [EncryptedInputFile] that decrypts fixed-size
+// AES-GCM blocks on demand, supporting random access via ReadAt/Seek.
+type standardInputFile struct {
+	underlying      icebergio.File
+	aead            cipher.AEAD
+	noncePrefix     []byte
+	blockSize       int
+	plaintextLength int64
+	keyMetadata     EncryptionKeyMetadata
+
+	pos int64
+}
+
+var _ EncryptedInputFile = (*standardInputFile)(nil)
+
+func (f *standardInputFile) numBlocks() int64 {
+	if f.plaintextLength == 0 {
+		return 0
+	}
+
+	return (f.plaintextLength + int64(f.blockSize) - 1) / int64(f.blockSize)
+}
+
+func (f *standardInputFile) blockPlainLen(idx int64) int64 {
+	if idx == f.numBlocks()-1 {
+		return f.plaintextLength - idx*int64(f.blockSize)
+	}
+
+	return int64(f.blockSize)
+}
+
+func (f *standardInputFile) physicalOffset(idx int64) int64 {
+	return idx * int64(f.blockSize+f.aead.Overhead())
+}
+
+func (f *standardInputFile) readBlock(idx int64) ([]byte, error) {

Review Comment:
   Not blocking, but a significant read cost: there's no block cache, so every `Read` re-decrypts its entire block.
   
   Measured: 5000 one-byte `Read` calls triggered 5000 full 64 KiB block decryptions — about 320 MB of AES to read 5 KB. Even a 4 KiB buffered reader shows ~4x amplification.
   
   Caching the most recently decrypted block is only a few lines. One caveat: a naive cache would break the parallel-use guarantee that `ReadAt` is documented to provide, so it needs guarding.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,511 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 {
+		return nil, fmt.Errorf("%w: block-size must be positive, got %d", ErrInvalidKeyMetadata, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}
+	if len(meta.NoncePrefix) != 4 {
+		return nil, fmt.Errorf("%w: nonce-prefix must be 4 bytes, got %d", ErrInvalidKeyMetadata, len(meta.NoncePrefix))
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	return &standardInputFile{
+		underlying:      file,
+		aead:            aead,
+		noncePrefix:     meta.NoncePrefix,
+		blockSize:       meta.BlockSize,
+		plaintextLength: meta.PlaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newStandardAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %v", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// standardBlockNonce derives the AES-GCM nonce for blockIndex: the 4-byte
+// per-file random prefix followed by the 8-byte big-endian block index. The
+// (key, nonce) pair is unique per block since the DEK is fresh per file and
+// no two blocks in the same file share an index.
+func standardBlockNonce(prefix []byte, blockIndex uint64) []byte {
+	nonce := make([]byte, 12)
+	copy(nonce, prefix)
+	binary.BigEndian.PutUint64(nonce[4:], blockIndex)
+
+	return nonce
+}
+
+// standardOutputFile is an [EncryptedOutputFile] that seals fixed-size
+// plaintext blocks with AES-GCM as they are written.
+type standardOutputFile struct {
+	icebergio.FileWriter
+
+	aead        cipher.AEAD
+	noncePrefix []byte
+	blockSize   int
+	keyID       string
+	wrappedKey  []byte
+
+	buf        []byte
+	blockIndex uint64
+	written    int64
+	closed     bool
+
+	keyMetadata EncryptionKeyMetadata
+}
+
+var _ EncryptedOutputFile = (*standardOutputFile)(nil)
+
+func (f *standardOutputFile) Write(p []byte) (int, error) {

Review Comment:
   `Write` after `Close` silently appends more sealed blocks and returns `nil`, while `KeyMetadata()` still describes the shorter file — so the trailing blocks are unreadable but no error is raised.
   
   Suggested fix: reject writes on a closed file with `fs.ErrClosed`.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,511 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 {
+		return nil, fmt.Errorf("%w: block-size must be positive, got %d", ErrInvalidKeyMetadata, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}
+	if len(meta.NoncePrefix) != 4 {
+		return nil, fmt.Errorf("%w: nonce-prefix must be 4 bytes, got %d", ErrInvalidKeyMetadata, len(meta.NoncePrefix))
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	return &standardInputFile{
+		underlying:      file,
+		aead:            aead,
+		noncePrefix:     meta.NoncePrefix,
+		blockSize:       meta.BlockSize,
+		plaintextLength: meta.PlaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newStandardAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %v", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// standardBlockNonce derives the AES-GCM nonce for blockIndex: the 4-byte
+// per-file random prefix followed by the 8-byte big-endian block index. The
+// (key, nonce) pair is unique per block since the DEK is fresh per file and
+// no two blocks in the same file share an index.
+func standardBlockNonce(prefix []byte, blockIndex uint64) []byte {
+	nonce := make([]byte, 12)
+	copy(nonce, prefix)
+	binary.BigEndian.PutUint64(nonce[4:], blockIndex)
+
+	return nonce
+}
+
+// standardOutputFile is an [EncryptedOutputFile] that seals fixed-size
+// plaintext blocks with AES-GCM as they are written.
+type standardOutputFile struct {
+	icebergio.FileWriter
+
+	aead        cipher.AEAD
+	noncePrefix []byte
+	blockSize   int
+	keyID       string
+	wrappedKey  []byte
+
+	buf        []byte
+	blockIndex uint64
+	written    int64
+	closed     bool
+
+	keyMetadata EncryptionKeyMetadata
+}
+
+var _ EncryptedOutputFile = (*standardOutputFile)(nil)
+
+func (f *standardOutputFile) Write(p []byte) (int, error) {
+	total := len(p)
+	for len(p) > 0 {
+		space := f.blockSize - len(f.buf)
+		n := min(space, len(p))
+		f.buf = append(f.buf, p[:n]...)
+		p = p[n:]
+		f.written += int64(n)
+		if len(f.buf) == f.blockSize {
+			if err := f.flushBlock(); err != nil {
+				return total - len(p), err
+			}
+		}
+	}
+
+	return total, nil
+}
+
+func (f *standardOutputFile) flushBlock() error {
+	ciphertext := f.aead.Seal(nil, standardBlockNonce(f.noncePrefix, f.blockIndex), f.buf, nil)
+	if _, err := f.FileWriter.Write(ciphertext); err != nil {
+		return fmt.Errorf("encryption: failed to write encrypted block: %w", err)
+	}
+	f.blockIndex++
+	f.buf = f.buf[:0]
+
+	return nil
+}
+
+// ReadFrom copies from r, encrypting as data is written, satisfying
+// io.ReaderFrom (required by [icebergio.FileWriter]).
+func (f *standardOutputFile) ReadFrom(r io.Reader) (int64, error) {
+	buf := make([]byte, 32*1024)
+	var total int64
+	for {
+		n, err := r.Read(buf)
+		if n > 0 {
+			wn, werr := f.Write(buf[:n])
+			total += int64(wn)
+			if werr != nil {
+				return total, werr
+			}
+		}
+		if err == io.EOF {
+			break
+		}
+		if err != nil {
+			return total, err
+		}
+	}
+
+	return total, nil
+}
+
+func (f *standardOutputFile) Close() error {
+	if f.closed {
+		return nil
+	}
+	f.closed = true

Review Comment:
   **Blocking: a failed `Close` reports success when retried.**
   
   `closed` is set before the final flush, so if the flush fails, a second `Close` takes the early-return path and returns `nil`. I measured `Close#1 = "failed to write encrypted block: disk full"`, `Close#2 = nil`.
   
   This matters because `defer f.Close()` alongside an explicit `f.Close()` is such a common pattern — the deferred call reports success on a file that was never written. `KeyMetadata()` is correctly left empty, so the damage is bounded, but a caller checking only the error would proceed.
   
   Suggested fix: record the failure and return it from every subsequent `Close`.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,511 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 {
+		return nil, fmt.Errorf("%w: block-size must be positive, got %d", ErrInvalidKeyMetadata, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}
+	if len(meta.NoncePrefix) != 4 {
+		return nil, fmt.Errorf("%w: nonce-prefix must be 4 bytes, got %d", ErrInvalidKeyMetadata, len(meta.NoncePrefix))
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	return &standardInputFile{
+		underlying:      file,
+		aead:            aead,
+		noncePrefix:     meta.NoncePrefix,
+		blockSize:       meta.BlockSize,
+		plaintextLength: meta.PlaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newStandardAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %v", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// standardBlockNonce derives the AES-GCM nonce for blockIndex: the 4-byte
+// per-file random prefix followed by the 8-byte big-endian block index. The
+// (key, nonce) pair is unique per block since the DEK is fresh per file and
+// no two blocks in the same file share an index.
+func standardBlockNonce(prefix []byte, blockIndex uint64) []byte {
+	nonce := make([]byte, 12)
+	copy(nonce, prefix)
+	binary.BigEndian.PutUint64(nonce[4:], blockIndex)
+
+	return nonce
+}
+
+// standardOutputFile is an [EncryptedOutputFile] that seals fixed-size
+// plaintext blocks with AES-GCM as they are written.
+type standardOutputFile struct {
+	icebergio.FileWriter
+
+	aead        cipher.AEAD
+	noncePrefix []byte
+	blockSize   int
+	keyID       string
+	wrappedKey  []byte
+
+	buf        []byte
+	blockIndex uint64
+	written    int64
+	closed     bool
+
+	keyMetadata EncryptionKeyMetadata
+}
+
+var _ EncryptedOutputFile = (*standardOutputFile)(nil)
+
+func (f *standardOutputFile) Write(p []byte) (int, error) {
+	total := len(p)
+	for len(p) > 0 {
+		space := f.blockSize - len(f.buf)
+		n := min(space, len(p))
+		f.buf = append(f.buf, p[:n]...)
+		p = p[n:]
+		f.written += int64(n)

Review Comment:
   **Blocking: `Write` over-reports by up to one block.**
   
   `written` advances when bytes are *buffered*, before `flushBlock` succeeds. On a flush failure `Write` returns `total - len(p)`, which counts the block that never made it. I observed `Write` returning `n = 32` when only 16 plaintext bytes had actually reached the underlying writer.
   
   That violates the `io.Writer` contract, which requires `n` to be the number of bytes successfully consumed.
   
   Suggested fix: advance `written` only after a successful flush.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,511 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 {
+		return nil, fmt.Errorf("%w: block-size must be positive, got %d", ErrInvalidKeyMetadata, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}
+	if len(meta.NoncePrefix) != 4 {
+		return nil, fmt.Errorf("%w: nonce-prefix must be 4 bytes, got %d", ErrInvalidKeyMetadata, len(meta.NoncePrefix))
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	return &standardInputFile{
+		underlying:      file,
+		aead:            aead,
+		noncePrefix:     meta.NoncePrefix,
+		blockSize:       meta.BlockSize,
+		plaintextLength: meta.PlaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newStandardAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %v", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// standardBlockNonce derives the AES-GCM nonce for blockIndex: the 4-byte
+// per-file random prefix followed by the 8-byte big-endian block index. The
+// (key, nonce) pair is unique per block since the DEK is fresh per file and
+// no two blocks in the same file share an index.
+func standardBlockNonce(prefix []byte, blockIndex uint64) []byte {
+	nonce := make([]byte, 12)
+	copy(nonce, prefix)
+	binary.BigEndian.PutUint64(nonce[4:], blockIndex)
+
+	return nonce
+}
+
+// standardOutputFile is an [EncryptedOutputFile] that seals fixed-size
+// plaintext blocks with AES-GCM as they are written.
+type standardOutputFile struct {
+	icebergio.FileWriter
+
+	aead        cipher.AEAD
+	noncePrefix []byte
+	blockSize   int
+	keyID       string
+	wrappedKey  []byte
+
+	buf        []byte
+	blockIndex uint64
+	written    int64
+	closed     bool
+
+	keyMetadata EncryptionKeyMetadata
+}
+
+var _ EncryptedOutputFile = (*standardOutputFile)(nil)
+
+func (f *standardOutputFile) Write(p []byte) (int, error) {
+	total := len(p)
+	for len(p) > 0 {
+		space := f.blockSize - len(f.buf)
+		n := min(space, len(p))
+		f.buf = append(f.buf, p[:n]...)
+		p = p[n:]
+		f.written += int64(n)
+		if len(f.buf) == f.blockSize {
+			if err := f.flushBlock(); err != nil {
+				return total - len(p), err
+			}
+		}
+	}
+
+	return total, nil
+}
+
+func (f *standardOutputFile) flushBlock() error {
+	ciphertext := f.aead.Seal(nil, standardBlockNonce(f.noncePrefix, f.blockIndex), f.buf, nil)
+	if _, err := f.FileWriter.Write(ciphertext); err != nil {
+		return fmt.Errorf("encryption: failed to write encrypted block: %w", err)
+	}
+	f.blockIndex++
+	f.buf = f.buf[:0]
+
+	return nil
+}
+
+// ReadFrom copies from r, encrypting as data is written, satisfying
+// io.ReaderFrom (required by [icebergio.FileWriter]).
+func (f *standardOutputFile) ReadFrom(r io.Reader) (int64, error) {
+	buf := make([]byte, 32*1024)
+	var total int64
+	for {
+		n, err := r.Read(buf)
+		if n > 0 {
+			wn, werr := f.Write(buf[:n])
+			total += int64(wn)
+			if werr != nil {
+				return total, werr
+			}
+		}
+		if err == io.EOF {
+			break
+		}
+		if err != nil {
+			return total, err
+		}
+	}
+
+	return total, nil
+}
+
+func (f *standardOutputFile) Close() error {
+	if f.closed {
+		return nil
+	}
+	f.closed = true
+
+	if len(f.buf) > 0 {
+		if err := f.flushBlock(); err != nil {
+			_ = f.FileWriter.Close()
+
+			return err
+		}
+	}
+
+	meta := standardKeyMetadata{
+		Version:         standardKeyMetadataVersion,
+		KeyID:           f.keyID,
+		WrappedKey:      f.wrappedKey,
+		NoncePrefix:     f.noncePrefix,
+		BlockSize:       f.blockSize,
+		PlaintextLength: f.written,
+	}
+	encoded, err := json.Marshal(meta)
+	if err != nil {
+		_ = f.FileWriter.Close()
+
+		return fmt.Errorf("encryption: failed to encode key metadata: %w", err)
+	}
+	f.keyMetadata = encoded
+
+	return f.FileWriter.Close()
+}
+
+// KeyMetadata returns the finalized per-file key metadata. It is only
+// populated after Close has been called.
+func (f *standardOutputFile) KeyMetadata() EncryptionKeyMetadata { return f.keyMetadata }
+
+// standardInputFile is an [EncryptedInputFile] that decrypts fixed-size
+// AES-GCM blocks on demand, supporting random access via ReadAt/Seek.
+type standardInputFile struct {
+	underlying      icebergio.File
+	aead            cipher.AEAD
+	noncePrefix     []byte
+	blockSize       int
+	plaintextLength int64
+	keyMetadata     EncryptionKeyMetadata
+
+	pos int64
+}
+
+var _ EncryptedInputFile = (*standardInputFile)(nil)
+
+func (f *standardInputFile) numBlocks() int64 {
+	if f.plaintextLength == 0 {
+		return 0
+	}
+
+	return (f.plaintextLength + int64(f.blockSize) - 1) / int64(f.blockSize)
+}
+
+func (f *standardInputFile) blockPlainLen(idx int64) int64 {
+	if idx == f.numBlocks()-1 {
+		return f.plaintextLength - idx*int64(f.blockSize)
+	}
+
+	return int64(f.blockSize)
+}
+
+func (f *standardInputFile) physicalOffset(idx int64) int64 {
+	return idx * int64(f.blockSize+f.aead.Overhead())
+}
+
+func (f *standardInputFile) readBlock(idx int64) ([]byte, error) {
+	plainLen := f.blockPlainLen(idx)
+	ciphertext := make([]byte, plainLen+int64(f.aead.Overhead()))
+	if _, err := f.underlying.ReadAt(ciphertext, f.physicalOffset(idx)); err != nil && !errors.Is(err, io.EOF) {
+		return nil, fmt.Errorf("encryption: failed to read block %d: %w", idx, err)
+	}
+
+	plaintext, err := f.aead.Open(nil, standardBlockNonce(f.noncePrefix, uint64(idx)), ciphertext, nil)

Review Comment:
   Matching `nil` AAD on the decrypt side (see the note on line 310).
   
   Related: trailing garbage appended past the final block is currently accepted silently, because nothing binds the file's total length into what gets authenticated.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,511 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 {
+		return nil, fmt.Errorf("%w: block-size must be positive, got %d", ErrInvalidKeyMetadata, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}
+	if len(meta.NoncePrefix) != 4 {
+		return nil, fmt.Errorf("%w: nonce-prefix must be 4 bytes, got %d", ErrInvalidKeyMetadata, len(meta.NoncePrefix))
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	return &standardInputFile{
+		underlying:      file,
+		aead:            aead,
+		noncePrefix:     meta.NoncePrefix,
+		blockSize:       meta.BlockSize,
+		plaintextLength: meta.PlaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newStandardAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %v", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// standardBlockNonce derives the AES-GCM nonce for blockIndex: the 4-byte
+// per-file random prefix followed by the 8-byte big-endian block index. The
+// (key, nonce) pair is unique per block since the DEK is fresh per file and
+// no two blocks in the same file share an index.
+func standardBlockNonce(prefix []byte, blockIndex uint64) []byte {
+	nonce := make([]byte, 12)
+	copy(nonce, prefix)
+	binary.BigEndian.PutUint64(nonce[4:], blockIndex)
+
+	return nonce
+}
+
+// standardOutputFile is an [EncryptedOutputFile] that seals fixed-size
+// plaintext blocks with AES-GCM as they are written.
+type standardOutputFile struct {
+	icebergio.FileWriter
+
+	aead        cipher.AEAD
+	noncePrefix []byte
+	blockSize   int
+	keyID       string
+	wrappedKey  []byte
+
+	buf        []byte
+	blockIndex uint64
+	written    int64
+	closed     bool
+
+	keyMetadata EncryptionKeyMetadata
+}
+
+var _ EncryptedOutputFile = (*standardOutputFile)(nil)
+
+func (f *standardOutputFile) Write(p []byte) (int, error) {
+	total := len(p)
+	for len(p) > 0 {
+		space := f.blockSize - len(f.buf)
+		n := min(space, len(p))
+		f.buf = append(f.buf, p[:n]...)
+		p = p[n:]
+		f.written += int64(n)
+		if len(f.buf) == f.blockSize {
+			if err := f.flushBlock(); err != nil {
+				return total - len(p), err
+			}
+		}
+	}
+
+	return total, nil
+}
+
+func (f *standardOutputFile) flushBlock() error {
+	ciphertext := f.aead.Seal(nil, standardBlockNonce(f.noncePrefix, f.blockIndex), f.buf, nil)
+	if _, err := f.FileWriter.Write(ciphertext); err != nil {
+		return fmt.Errorf("encryption: failed to write encrypted block: %w", err)
+	}
+	f.blockIndex++
+	f.buf = f.buf[:0]
+
+	return nil
+}
+
+// ReadFrom copies from r, encrypting as data is written, satisfying
+// io.ReaderFrom (required by [icebergio.FileWriter]).
+func (f *standardOutputFile) ReadFrom(r io.Reader) (int64, error) {
+	buf := make([]byte, 32*1024)
+	var total int64
+	for {
+		n, err := r.Read(buf)
+		if n > 0 {
+			wn, werr := f.Write(buf[:n])
+			total += int64(wn)
+			if werr != nil {
+				return total, werr
+			}
+		}
+		if err == io.EOF {
+			break
+		}
+		if err != nil {
+			return total, err
+		}
+	}
+
+	return total, nil
+}
+
+func (f *standardOutputFile) Close() error {
+	if f.closed {
+		return nil
+	}
+	f.closed = true
+
+	if len(f.buf) > 0 {
+		if err := f.flushBlock(); err != nil {
+			_ = f.FileWriter.Close()
+
+			return err
+		}
+	}
+
+	meta := standardKeyMetadata{
+		Version:         standardKeyMetadataVersion,
+		KeyID:           f.keyID,
+		WrappedKey:      f.wrappedKey,
+		NoncePrefix:     f.noncePrefix,
+		BlockSize:       f.blockSize,
+		PlaintextLength: f.written,
+	}
+	encoded, err := json.Marshal(meta)
+	if err != nil {
+		_ = f.FileWriter.Close()
+
+		return fmt.Errorf("encryption: failed to encode key metadata: %w", err)
+	}
+	f.keyMetadata = encoded
+
+	return f.FileWriter.Close()
+}
+
+// KeyMetadata returns the finalized per-file key metadata. It is only
+// populated after Close has been called.
+func (f *standardOutputFile) KeyMetadata() EncryptionKeyMetadata { return f.keyMetadata }
+
+// standardInputFile is an [EncryptedInputFile] that decrypts fixed-size
+// AES-GCM blocks on demand, supporting random access via ReadAt/Seek.
+type standardInputFile struct {
+	underlying      icebergio.File
+	aead            cipher.AEAD
+	noncePrefix     []byte
+	blockSize       int
+	plaintextLength int64
+	keyMetadata     EncryptionKeyMetadata
+
+	pos int64
+}
+
+var _ EncryptedInputFile = (*standardInputFile)(nil)
+
+func (f *standardInputFile) numBlocks() int64 {

Review Comment:
   **Blocking: unguarded overflow on attacker-controlled values.**
   
   `f.plaintextLength + int64(f.blockSize) - 1` has no overflow check, and both operands come from key metadata that `NewDecryptedInputFile` only checks for `> 0` / `>= 0` (line 215). With `block-size = MaxInt64` this wraps negative, `numBlocks()` returns 0, and `blockPlainLen` then falls through to `return int64(f.blockSize)` — which panics in `readBlock` with `makeslice: len out of range`.
   
   Suggested fix: use overflow-safe arithmetic here, and cross-check `plaintextLength` against the underlying file's `Stat().Size()` at construction.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,511 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 {
+		return nil, fmt.Errorf("%w: block-size must be positive, got %d", ErrInvalidKeyMetadata, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}
+	if len(meta.NoncePrefix) != 4 {
+		return nil, fmt.Errorf("%w: nonce-prefix must be 4 bytes, got %d", ErrInvalidKeyMetadata, len(meta.NoncePrefix))
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	return &standardInputFile{
+		underlying:      file,
+		aead:            aead,
+		noncePrefix:     meta.NoncePrefix,
+		blockSize:       meta.BlockSize,
+		plaintextLength: meta.PlaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newStandardAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %v", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// standardBlockNonce derives the AES-GCM nonce for blockIndex: the 4-byte
+// per-file random prefix followed by the 8-byte big-endian block index. The
+// (key, nonce) pair is unique per block since the DEK is fresh per file and
+// no two blocks in the same file share an index.
+func standardBlockNonce(prefix []byte, blockIndex uint64) []byte {

Review Comment:
   Not blocking, but worth hardening.
   
   The 4-byte random per-file prefix concatenated with the 8-byte block index is unique only under the invariant that every file gets a fresh DEK. That invariant is real today but neither enforced nor documented, and it's exactly what a future key-cache or rotation-interval optimization would break — Java caches unwrapped keys, for reference.
   
   The consequence is unusually severe for GCM: nonce reuse leaks the plaintext XOR *and* the GHASH authentication key. With only 4 random bytes, roughly 2^16 files sharing a DEK gives ~50% collision odds.
   
   Adopting the spec's per-block stored 12-byte RBG nonce would remove the invariant entirely. Short of that, widening the prefix and documenting the fresh-DEK requirement at the type would help.
   
   (`crypto/rand` is used correctly throughout, return values are checked, and I confirmed 16 concurrent `ReadAt` calls are race-clean under `-race`.)



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,511 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 {

Review Comment:
   These two checks are the only validation applied to attacker-controlled key metadata, and `> 0` / `>= 0` isn't enough — both values remain free up to `MaxInt64`, which drives the overflow at line 397 and the allocation at line 419.
   
   Suggested additions here: an upper bound on `BlockSize`, and a cross-check of `PlaintextLength` against the underlying file size.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,511 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 {
+		return nil, fmt.Errorf("%w: block-size must be positive, got %d", ErrInvalidKeyMetadata, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}
+	if len(meta.NoncePrefix) != 4 {
+		return nil, fmt.Errorf("%w: nonce-prefix must be 4 bytes, got %d", ErrInvalidKeyMetadata, len(meta.NoncePrefix))
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	return &standardInputFile{
+		underlying:      file,
+		aead:            aead,
+		noncePrefix:     meta.NoncePrefix,
+		blockSize:       meta.BlockSize,
+		plaintextLength: meta.PlaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newStandardAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %v", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// standardBlockNonce derives the AES-GCM nonce for blockIndex: the 4-byte
+// per-file random prefix followed by the 8-byte big-endian block index. The
+// (key, nonce) pair is unique per block since the DEK is fresh per file and
+// no two blocks in the same file share an index.
+func standardBlockNonce(prefix []byte, blockIndex uint64) []byte {
+	nonce := make([]byte, 12)
+	copy(nonce, prefix)
+	binary.BigEndian.PutUint64(nonce[4:], blockIndex)
+
+	return nonce
+}
+
+// standardOutputFile is an [EncryptedOutputFile] that seals fixed-size
+// plaintext blocks with AES-GCM as they are written.
+type standardOutputFile struct {
+	icebergio.FileWriter
+
+	aead        cipher.AEAD
+	noncePrefix []byte
+	blockSize   int
+	keyID       string
+	wrappedKey  []byte
+
+	buf        []byte
+	blockIndex uint64
+	written    int64
+	closed     bool
+
+	keyMetadata EncryptionKeyMetadata
+}
+
+var _ EncryptedOutputFile = (*standardOutputFile)(nil)
+
+func (f *standardOutputFile) Write(p []byte) (int, error) {
+	total := len(p)
+	for len(p) > 0 {
+		space := f.blockSize - len(f.buf)
+		n := min(space, len(p))
+		f.buf = append(f.buf, p[:n]...)
+		p = p[n:]
+		f.written += int64(n)
+		if len(f.buf) == f.blockSize {
+			if err := f.flushBlock(); err != nil {
+				return total - len(p), err
+			}
+		}
+	}
+
+	return total, nil
+}
+
+func (f *standardOutputFile) flushBlock() error {
+	ciphertext := f.aead.Seal(nil, standardBlockNonce(f.noncePrefix, f.blockIndex), f.buf, nil)
+	if _, err := f.FileWriter.Write(ciphertext); err != nil {
+		return fmt.Errorf("encryption: failed to write encrypted block: %w", err)
+	}
+	f.blockIndex++
+	f.buf = f.buf[:0]
+
+	return nil
+}
+
+// ReadFrom copies from r, encrypting as data is written, satisfying
+// io.ReaderFrom (required by [icebergio.FileWriter]).
+func (f *standardOutputFile) ReadFrom(r io.Reader) (int64, error) {
+	buf := make([]byte, 32*1024)
+	var total int64
+	for {
+		n, err := r.Read(buf)
+		if n > 0 {
+			wn, werr := f.Write(buf[:n])
+			total += int64(wn)
+			if werr != nil {
+				return total, werr
+			}
+		}
+		if err == io.EOF {
+			break
+		}
+		if err != nil {
+			return total, err
+		}
+	}
+
+	return total, nil
+}
+
+func (f *standardOutputFile) Close() error {
+	if f.closed {
+		return nil
+	}
+	f.closed = true
+
+	if len(f.buf) > 0 {
+		if err := f.flushBlock(); err != nil {
+			_ = f.FileWriter.Close()
+
+			return err
+		}
+	}
+
+	meta := standardKeyMetadata{
+		Version:         standardKeyMetadataVersion,
+		KeyID:           f.keyID,
+		WrappedKey:      f.wrappedKey,
+		NoncePrefix:     f.noncePrefix,
+		BlockSize:       f.blockSize,
+		PlaintextLength: f.written,
+	}
+	encoded, err := json.Marshal(meta)
+	if err != nil {
+		_ = f.FileWriter.Close()
+
+		return fmt.Errorf("encryption: failed to encode key metadata: %w", err)
+	}
+	f.keyMetadata = encoded
+
+	return f.FileWriter.Close()
+}
+
+// KeyMetadata returns the finalized per-file key metadata. It is only
+// populated after Close has been called.
+func (f *standardOutputFile) KeyMetadata() EncryptionKeyMetadata { return f.keyMetadata }
+
+// standardInputFile is an [EncryptedInputFile] that decrypts fixed-size
+// AES-GCM blocks on demand, supporting random access via ReadAt/Seek.
+type standardInputFile struct {
+	underlying      icebergio.File
+	aead            cipher.AEAD
+	noncePrefix     []byte
+	blockSize       int
+	plaintextLength int64
+	keyMetadata     EncryptionKeyMetadata
+
+	pos int64
+}
+
+var _ EncryptedInputFile = (*standardInputFile)(nil)
+
+func (f *standardInputFile) numBlocks() int64 {
+	if f.plaintextLength == 0 {
+		return 0
+	}
+
+	return (f.plaintextLength + int64(f.blockSize) - 1) / int64(f.blockSize)
+}
+
+func (f *standardInputFile) blockPlainLen(idx int64) int64 {
+	if idx == f.numBlocks()-1 {
+		return f.plaintextLength - idx*int64(f.blockSize)
+	}
+
+	return int64(f.blockSize)
+}
+
+func (f *standardInputFile) physicalOffset(idx int64) int64 {
+	return idx * int64(f.blockSize+f.aead.Overhead())
+}
+
+func (f *standardInputFile) readBlock(idx int64) ([]byte, error) {
+	plainLen := f.blockPlainLen(idx)
+	ciphertext := make([]byte, plainLen+int64(f.aead.Overhead()))

Review Comment:
   **Blocking: unbounded allocation from untrusted metadata — takes the process down.**
   
   `plainLen` derives from the attacker-controlled `block-size` / `plaintext-length`, so this `make` is effectively unbounded. With `block-size = plaintext-length = 2^40` I got `fatal error: runtime: out of memory`, which is an unrecoverable runtime throw — not a panic a caller can recover from. One malicious manifest entry kills the process.
   
   Suggested fix: cap `BlockSize` at something sane (64 MiB would be generous) during metadata validation.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,511 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {

Review Comment:
   `WithDEKLength` and `WithBlockSize` accept invalid values silently — errors only surface later at `NewEncryptedOutputFile`, and for `dekLength = 0` only after a wasted KMS round trip.
   
   Validating at construction would fail faster and closer to the mistake.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat(encryption): add GoEnvelopeEncryptionManager for generic file envelope encryption [iceberg-go]

Posted by "zeroshade (via GitHub)" <gi...@apache.org>.
zeroshade commented on code in PR #1620:
URL: https://github.com/apache/iceberg-go/pull/1620#discussion_r4065518558


##########
encryption/go_envelope_manager.go:
##########
@@ -0,0 +1,883 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+	"math"
+	"sync"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [GoEnvelopeEncryptionManager].
+const (
+	// GoEnvelopeDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	GoEnvelopeDefaultDEKLength = 32
+
+	// GoEnvelopeDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	//
+	// This is not Java's Ciphers.PLAIN_BLOCK_SIZE (1 MiB, a compile-time
+	// constant there); see the [GoEnvelopeEncryptionManager] doc comment.
+	GoEnvelopeDefaultBlockSize = 64 * 1024
+
+	// GoEnvelopeMaxBlockSize is the largest plaintext block size accepted
+	// from the AES GCM Stream header on read, and the largest that
+	// [WithBlockSize] will configure for writing. The header's block-length
+	// field is unauthenticated, untrusted data (the Iceberg AES GCM Stream
+	// spec's "File length" note applies equally here); without a ceiling, a
+	// crafted header claiming e.g. 1<<40 bytes would force a huge
+	// allocation (see readBlock) before any authentication check can run.
+	GoEnvelopeMaxBlockSize = 128 * 1024 * 1024
+)
+
+// Sentinel errors returned by [GoEnvelopeEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile] when keyID is
+	// empty. GoEnvelopeEncryptionManager always encrypts, so it requires a
+	// KEK to wrap the generated DEK; use [PlaintextEncryptionManager] for
+	// unencrypted tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when keyMetadata
+	// is empty. GoEnvelopeEncryptionManager always decrypts, so it requires
+	// the per-file key metadata produced by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured block size is not
+	// positive or exceeds [GoEnvelopeMaxBlockSize].
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive and at most GoEnvelopeMaxBlockSize")
+
+	// ErrInvalidStreamHeader is returned when the AES GCM Stream header
+	// (the "AGS1" magic and little-endian block-length fields at the start
+	// of an encrypted file, per the Iceberg AES GCM Stream spec) is
+	// missing, truncated, or specifies a block length outside the
+	// supported range.
+	ErrInvalidStreamHeader = errors.New("encryption: invalid AES GCM Stream header")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a missing AAD prefix). Key metadata is untrusted input on a crypto
+	// read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+
+	// ErrOutputFileClosed is returned by [goEnvelopeOutputFile.Write] when
+	// called after Close, or after a previous flush has poisoned the writer.
+	// It wraps [fs.ErrClosed] so callers can test with errors.Is(err, fs.ErrClosed).
+	ErrOutputFileClosed = fmt.Errorf("encryption: write to closed GoEnvelopeEncryptionManager output file: %w", fs.ErrClosed)
+
+	// ErrBlockTruncated is returned by [goEnvelopeInputFile.ReadAt] when the
+	// underlying storage returns fewer ciphertext bytes for a block than its
+	// recorded length requires, indicating the file was truncated at rest.
+	// This is distinct from [ErrCiphertextTooShort], which [KeyManagementClient]
+	// implementations use for a too-short wrapped key or KMS-encrypted
+	// payload; keeping them separate lets a caller tell a malformed KMS blob
+	// apart from a short block read.
+	ErrBlockTruncated = errors.New("encryption: block truncated: read fewer ciphertext bytes than expected")
+)
+
+// Constants describing the Iceberg AES GCM Stream ("AGS1") wire format used
+// for the ciphertext produced by [GoEnvelopeEncryptionManager]. See
+// https://iceberg.apache.org/gcm-stream-spec/ for the full specification.
+const (
+	// gcmStreamMagic identifies an AES GCM Stream version 1 file.
+	gcmStreamMagic = "AGS1"
+
+	// gcmStreamHeaderLength is the length, in bytes, of the magic plus the
+	// little-endian block-length field written at the start of every file.
+	gcmStreamHeaderLength = len(gcmStreamMagic) + 4
+
+	// gcmStreamNonceLength is the length, in bytes, of the random AES-GCM
+	// nonce stored at the start of every cipher block.
+	gcmStreamNonceLength = 12
+
+	// gcmStreamTagLength is the length, in bytes, of the AES-GCM
+	// authentication tag appended to every cipher block's ciphertext.
+	gcmStreamTagLength = 16
+
+	// gcmStreamBlockOverhead is the number of ciphertext bytes added to
+	// each block beyond its plaintext length (nonce + tag).
+	gcmStreamBlockOverhead = gcmStreamNonceLength + gcmStreamTagLength
+
+	// gcmStreamAADPrefixLength is the length, in bytes, of the random
+	// per-file AAD prefix generated for new output files.
+	gcmStreamAADPrefixLength = 16
+)
+
+// goEnvelopeKeyMetadataVersion is the current encoding version written by
+// [GoEnvelopeEncryptionManager]. It is bumped whenever the on-disk layout of
+// goEnvelopeKeyMetadata changes incompatibly.
+const goEnvelopeKeyMetadataVersion = 1
+
+// goEnvelopeKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [GoEnvelopeEncryptionManager].
+//
+// This encoding is Go-specific, not Java's Avro-encoded StandardKeyMetadata;
+// see the [GoEnvelopeEncryptionManager] doc comment. Per the table spec,
+// DataFile/ManifestFile key_metadata is explicitly "implementation-specific";
+// what must be Iceberg AES GCM Stream compliant - and is - is the wire
+// format of the encrypted byte stream itself (magic, block framing, nonce
+// placement, and AAD; see the constants above).
+type goEnvelopeKeyMetadata struct {
+	Version    int    `json:"v"`
+	KeyID      string `json:"key-id"`
+	WrappedKey []byte `json:"wrapped-key"`
+
+	// BlockSize is the trusted plaintext block size the file was written
+	// with. It is validated bounded before any file I/O, and is what's
+	// actually used to size reads; the stream header's block-length field
+	// is untrusted (unauthenticated, attacker-influenced storage bytes) and
+	// is only compared against this value, never used directly to size an
+	// allocation.
+	BlockSize int64 `json:"block-size"`
+
+	// AADPrefix is combined with each block's little-endian index to form
+	// the AES GCM Stream additional authenticated data, binding every
+	// ciphertext block to this file and to its position so that blocks
+	// cannot be silently reordered, replayed from another file, or spliced
+	// in from elsewhere in the same file. It is not secret.
+	AADPrefix []byte `json:"aad-prefix"`
+
+	// PlaintextLength is the trusted total plaintext size used to compute
+	// the block count on read. Per the AES GCM Stream spec's "File length"
+	// note, a reader must use a length from a trusted source rather than
+	// the underlying storage's reported size, since storage size alone
+	// cannot distinguish a genuinely short file from one truncated by an
+	// attacker who does not also control this metadata.
+	PlaintextLength int64 `json:"plaintext-length"`
+}
+
+// GoEnvelopeEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks and written using the
+// Iceberg AES GCM Stream ("AGS1") format: a magic/block-length header
+// followed by independently authenticated blocks, each carrying its own
+// random nonce and authenticated with an AAD that binds it to the file and
+// to its position. This bounds memory usage and supports random access
+// (Seek/ReadAt) on the decrypted file without buffering or decrypting more
+// than the requested blocks.
+//
+// GoEnvelopeEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+//
+// Not interoperable with Java's StandardEncryptionManager: the AGS1 byte
+// stream framing (magic, block layout, nonce placement, AAD) matches the
+// spec, but the two implementations are not cross-readable. Java's reader
+// hard-requires a 1 MiB header block size (a compile-time constant there),
+// while [GoEnvelopeDefaultBlockSize] is 64 KiB, and Java decodes key
+// metadata as a 1-byte version plus Avro-encoded StandardKeyMetadata, while
+// this type encodes key metadata as JSON (goEnvelopeKeyMetadata). Files
+// written by one are not readable by the other.
+type GoEnvelopeEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*GoEnvelopeEncryptionManager)(nil)
+
+// GoEnvelopeManagerOption configures a [GoEnvelopeEncryptionManager] created
+// by [NewGoEnvelopeEncryptionManager].
+type GoEnvelopeManagerOption func(*GoEnvelopeEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) GoEnvelopeManagerOption {
+	return func(m *GoEnvelopeEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication. size must be
+// positive and at most [GoEnvelopeMaxBlockSize].
+func WithBlockSize(size int) GoEnvelopeManagerOption {
+	return func(m *GoEnvelopeEncryptionManager) { m.blockSize = size }
+}
+
+// NewGoEnvelopeEncryptionManager creates a [GoEnvelopeEncryptionManager]
+// backed by kms. kms must not be nil; NewGoEnvelopeEncryptionManager panics
+// if it is.
+func NewGoEnvelopeEncryptionManager(kms KeyManagementClient, opts ...GoEnvelopeManagerOption) *GoEnvelopeEncryptionManager {
+	if kms == nil {
+		panic("encryption: NewGoEnvelopeEncryptionManager: kms must not be nil")
+	}
+
+	m := &GoEnvelopeEncryptionManager{
+		kms:       kms,
+		dekLength: GoEnvelopeDefaultDEKLength,
+		blockSize: GoEnvelopeDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *GoEnvelopeEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 || m.blockSize > GoEnvelopeMaxBlockSize {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+	switch m.dekLength {
+	case 16, 24, 32:
+	default:
+		return nil, fmt.Errorf("%w: DEK length must be 16, 24, or 32 bytes; got %d", ErrInvalidKeyLength, m.dekLength)
+	}
+
+	// The (key, nonce) uniqueness this block format relies on requires a
+	// freshly generated DEK for every file: never cache or reuse
+	// plainDEK/wrappedDEK across calls to NewEncryptedOutputFile.
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = io.ReadFull(rand.Reader, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newGoEnvelopeAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	aadPrefix := make([]byte, gcmStreamAADPrefixLength)
+	if _, err := io.ReadFull(rand.Reader, aadPrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate AAD prefix: %w", err)
+	}
+
+	// Write the AES GCM Stream header (magic + little-endian block length)
+	// up front, before any ciphertext blocks, per the format spec.
+	header := make([]byte, gcmStreamHeaderLength)
+	copy(header, gcmStreamMagic)
+	binary.LittleEndian.PutUint32(header[len(gcmStreamMagic):], uint32(m.blockSize)) //nolint:gosec // bounded by ErrInvalidBlockSize above
+	if _, err := writer.Write(header); err != nil {
+		return nil, fmt.Errorf("encryption: failed to write stream header: %w", err)
+	}
+
+	return &goEnvelopeOutputFile{
+		FileWriter: writer,
+		aead:       aead,
+		aadPrefix:  aadPrefix,
+		blockSize:  m.blockSize,
+		keyID:      keyID,
+		wrappedKey: wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *GoEnvelopeEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta goEnvelopeKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != goEnvelopeKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 || meta.BlockSize > GoEnvelopeMaxBlockSize {
+		return nil, fmt.Errorf("%w: block-size must be positive and at most %d, got %d", ErrInvalidKeyMetadata, GoEnvelopeMaxBlockSize, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}
+	if len(meta.AADPrefix) == 0 {
+		return nil, fmt.Errorf("%w: aad-prefix must not be empty", ErrInvalidKeyMetadata)
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newGoEnvelopeAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	// headerBlockSize is untrusted (unauthenticated bytes read from
+	// storage): it is only ever compared against the trusted, already
+	// bounded meta.BlockSize below, never used to size a read or allocation.
+	headerBlockSize, err := readGCMStreamHeader(file)
+	if err != nil {
+		return nil, err
+	}
+	if headerBlockSize != meta.BlockSize {
+		return nil, fmt.Errorf("%w: stream header block length %d does not match key metadata block-size %d", ErrInvalidStreamHeader, headerBlockSize, meta.BlockSize)
+	}
+
+	return &goEnvelopeInputFile{
+		underlying:      file,
+		aead:            aead,
+		aadPrefix:       meta.AADPrefix,
+		blockSize:       meta.BlockSize,
+		plaintextLength: meta.PlaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newGoEnvelopeAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %w", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// readGCMStreamHeader reads and validates the AES GCM Stream magic and
+// block-length header at the start of file, returning the plaintext block
+// length. The header is untrusted, unauthenticated data, so the returned
+// length is bounded to [GoEnvelopeMaxBlockSize] before any allocation sized
+// by it takes place.
+func readGCMStreamHeader(file icebergio.File) (int64, error) {
+	header := make([]byte, gcmStreamHeaderLength)
+	n, err := file.ReadAt(header, 0)
+	if err != nil && !errors.Is(err, io.EOF) {
+		return 0, fmt.Errorf("encryption: failed to read stream header: %w", err)
+	}
+	if n != gcmStreamHeaderLength {
+		return 0, fmt.Errorf("%w: expected %d header bytes, got %d", ErrInvalidStreamHeader, gcmStreamHeaderLength, n)
+	}
+	if string(header[:len(gcmStreamMagic)]) != gcmStreamMagic {
+		return 0, fmt.Errorf("%w: missing %q magic", ErrInvalidStreamHeader, gcmStreamMagic)
+	}
+
+	blockSize := int64(binary.LittleEndian.Uint32(header[len(gcmStreamMagic):]))
+	if blockSize <= 0 || blockSize > GoEnvelopeMaxBlockSize {
+		return 0, fmt.Errorf("%w: block length %d out of supported range (0, %d]", ErrInvalidStreamHeader, blockSize, GoEnvelopeMaxBlockSize)
+	}
+
+	return blockSize, nil
+}
+
+// gcmStreamBlockAAD derives the AES-GCM additional authenticated data for
+// blockIndex: the per-file AAD prefix followed by the 4-byte little-endian
+// block index, per the Iceberg AES GCM Stream spec. This binds every
+// ciphertext block to this file and to its position, which matters because
+// blocks carry independent random nonces (rather than a nonce derived from
+// the block index): without the index in the AAD, an attacker able to
+// tamper with ciphertext at rest could silently reorder or splice blocks.
+func gcmStreamBlockAAD(prefix []byte, blockIndex uint32) []byte {
+	aad := make([]byte, len(prefix)+4)
+	copy(aad, prefix)
+	binary.LittleEndian.PutUint32(aad[len(prefix):], blockIndex)
+
+	return aad
+}
+
+// checkedMulInt64 returns a*b and true, or (0, false) if the multiplication
+// overflows int64.
+func checkedMulInt64(a, b int64) (int64, bool) {
+	if a == 0 || b == 0 {
+		return 0, true
+	}
+	result := a * b
+	if result/b != a {
+		return 0, false
+	}
+
+	return result, true
+}
+
+// checkedAddInt64 returns a+b and true, or (0, false) if the addition
+// overflows int64.
+func checkedAddInt64(a, b int64) (int64, bool) {
+	result := a + b
+	if (b > 0 && result < a) || (b < 0 && result > a) {
+		return 0, false
+	}
+
+	return result, true
+}
+
+// goEnvelopeOutputFile is an [EncryptedOutputFile] that seals fixed-size
+// plaintext blocks with AES-GCM as they are written, using the Iceberg AES
+// GCM Stream ("AGS1") wire format.
+type goEnvelopeOutputFile struct {
+	icebergio.FileWriter
+
+	aead       cipher.AEAD
+	aadPrefix  []byte
+	blockSize  int
+	keyID      string
+	wrappedKey []byte
+
+	buf        []byte
+	blockIndex uint32
+	written    int64
+	closed     bool
+	err        error
+
+	// underlyingClosed tracks whether FileWriter.Close has already been
+	// attempted, so a poisoned writer is closed exactly once regardless of
+	// whether the failure is first observed in Write or in Close.
+	underlyingClosed bool
+
+	keyMetadata EncryptionKeyMetadata
+}
+
+var _ EncryptedOutputFile = (*goEnvelopeOutputFile)(nil)
+
+// closeUnderlyingIgnoringError closes the underlying writer at most once.
+// The error is ignored: the caller is already reporting a more specific
+// failure (a flush or encode error), and this is best-effort cleanup so a
+// poisoned writer never leaks its underlying file descriptor or connection.
+//
+// defensive: today every call site sets f.err before calling this, and
+// Write/Close both bail out early once f.err is set, so the
+// underlyingClosed guard never actually stops a second Close in practice.
+// It stays as a hard invariant in case a future call site is added that
+// doesn't follow that pattern.
+func (f *goEnvelopeOutputFile) closeUnderlyingIgnoringError() {
+	if f.underlyingClosed {
+		return
+	}
+	f.underlyingClosed = true
+	_ = f.FileWriter.Close()
+}
+
+func (f *goEnvelopeOutputFile) Write(p []byte) (int, error) {
+	if f.err != nil {
+		return 0, f.err
+	}
+	if f.closed {
+		return 0, ErrOutputFileClosed
+	}
+
+	total := len(p)
+	consumed := 0 // bytes of p appended into f.buf so far in this call
+	accepted := 0 // bytes of p known to be durably flushed; reported on failure
+	for len(p) > 0 {
+		space := f.blockSize - len(f.buf)
+		n := min(space, len(p))
+		f.buf = append(f.buf, p[:n]...)
+		p = p[n:]
+		consumed += n
+		if len(f.buf) == f.blockSize {
+			if err := f.flushBlock(); err != nil {
+				f.err = err
+				f.closeUnderlyingIgnoringError()
+
+				return accepted, err
+			}
+			accepted = consumed
+		}
+	}
+
+	return total, nil
+}
+
+// flushBlock seals and writes the currently buffered plaintext block using a
+// fresh random nonce, per the Iceberg AES GCM Stream format. f.written is
+// only advanced once the ciphertext has actually reached the underlying
+// writer, so a failed flush never overcounts PlaintextLength.
+func (f *goEnvelopeOutputFile) flushBlock() error {
+	if f.blockIndex == math.MaxUint32 {
+		return errors.New("encryption: cannot write block: exceeded maximum block count")
+	}
+
+	nonce := make([]byte, gcmStreamNonceLength)

Review Comment:
   The 09-08 blocker — per-block nonce uniqueness is pinned by no test — is still open.
   
   Your reply on this line says `TestGoEnvelopeEncryptionManager_BlockNoncesAreUnique` was added and "mutation-verified against a constant-nonce regression". That symbol does not exist anywhere in the branch, and the 597-line test file contains no nonce assertion: only comments at `:137` and `:156-157` and a size check at `:507`.
   
   I mutation-checked this head directly. Replacing `io.ReadFull(rand.Reader, nonce)` at `:547` with a constant all-zero nonce leaves `go test ./encryption/... -count=1` fully green.
   
   Nonce reuse under a fixed key is GCM's catastrophic failure mode — it leaks the XOR of the affected plaintexts and enables forgery — and it is precisely what the existing round-trip, tamper, and reorder tests cannot detect.
   
   Please add the test: parse each inline 12-byte nonce at offset `8 + i*(blockSize+28)` across a multi-block repeated-plaintext payload, assert pairwise distinctness, and confirm the constant-nonce mutation fails it.



##########
encryption/go_envelope_manager.go:
##########
@@ -0,0 +1,883 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+	"math"
+	"sync"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [GoEnvelopeEncryptionManager].
+const (
+	// GoEnvelopeDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	GoEnvelopeDefaultDEKLength = 32
+
+	// GoEnvelopeDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	//
+	// This is not Java's Ciphers.PLAIN_BLOCK_SIZE (1 MiB, a compile-time
+	// constant there); see the [GoEnvelopeEncryptionManager] doc comment.
+	GoEnvelopeDefaultBlockSize = 64 * 1024
+
+	// GoEnvelopeMaxBlockSize is the largest plaintext block size accepted
+	// from the AES GCM Stream header on read, and the largest that
+	// [WithBlockSize] will configure for writing. The header's block-length
+	// field is unauthenticated, untrusted data (the Iceberg AES GCM Stream
+	// spec's "File length" note applies equally here); without a ceiling, a
+	// crafted header claiming e.g. 1<<40 bytes would force a huge
+	// allocation (see readBlock) before any authentication check can run.
+	GoEnvelopeMaxBlockSize = 128 * 1024 * 1024
+)
+
+// Sentinel errors returned by [GoEnvelopeEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile] when keyID is
+	// empty. GoEnvelopeEncryptionManager always encrypts, so it requires a
+	// KEK to wrap the generated DEK; use [PlaintextEncryptionManager] for
+	// unencrypted tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when keyMetadata
+	// is empty. GoEnvelopeEncryptionManager always decrypts, so it requires
+	// the per-file key metadata produced by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured block size is not
+	// positive or exceeds [GoEnvelopeMaxBlockSize].
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive and at most GoEnvelopeMaxBlockSize")
+
+	// ErrInvalidStreamHeader is returned when the AES GCM Stream header
+	// (the "AGS1" magic and little-endian block-length fields at the start
+	// of an encrypted file, per the Iceberg AES GCM Stream spec) is
+	// missing, truncated, or specifies a block length outside the
+	// supported range.
+	ErrInvalidStreamHeader = errors.New("encryption: invalid AES GCM Stream header")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a missing AAD prefix). Key metadata is untrusted input on a crypto
+	// read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+
+	// ErrOutputFileClosed is returned by [goEnvelopeOutputFile.Write] when
+	// called after Close, or after a previous flush has poisoned the writer.
+	// It wraps [fs.ErrClosed] so callers can test with errors.Is(err, fs.ErrClosed).
+	ErrOutputFileClosed = fmt.Errorf("encryption: write to closed GoEnvelopeEncryptionManager output file: %w", fs.ErrClosed)
+
+	// ErrBlockTruncated is returned by [goEnvelopeInputFile.ReadAt] when the
+	// underlying storage returns fewer ciphertext bytes for a block than its
+	// recorded length requires, indicating the file was truncated at rest.
+	// This is distinct from [ErrCiphertextTooShort], which [KeyManagementClient]
+	// implementations use for a too-short wrapped key or KMS-encrypted
+	// payload; keeping them separate lets a caller tell a malformed KMS blob
+	// apart from a short block read.
+	ErrBlockTruncated = errors.New("encryption: block truncated: read fewer ciphertext bytes than expected")
+)
+
+// Constants describing the Iceberg AES GCM Stream ("AGS1") wire format used
+// for the ciphertext produced by [GoEnvelopeEncryptionManager]. See
+// https://iceberg.apache.org/gcm-stream-spec/ for the full specification.
+const (
+	// gcmStreamMagic identifies an AES GCM Stream version 1 file.
+	gcmStreamMagic = "AGS1"
+
+	// gcmStreamHeaderLength is the length, in bytes, of the magic plus the
+	// little-endian block-length field written at the start of every file.
+	gcmStreamHeaderLength = len(gcmStreamMagic) + 4
+
+	// gcmStreamNonceLength is the length, in bytes, of the random AES-GCM
+	// nonce stored at the start of every cipher block.
+	gcmStreamNonceLength = 12
+
+	// gcmStreamTagLength is the length, in bytes, of the AES-GCM
+	// authentication tag appended to every cipher block's ciphertext.
+	gcmStreamTagLength = 16
+
+	// gcmStreamBlockOverhead is the number of ciphertext bytes added to
+	// each block beyond its plaintext length (nonce + tag).
+	gcmStreamBlockOverhead = gcmStreamNonceLength + gcmStreamTagLength
+
+	// gcmStreamAADPrefixLength is the length, in bytes, of the random
+	// per-file AAD prefix generated for new output files.
+	gcmStreamAADPrefixLength = 16
+)
+
+// goEnvelopeKeyMetadataVersion is the current encoding version written by
+// [GoEnvelopeEncryptionManager]. It is bumped whenever the on-disk layout of
+// goEnvelopeKeyMetadata changes incompatibly.
+const goEnvelopeKeyMetadataVersion = 1
+
+// goEnvelopeKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [GoEnvelopeEncryptionManager].
+//
+// This encoding is Go-specific, not Java's Avro-encoded StandardKeyMetadata;
+// see the [GoEnvelopeEncryptionManager] doc comment. Per the table spec,
+// DataFile/ManifestFile key_metadata is explicitly "implementation-specific";
+// what must be Iceberg AES GCM Stream compliant - and is - is the wire
+// format of the encrypted byte stream itself (magic, block framing, nonce
+// placement, and AAD; see the constants above).
+type goEnvelopeKeyMetadata struct {
+	Version    int    `json:"v"`
+	KeyID      string `json:"key-id"`
+	WrappedKey []byte `json:"wrapped-key"`
+
+	// BlockSize is the trusted plaintext block size the file was written
+	// with. It is validated bounded before any file I/O, and is what's
+	// actually used to size reads; the stream header's block-length field
+	// is untrusted (unauthenticated, attacker-influenced storage bytes) and
+	// is only compared against this value, never used directly to size an
+	// allocation.
+	BlockSize int64 `json:"block-size"`
+
+	// AADPrefix is combined with each block's little-endian index to form
+	// the AES GCM Stream additional authenticated data, binding every
+	// ciphertext block to this file and to its position so that blocks
+	// cannot be silently reordered, replayed from another file, or spliced
+	// in from elsewhere in the same file. It is not secret.
+	AADPrefix []byte `json:"aad-prefix"`
+
+	// PlaintextLength is the trusted total plaintext size used to compute
+	// the block count on read. Per the AES GCM Stream spec's "File length"
+	// note, a reader must use a length from a trusted source rather than
+	// the underlying storage's reported size, since storage size alone
+	// cannot distinguish a genuinely short file from one truncated by an
+	// attacker who does not also control this metadata.
+	PlaintextLength int64 `json:"plaintext-length"`
+}
+
+// GoEnvelopeEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks and written using the
+// Iceberg AES GCM Stream ("AGS1") format: a magic/block-length header
+// followed by independently authenticated blocks, each carrying its own
+// random nonce and authenticated with an AAD that binds it to the file and
+// to its position. This bounds memory usage and supports random access
+// (Seek/ReadAt) on the decrypted file without buffering or decrypting more
+// than the requested blocks.
+//
+// GoEnvelopeEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+//
+// Not interoperable with Java's StandardEncryptionManager: the AGS1 byte
+// stream framing (magic, block layout, nonce placement, AAD) matches the
+// spec, but the two implementations are not cross-readable. Java's reader
+// hard-requires a 1 MiB header block size (a compile-time constant there),
+// while [GoEnvelopeDefaultBlockSize] is 64 KiB, and Java decodes key
+// metadata as a 1-byte version plus Avro-encoded StandardKeyMetadata, while
+// this type encodes key metadata as JSON (goEnvelopeKeyMetadata). Files
+// written by one are not readable by the other.
+type GoEnvelopeEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*GoEnvelopeEncryptionManager)(nil)
+
+// GoEnvelopeManagerOption configures a [GoEnvelopeEncryptionManager] created
+// by [NewGoEnvelopeEncryptionManager].
+type GoEnvelopeManagerOption func(*GoEnvelopeEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) GoEnvelopeManagerOption {
+	return func(m *GoEnvelopeEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication. size must be
+// positive and at most [GoEnvelopeMaxBlockSize].
+func WithBlockSize(size int) GoEnvelopeManagerOption {
+	return func(m *GoEnvelopeEncryptionManager) { m.blockSize = size }
+}
+
+// NewGoEnvelopeEncryptionManager creates a [GoEnvelopeEncryptionManager]
+// backed by kms. kms must not be nil; NewGoEnvelopeEncryptionManager panics
+// if it is.
+func NewGoEnvelopeEncryptionManager(kms KeyManagementClient, opts ...GoEnvelopeManagerOption) *GoEnvelopeEncryptionManager {
+	if kms == nil {
+		panic("encryption: NewGoEnvelopeEncryptionManager: kms must not be nil")
+	}
+
+	m := &GoEnvelopeEncryptionManager{
+		kms:       kms,
+		dekLength: GoEnvelopeDefaultDEKLength,
+		blockSize: GoEnvelopeDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *GoEnvelopeEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 || m.blockSize > GoEnvelopeMaxBlockSize {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+	switch m.dekLength {
+	case 16, 24, 32:
+	default:
+		return nil, fmt.Errorf("%w: DEK length must be 16, 24, or 32 bytes; got %d", ErrInvalidKeyLength, m.dekLength)
+	}
+
+	// The (key, nonce) uniqueness this block format relies on requires a
+	// freshly generated DEK for every file: never cache or reuse
+	// plainDEK/wrappedDEK across calls to NewEncryptedOutputFile.
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = io.ReadFull(rand.Reader, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newGoEnvelopeAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	aadPrefix := make([]byte, gcmStreamAADPrefixLength)
+	if _, err := io.ReadFull(rand.Reader, aadPrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate AAD prefix: %w", err)
+	}
+
+	// Write the AES GCM Stream header (magic + little-endian block length)
+	// up front, before any ciphertext blocks, per the format spec.
+	header := make([]byte, gcmStreamHeaderLength)
+	copy(header, gcmStreamMagic)
+	binary.LittleEndian.PutUint32(header[len(gcmStreamMagic):], uint32(m.blockSize)) //nolint:gosec // bounded by ErrInvalidBlockSize above
+	if _, err := writer.Write(header); err != nil {
+		return nil, fmt.Errorf("encryption: failed to write stream header: %w", err)
+	}
+
+	return &goEnvelopeOutputFile{
+		FileWriter: writer,
+		aead:       aead,
+		aadPrefix:  aadPrefix,
+		blockSize:  m.blockSize,
+		keyID:      keyID,
+		wrappedKey: wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *GoEnvelopeEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta goEnvelopeKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != goEnvelopeKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 || meta.BlockSize > GoEnvelopeMaxBlockSize {
+		return nil, fmt.Errorf("%w: block-size must be positive and at most %d, got %d", ErrInvalidKeyMetadata, GoEnvelopeMaxBlockSize, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}
+	if len(meta.AADPrefix) == 0 {

Review Comment:
   Your reply on this line says "aad-prefix now requires 16 bytes", but the check is still emptiness only:
   
   ```go
   if len(meta.AADPrefix) == 0 {
   ```
   
   A one-byte prefix is accepted at construction; I confirmed that with a focused probe. The PR body also states the AAD-prefix length is bounds-checked.
   
   Non-blocking by itself, since malformed key metadata arrives from an operator- or catalog-supplied path. But please either enforce `len(meta.AADPrefix) == 16` with a case, or correct the claim so the thread record matches the code.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat(encryption): add StandardEncryptionManager [iceberg-go]

Posted by "tanmayrauth (via GitHub)" <gi...@apache.org>.
tanmayrauth commented on code in PR #1620:
URL: https://github.com/apache/iceberg-go/pull/1620#discussion_r3693024310


##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,488 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	return &standardInputFile{
+		underlying:      file,
+		aead:            aead,
+		noncePrefix:     meta.NoncePrefix,
+		blockSize:       meta.BlockSize,

Review Comment:
   Nit: NewStandardEncryptionManager doesn't validate blockSize, so a bad WithBlockSize only surfaces at write time — WithBlockSize(-1) panics slice bounds out of range [:-1] on the first Write, and WithBlockSize(0) spins forever here  (len(f.buf) == f.blockSize is 0 == 0 every iteration, so p is never consumed). A blockSize > 0 guard in NewEncryptedOutputFile (which already returns an error) rejects it early.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat(encryption): add StandardEncryptionManager [iceberg-go]

Posted by "hectar-glitches (via GitHub)" <gi...@apache.org>.
hectar-glitches commented on code in PR #1620:
URL: https://github.com/apache/iceberg-go/pull/1620#discussion_r3707721148


##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,488 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	return &standardInputFile{
+		underlying:      file,
+		aead:            aead,
+		noncePrefix:     meta.NoncePrefix,
+		blockSize:       meta.BlockSize,

Review Comment:
   agreed. Added validation right after the version check: block-size must be positive, plaintext-length must be non-negative, and nonce-prefix must be exactly 4 bytes, all wrapped in a new 'ErrInvalidKeyMetadata'. Added the well-formed-but-block-size-0 case you mentioned, plus negative-plaintext-length and bad-nonce-prefix-length cases.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat(encryption): add GoEnvelopeEncryptionManager for generic file envelope encryption [iceberg-go]

Posted by "hectar-glitches (via GitHub)" <gi...@apache.org>.
hectar-glitches commented on PR #1620:
URL: https://github.com/apache/iceberg-go/pull/1620#issuecomment-5770919351

   sorry, the changes were still in my branch, i didnt push upstream


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat(encryption): add StandardEncryptionManager for generic file envelope encryption [iceberg-go]

Posted by "hectar-glitches (via GitHub)" <gi...@apache.org>.
hectar-glitches commented on code in PR #1620:
URL: https://github.com/apache/iceberg-go/pull/1620#discussion_r4262469935


##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,862 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+	"math"
+	"slices"
+	"sync"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// StandardDefaultDataKeyLength is the default length, in bytes, of the
+// per-file data encryption key (DEK). It is 128-bit, matching the default of
+// the encryption.data-key-length table property in the Java and Rust
+// implementations.
+const StandardDefaultDataKeyLength = 16
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires the table's
+	// encryption key ID; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by
+	// [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata starts
+	// with a version byte other than the one this package understands.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidStreamHeader is returned when the AES GCM Stream header (the
+	// "AGS1" magic and little-endian plain block length at the start of an
+	// encrypted file, per the Iceberg AES GCM Stream spec) is missing,
+	// truncated, or declares a block length other than the fixed 1 MiB.
+	ErrInvalidStreamHeader = errors.New("encryption: invalid AES GCM Stream header")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when key metadata is
+	// not a well-formed StandardKeyMetadata record or fails basic sanity
+	// checks (e.g. a truncated record, a missing or wrong-sized AAD prefix, or
+	// a missing or impossible file length). Key metadata is untrusted input on
+	// a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+
+	// ErrOutputFileClosed is returned by [standardOutputFile.Write] when
+	// called after a successful Close. It wraps [fs.ErrClosed] so callers can
+	// test with errors.Is(err, fs.ErrClosed). A Write after a failed flush or
+	// a failed Close returns that original error instead.
+	ErrOutputFileClosed = fmt.Errorf("encryption: write to closed StandardEncryptionManager output file: %w", fs.ErrClosed)
+
+	// ErrBlockTruncated is returned by [standardInputFile.ReadAt] when the
+	// underlying storage returns fewer ciphertext bytes for a block than its
+	// recorded length requires, indicating the file was truncated at rest.
+	// This is distinct from [ErrCiphertextTooShort], which [KeyManagementClient]
+	// implementations use for a too-short wrapped key or KMS-encrypted
+	// payload; keeping them separate lets a caller tell a malformed KMS blob
+	// apart from a short block read.
+	ErrBlockTruncated = errors.New("encryption: block truncated: read fewer ciphertext bytes than expected")
+)
+
+// Constants describing the Iceberg AES GCM Stream ("AGS1") wire format used
+// for the ciphertext produced by [StandardEncryptionManager]. See
+// https://iceberg.apache.org/gcm-stream-spec/ for the full specification.
+const (
+	// gcmStreamMagic identifies an AES GCM Stream version 1 file.
+	gcmStreamMagic = "AGS1"
+
+	// gcmStreamHeaderLength is the length, in bytes, of the magic plus the
+	// 4-byte little-endian plain block length written at the start of every
+	// file.
+	gcmStreamHeaderLength = 8
+
+	// gcmStreamPlainBlockSize is the plaintext block size. It is fixed:
+	// Java's Ciphers.PLAIN_BLOCK_SIZE and iceberg-rust's PLAIN_BLOCK_SIZE are
+	// both 1 MiB, and Java's AesGcmInputStream rejects any other value in the
+	// header, so a stream with a different block size is unreadable there.
+	gcmStreamPlainBlockSize = 1024 * 1024
+
+	// gcmStreamNonceLength is the length, in bytes, of the random AES-GCM
+	// nonce stored at the start of every cipher block.
+	gcmStreamNonceLength = 12
+
+	// gcmStreamTagLength is the length, in bytes, of the AES-GCM
+	// authentication tag appended to every cipher block's ciphertext.
+	gcmStreamTagLength = 16
+
+	// gcmStreamBlockOverhead is the number of ciphertext bytes added to
+	// each block beyond its plaintext length (nonce + tag).
+	gcmStreamBlockOverhead = gcmStreamNonceLength + gcmStreamTagLength
+
+	// gcmStreamCipherBlockSize is the on-disk length of a full block.
+	gcmStreamCipherBlockSize = gcmStreamPlainBlockSize + gcmStreamBlockOverhead
+
+	// gcmStreamMinLength is the length of the smallest valid stream: the
+	// header followed by one block holding no plaintext. Java and iceberg-rust
+	// always write block 0, even for an empty file, and iceberg-rust rejects
+	// anything shorter.
+	gcmStreamMinLength = gcmStreamHeaderLength + gcmStreamBlockOverhead
+
+	// gcmStreamAADPrefixLength is the length, in bytes, of the random
+	// per-file AAD prefix. It matches Java's ENCRYPTION_AAD_LENGTH_DEFAULT.
+	gcmStreamAADPrefixLength = 16
+)
+
+// standardKeyMetadataVersion is the leading version byte of Iceberg's
+// StandardKeyMetadata encoding.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the decoded form of Iceberg's StandardKeyMetadata:
+// a version byte followed by an Avro binary record
+//
+//	{encryption_key: bytes, aad_prefix: ["null", bytes], file_length: ["null", long]}
+//
+// This is the key_metadata encoding Java's StandardEncryptionManager,
+// iceberg-rust and pyiceberg read and write. It holds the raw DEK, so it is a
+// secret and must be protected by whatever stores it.
+type standardKeyMetadata struct {
+	encryptionKey []byte
+
+	// aadPrefix is combined with each block's little-endian index to form
+	// the AES GCM Stream additional authenticated data, binding every
+	// ciphertext block to this file and to its position so that blocks
+	// cannot be silently reordered, replayed from another file, or spliced
+	// in from elsewhere in the same file. It is not secret. It is nil when
+	// the record omits it.
+	aadPrefix []byte
+
+	// fileLength is the length of the encrypted stream, header included.
+	// Per the AES GCM Stream spec's "File length" note, a reader must take
+	// the length from a trusted source rather than the underlying storage's
+	// reported size, since storage size alone cannot distinguish a genuinely
+	// short file from one truncated by an attacker who does not also control
+	// this metadata. hasFileLength is false when the record omits it.
+	fileLength    int64
+	hasFileLength bool
+}
+
+// encodeStandardKeyMetadata encodes the version byte and Avro record for a
+// file, with both optional fields present.
+func encodeStandardKeyMetadata(encryptionKey, aadPrefix []byte, fileLength int64) EncryptionKeyMetadata {
+	b := []byte{standardKeyMetadataVersion}
+	b = binary.AppendVarint(b, int64(len(encryptionKey)))
+	b = append(b, encryptionKey...)
+	b = binary.AppendVarint(b, 1) // union branch 1 (bytes): aad_prefix is present
+	b = binary.AppendVarint(b, int64(len(aadPrefix)))
+	b = append(b, aadPrefix...)
+	b = binary.AppendVarint(b, 1) // union branch 1 (long): file_length is present
+	b = binary.AppendVarint(b, fileLength)
+
+	return b
+}
+
+// decodeStandardKeyMetadata decodes the version byte and Avro record written
+// by [encodeStandardKeyMetadata] or by Java's StandardKeyMetadata.buffer().
+func decodeStandardKeyMetadata(b []byte) (standardKeyMetadata, error) {
+	if b[0] != standardKeyMetadataVersion {
+		return standardKeyMetadata{}, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, b[0])
+	}
+
+	r := avroReader{buf: b[1:]}
+	var k standardKeyMetadata
+	k.encryptionKey = r.bytes()
+	if r.present() {
+		k.aadPrefix = r.bytes()
+	}
+	if r.present() {
+		k.fileLength = r.long()
+		k.hasFileLength = true
+	}
+	if r.err == nil && len(r.buf) != 0 {
+		r.err = fmt.Errorf("%d unexpected trailing bytes", len(r.buf))
+	}
+	if r.err != nil {
+		return standardKeyMetadata{}, fmt.Errorf("%w: %w", ErrInvalidKeyMetadata, r.err)
+	}
+
+	return k, nil
+}
+
+// avroReader decodes the few Avro binary primitives StandardKeyMetadata uses,
+// remembering the first error. Avro longs are zig-zag varints, which is what
+// encoding/binary's Varint implements.
+type avroReader struct {
+	buf []byte
+	err error
+}
+
+func (r *avroReader) long() int64 {
+	if r.err != nil {
+		return 0
+	}
+	v, n := binary.Varint(r.buf)
+	if n <= 0 {
+		r.err = errors.New("truncated or oversized varint")
+
+		return 0
+	}
+	r.buf = r.buf[n:]
+
+	return v
+}
+
+func (r *avroReader) bytes() []byte {
+	n := r.long()
+	if r.err != nil {
+		return nil
+	}
+	if n < 0 || n > int64(len(r.buf)) {
+		r.err = fmt.Errorf("bytes length %d out of range (%d bytes remain)", n, len(r.buf))
+
+		return nil
+	}
+	out := slices.Clone(r.buf[:n])
+	r.buf = r.buf[n:]
+
+	return out
+}
+
+// present reads the branch index of a ["null", T] union and reports whether
+// the value is present (branch 1) rather than null (branch 0).
+func (r *avroReader) present() bool {
+	branch := r.long()
+	if r.err != nil {
+		return false
+	}
+	if branch != 0 && branch != 1 {
+		r.err = fmt.Errorf("unexpected union branch %d", branch)
+
+		return false
+	}
+
+	return branch == 1
+}
+
+// plaintextLengthFromStreamLength derives the plaintext length from the
+// length of the encrypted stream, the way Java's
+// AesGcmInputStream.calculatePlaintextLength does. It accepts the 36-byte
+// form of an empty file (header plus one empty block) and rejects lengths no
+// writer could have produced.
+func plaintextLengthFromStreamLength(streamLength int64) (int64, error) {
+	if streamLength < gcmStreamMinLength {
+		return 0, fmt.Errorf("%w: file-length %d is shorter than the %d-byte minimum stream", ErrInvalidKeyMetadata, streamLength, gcmStreamMinLength)
+	}
+
+	body := streamLength - gcmStreamHeaderLength
+	plainLength := body / gcmStreamCipherBlockSize * gcmStreamPlainBlockSize
+	if lastBlock := body % gcmStreamCipherBlockSize; lastBlock != 0 {
+		if lastBlock < gcmStreamBlockOverhead {
+			return 0, fmt.Errorf("%w: file-length %d ends in a %d-byte block, shorter than its %d-byte nonce and tag", ErrInvalidKeyMetadata, streamLength, lastBlock, gcmStreamBlockOverhead)
+		}
+		plainLength += lastBlock - gcmStreamBlockOverhead
+	}
+
+	return plainLength, nil
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// for arbitrary files (e.g. manifests, manifest lists, Puffin statistics). It
+// reads and writes the same bytes as Java's StandardEncryptionManager,
+// iceberg-rust and pyiceberg: an Iceberg AES GCM Stream ("AGS1") with fixed
+// 1 MiB plaintext blocks, and key metadata in Iceberg's StandardKeyMetadata
+// encoding.
+//
+// Each file is encrypted under a fresh random data encryption key (DEK),
+// generated locally with no KMS call. Each block carries its own random nonce
+// and is authenticated with an AAD that binds it to the file and to its
+// position. This bounds memory usage and supports random access
+// (Seek/ReadAt) on the decrypted file without buffering or decrypting more
+// than the requested blocks.
+//
+// The key metadata returned by Close contains the raw DEK, so it is a secret:
+// persist it only where something protects it, such as a manifest or manifest
+// list that is itself encrypted under a key encryption key. Wrapping the DEK
+// that way is not done by this type.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	dataKeyLength int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithStandardDataKeyLength sets the length, in bytes, of the per-file data
+// encryption key. It corresponds to the encryption.data-key-length table
+// property. Valid AES key lengths are 16, 24, or 32 bytes; the default is
+// [StandardDefaultDataKeyLength].
+func WithStandardDataKeyLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dataKeyLength = length }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager].
+func NewStandardEncryptionManager(opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{dataKeyLength: StandardDefaultDataKeyLength}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID is the table's encryption key ID and must be non-empty; otherwise
+// [ErrKeyIDRequired] is returned. It is not recorded in the file's key
+// metadata.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(_ context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	switch m.dataKeyLength {
+	case 16, 24, 32:
+	default:
+		return nil, fmt.Errorf("%w: DEK length must be 16, 24, or 32 bytes; got %d", ErrInvalidKeyLength, m.dataKeyLength)
+	}
+
+	// A fresh DEK per file keeps the number of random-nonce encryptions under
+	// any one key within the 2^32 limit NIST SP 800-38D sets for random
+	// 96-bit nonces: a file holds at most 2^32-1 blocks.
+	dek := make([]byte, m.dataKeyLength)
+	if _, err := io.ReadFull(rand.Reader, dek); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(dek)
+	if err != nil {
+		return nil, err
+	}
+
+	aadPrefix := make([]byte, gcmStreamAADPrefixLength)
+	if _, err := io.ReadFull(rand.Reader, aadPrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate AAD prefix: %w", err)
+	}
+
+	// Write the AES GCM Stream header (magic + little-endian block length)
+	// up front, before any ciphertext blocks, per the format spec.
+	header := make([]byte, gcmStreamHeaderLength)
+	copy(header, gcmStreamMagic)
+	binary.LittleEndian.PutUint32(header[len(gcmStreamMagic):], gcmStreamPlainBlockSize)
+	if _, err := writer.Write(header); err != nil {
+		return nil, fmt.Errorf("encryption: failed to write stream header: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:      writer,
+		aead:            aead,
+		dek:             dek,
+		aadPrefix:       aadPrefix,
+		encryptedLength: gcmStreamHeaderLength,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty StandardKeyMetadata blob
+// produced by [StandardEncryptionManager.NewEncryptedOutputFile] or by another
+// Iceberg implementation; otherwise [ErrKeyMetadataRequired] is returned.
+//
+// The plaintext length is derived from the file length recorded in key
+// metadata, never from the underlying file's size. Key metadata without a file
+// length is rejected, because there is no other trusted source for it here.
+// Key metadata without an AAD prefix, which the encoding permits, is rejected
+// too: the prefix is what binds a block to its file.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(_ context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	meta, err := decodeStandardKeyMetadata(keyMetadata)
+	if err != nil {
+		return nil, err
+	}
+	// Java, iceberg-rust and this writer all emit 16-byte prefixes. Bounding
+	// it also keeps the per-block AAD allocation in readBlock small.
+	if len(meta.aadPrefix) != gcmStreamAADPrefixLength {
+		return nil, fmt.Errorf("%w: aad-prefix must be exactly %d bytes, got %d", ErrInvalidKeyMetadata, gcmStreamAADPrefixLength, len(meta.aadPrefix))
+	}
+	if !meta.hasFileLength {

Review Comment:
   NewDecryptedInputFileWithLength (standard_manager.go:412) uses file_length when it’s present, otherwise the caller’s length, and fails only when neither exists.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat(encryption): add GoEnvelopeEncryptionManager for generic file envelope encryption [iceberg-go]

Posted by "hectar-glitches (via GitHub)" <gi...@apache.org>.
hectar-glitches commented on code in PR #1620:
URL: https://github.com/apache/iceberg-go/pull/1620#discussion_r3972305605


##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,883 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+	"math"
+	"sync"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [GoEnvelopeEncryptionManager].
+const (
+	// GoEnvelopeDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	GoEnvelopeDefaultDEKLength = 32
+
+	// GoEnvelopeDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	//
+	// This is not Java's Ciphers.PLAIN_BLOCK_SIZE (1 MiB, a compile-time
+	// constant there); see the [GoEnvelopeEncryptionManager] doc comment.
+	GoEnvelopeDefaultBlockSize = 64 * 1024
+
+	// GoEnvelopeMaxBlockSize is the largest plaintext block size accepted
+	// from the AES GCM Stream header on read, and the largest that
+	// [WithBlockSize] will configure for writing. The header's block-length
+	// field is unauthenticated, untrusted data (the Iceberg AES GCM Stream
+	// spec's "File length" note applies equally here); without a ceiling, a
+	// crafted header claiming e.g. 1<<40 bytes would force a huge
+	// allocation (see readBlock) before any authentication check can run.
+	GoEnvelopeMaxBlockSize = 128 * 1024 * 1024
+)
+
+// Sentinel errors returned by [GoEnvelopeEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile] when keyID is
+	// empty. GoEnvelopeEncryptionManager always encrypts, so it requires a
+	// KEK to wrap the generated DEK; use [PlaintextEncryptionManager] for
+	// unencrypted tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when keyMetadata
+	// is empty. GoEnvelopeEncryptionManager always decrypts, so it requires
+	// the per-file key metadata produced by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured block size is not
+	// positive or exceeds [GoEnvelopeMaxBlockSize].
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive and at most GoEnvelopeMaxBlockSize")
+
+	// ErrInvalidStreamHeader is returned when the AES GCM Stream header
+	// (the "AGS1" magic and little-endian block-length fields at the start
+	// of an encrypted file, per the Iceberg AES GCM Stream spec) is
+	// missing, truncated, or specifies a block length outside the
+	// supported range.
+	ErrInvalidStreamHeader = errors.New("encryption: invalid AES GCM Stream header")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a missing AAD prefix). Key metadata is untrusted input on a crypto
+	// read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+
+	// ErrOutputFileClosed is returned by [goEnvelopeOutputFile.Write] when
+	// called after Close, or after a previous flush has poisoned the writer.
+	// It wraps [fs.ErrClosed] so callers can test with errors.Is(err, fs.ErrClosed).
+	ErrOutputFileClosed = fmt.Errorf("encryption: write to closed GoEnvelopeEncryptionManager output file: %w", fs.ErrClosed)
+
+	// ErrBlockTruncated is returned by [goEnvelopeInputFile.ReadAt] when the
+	// underlying storage returns fewer ciphertext bytes for a block than its
+	// recorded length requires, indicating the file was truncated at rest.
+	// This is distinct from [ErrCiphertextTooShort], which [KeyManagementClient]
+	// implementations use for a too-short wrapped key or KMS-encrypted
+	// payload; keeping them separate lets a caller tell a malformed KMS blob
+	// apart from a short block read.
+	ErrBlockTruncated = errors.New("encryption: block truncated: read fewer ciphertext bytes than expected")
+)
+
+// Constants describing the Iceberg AES GCM Stream ("AGS1") wire format used
+// for the ciphertext produced by [GoEnvelopeEncryptionManager]. See
+// https://iceberg.apache.org/gcm-stream-spec/ for the full specification.
+const (
+	// gcmStreamMagic identifies an AES GCM Stream version 1 file.
+	gcmStreamMagic = "AGS1"
+
+	// gcmStreamHeaderLength is the length, in bytes, of the magic plus the
+	// little-endian block-length field written at the start of every file.
+	gcmStreamHeaderLength = len(gcmStreamMagic) + 4
+
+	// gcmStreamNonceLength is the length, in bytes, of the random AES-GCM
+	// nonce stored at the start of every cipher block.
+	gcmStreamNonceLength = 12
+
+	// gcmStreamTagLength is the length, in bytes, of the AES-GCM
+	// authentication tag appended to every cipher block's ciphertext.
+	gcmStreamTagLength = 16
+
+	// gcmStreamBlockOverhead is the number of ciphertext bytes added to
+	// each block beyond its plaintext length (nonce + tag).
+	gcmStreamBlockOverhead = gcmStreamNonceLength + gcmStreamTagLength
+
+	// gcmStreamAADPrefixLength is the length, in bytes, of the random
+	// per-file AAD prefix generated for new output files.
+	gcmStreamAADPrefixLength = 16
+)
+
+// goEnvelopeKeyMetadataVersion is the current encoding version written by
+// [GoEnvelopeEncryptionManager]. It is bumped whenever the on-disk layout of
+// goEnvelopeKeyMetadata changes incompatibly.
+const goEnvelopeKeyMetadataVersion = 1
+
+// goEnvelopeKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [GoEnvelopeEncryptionManager].
+//
+// This encoding is Go-specific, not Java's Avro-encoded StandardKeyMetadata;
+// see the [GoEnvelopeEncryptionManager] doc comment. Per the table spec,
+// DataFile/ManifestFile key_metadata is explicitly "implementation-specific";
+// what must be Iceberg AES GCM Stream compliant - and is - is the wire
+// format of the encrypted byte stream itself (magic, block framing, nonce
+// placement, and AAD; see the constants above).
+type goEnvelopeKeyMetadata struct {
+	Version    int    `json:"v"`
+	KeyID      string `json:"key-id"`
+	WrappedKey []byte `json:"wrapped-key"`
+
+	// BlockSize is the trusted plaintext block size the file was written
+	// with. It is validated bounded before any file I/O, and is what's
+	// actually used to size reads; the stream header's block-length field
+	// is untrusted (unauthenticated, attacker-influenced storage bytes) and
+	// is only compared against this value, never used directly to size an
+	// allocation.
+	BlockSize int64 `json:"block-size"`
+
+	// AADPrefix is combined with each block's little-endian index to form
+	// the AES GCM Stream additional authenticated data, binding every
+	// ciphertext block to this file and to its position so that blocks
+	// cannot be silently reordered, replayed from another file, or spliced
+	// in from elsewhere in the same file. It is not secret.
+	AADPrefix []byte `json:"aad-prefix"`
+
+	// PlaintextLength is the trusted total plaintext size used to compute
+	// the block count on read. Per the AES GCM Stream spec's "File length"
+	// note, a reader must use a length from a trusted source rather than
+	// the underlying storage's reported size, since storage size alone
+	// cannot distinguish a genuinely short file from one truncated by an
+	// attacker who does not also control this metadata.
+	PlaintextLength int64 `json:"plaintext-length"`
+}
+
+// GoEnvelopeEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks and written using the
+// Iceberg AES GCM Stream ("AGS1") format: a magic/block-length header
+// followed by independently authenticated blocks, each carrying its own
+// random nonce and authenticated with an AAD that binds it to the file and
+// to its position. This bounds memory usage and supports random access
+// (Seek/ReadAt) on the decrypted file without buffering or decrypting more
+// than the requested blocks.
+//
+// GoEnvelopeEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+//
+// Not interoperable with Java's StandardEncryptionManager: the AGS1 byte
+// stream framing (magic, block layout, nonce placement, AAD) matches the
+// spec, but the two implementations are not cross-readable. Java's reader
+// hard-requires a 1 MiB header block size (a compile-time constant there),
+// while [GoEnvelopeDefaultBlockSize] is 64 KiB, and Java decodes key
+// metadata as a 1-byte version plus Avro-encoded StandardKeyMetadata, while
+// this type encodes key metadata as JSON (goEnvelopeKeyMetadata). Files
+// written by one are not readable by the other.
+type GoEnvelopeEncryptionManager struct {
+	kms       KeyManagementClient

Review Comment:
   Updating the title and body now to match the AGS1 rewrite



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat(encryption): add StandardEncryptionManager [iceberg-go]

Posted by "tanmayrauth (via GitHub)" <gi...@apache.org>.
tanmayrauth commented on code in PR #1620:
URL: https://github.com/apache/iceberg-go/pull/1620#discussion_r3693021679


##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,488 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	return &standardInputFile{
+		underlying:      file,
+		aead:            aead,
+		noncePrefix:     meta.NoncePrefix,
+		blockSize:       meta.BlockSize,
+		plaintextLength: meta.PlaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newStandardAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %v", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// standardBlockNonce derives the AES-GCM nonce for blockIndex: the 4-byte
+// per-file random prefix followed by the 8-byte big-endian block index. The
+// (key, nonce) pair is unique per block since the DEK is fresh per file and
+// no two blocks in the same file share an index.
+func standardBlockNonce(prefix []byte, blockIndex uint64) []byte {
+	nonce := make([]byte, 12)
+	copy(nonce, prefix)
+	binary.BigEndian.PutUint64(nonce[4:], blockIndex)
+
+	return nonce
+}
+
+// standardOutputFile is an [EncryptedOutputFile] that seals fixed-size
+// plaintext blocks with AES-GCM as they are written.
+type standardOutputFile struct {
+	icebergio.FileWriter
+
+	aead        cipher.AEAD
+	noncePrefix []byte
+	blockSize   int
+	keyID       string
+	wrappedKey  []byte
+
+	buf        []byte
+	blockIndex uint64
+	written    int64
+	closed     bool
+
+	keyMetadata EncryptionKeyMetadata
+}
+
+var _ EncryptedOutputFile = (*standardOutputFile)(nil)
+
+func (f *standardOutputFile) Write(p []byte) (int, error) {
+	total := len(p)
+	for len(p) > 0 {
+		space := f.blockSize - len(f.buf)

Review Comment:
   Nit: NewStandardEncryptionManager doesn't validate blockSize, so a bad WithBlockSize only surfaces at write time — WithBlockSize(-1) panics slice bounds out of range [:-1] on the first Write, and WithBlockSize(0) spins forever here  (len(f.buf) == f.blockSize is 0 == 0 every iteration, so p is never consumed). A blockSize > 0 guard in NewEncryptedOutputFile (which already returns an error) rejects it early.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat(encryption): add StandardEncryptionManager [iceberg-go]

Posted by "zeroshade (via GitHub)" <gi...@apache.org>.
zeroshade commented on PR #1620:
URL: https://github.com/apache/iceberg-go/pull/1620#issuecomment-5270636606

   @rambleraptor Thanks for the interest! Status: the review feedback (chiefly that the on-disk layout needs to conform to the Iceberg AES GCM Stream spec — AGS1 magic, per-block stored nonces, block-sequence AAD, and Java's `StandardKeyMetadata` Avro form — so files interop with Java/PyIceberg) hasn't been addressed yet. If @hectar-glitches doesn't have bandwidth, a fresh PR building on this one with the format fixed would be very welcome — happy to review promptly.
   
   <sub>_Posted by an AI-assisted tool on behalf of maintainer `zeroshade`._</sub>
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat(encryption): add StandardEncryptionManager for generic file envelope encryption [iceberg-go]

Posted by "zeroshade (via GitHub)" <gi...@apache.org>.
zeroshade merged PR #1620:
URL: https://github.com/apache/iceberg-go/pull/1620


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat(encryption): add StandardEncryptionManager [iceberg-go]

Posted by "laskoviymishka (via GitHub)" <gi...@apache.org>.
laskoviymishka commented on code in PR #1620:
URL: https://github.com/apache/iceberg-go/pull/1620#discussion_r3850550091


##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,583 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+
+	// ErrOutputFileClosed is returned by [standardOutputFile.Write] when
+	// called after Close, or after a previous flush has poisoned the writer.
+	ErrOutputFileClosed = errors.New("encryption: write to closed StandardEncryptionManager output file")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+	switch m.dekLength {
+	case 16, 24, 32:
+	default:
+		return nil, fmt.Errorf("%w: DEK length must be 16, 24, or 32 bytes; got %d", ErrInvalidKeyLength, m.dekLength)
+	}
+
+	// The (key, nonce) uniqueness this block format relies on requires a
+	// freshly generated DEK for every file: the nonce is only 4 random bytes
+	// plus a block index, so reusing a DEK across files would reuse (DEK,
+	// nonce) pairs and break AES-GCM's security guarantees. Never cache or
+	// reuse plainDEK/wrappedDEK across calls to NewEncryptedOutputFile.
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}

Review Comment:
   Small one: `crypto/rand.Read` always returns `(n, nil)` since Go 1.20, so this error check (and the one on the nonce prefix at ~205) is dead. `kms.go` in this package uses `io.ReadFull(rand.Reader, buf)`; matching that here keeps the check live and the crypto path consistent.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,583 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+
+	// ErrOutputFileClosed is returned by [standardOutputFile.Write] when
+	// called after Close, or after a previous flush has poisoned the writer.
+	ErrOutputFileClosed = errors.New("encryption: write to closed StandardEncryptionManager output file")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+	switch m.dekLength {
+	case 16, 24, 32:
+	default:
+		return nil, fmt.Errorf("%w: DEK length must be 16, 24, or 32 bytes; got %d", ErrInvalidKeyLength, m.dekLength)
+	}
+
+	// The (key, nonce) uniqueness this block format relies on requires a
+	// freshly generated DEK for every file: the nonce is only 4 random bytes
+	// plus a block index, so reusing a DEK across files would reuse (DEK,
+	// nonce) pairs and break AES-GCM's security guarantees. Never cache or
+	// reuse plainDEK/wrappedDEK across calls to NewEncryptedOutputFile.
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 {
+		return nil, fmt.Errorf("%w: block-size must be positive, got %d", ErrInvalidKeyMetadata, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}
+	if len(meta.NoncePrefix) != 4 {
+		return nil, fmt.Errorf("%w: nonce-prefix must be 4 bytes, got %d", ErrInvalidKeyMetadata, len(meta.NoncePrefix))
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	return &standardInputFile{
+		underlying:      file,
+		aead:            aead,
+		noncePrefix:     meta.NoncePrefix,
+		blockSize:       meta.BlockSize,
+		plaintextLength: meta.PlaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newStandardAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %w", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// standardBlockNonce derives the AES-GCM nonce for blockIndex: the 4-byte
+// per-file random prefix followed by the 8-byte big-endian block index.
+// Uniqueness of the (key, nonce) pair across every block ever sealed with a
+// given DEK depends entirely on the DEK being freshly generated per file;
+// see the caution in [StandardEncryptionManager.NewEncryptedOutputFile].
+func standardBlockNonce(prefix []byte, blockIndex uint64) []byte {
+	nonce := make([]byte, 12)
+	copy(nonce, prefix)
+	binary.BigEndian.PutUint64(nonce[4:], blockIndex)
+
+	return nonce
+}
+
+// standardOutputFile is an [EncryptedOutputFile] that seals fixed-size
+// plaintext blocks with AES-GCM as they are written.
+type standardOutputFile struct {
+	icebergio.FileWriter
+
+	aead        cipher.AEAD
+	noncePrefix []byte
+	blockSize   int
+	keyID       string
+	wrappedKey  []byte
+
+	buf        []byte
+	blockIndex uint64
+	written    int64
+	closed     bool
+	err        error
+
+	keyMetadata EncryptionKeyMetadata
+}
+
+var _ EncryptedOutputFile = (*standardOutputFile)(nil)
+
+func (f *standardOutputFile) Write(p []byte) (int, error) {
+	if f.err != nil {
+		return 0, f.err
+	}
+	if f.closed {
+		return 0, ErrOutputFileClosed
+	}
+
+	total := len(p)
+	for len(p) > 0 {
+		space := f.blockSize - len(f.buf)
+		n := min(space, len(p))
+		f.buf = append(f.buf, p[:n]...)
+		p = p[n:]
+		if len(f.buf) == f.blockSize {
+			if err := f.flushBlock(); err != nil {
+				f.err = err
+
+				return total - len(p), err
+			}
+		}
+	}
+
+	return total, nil
+}

Review Comment:
   The count side of that same write concern. When a block flush fails mid-Write we return `total - len(p)`, but the failed block is still sitting in `f.buf`, drained out of `p` and never written. So `Write([]byte("aaaabbbb"))` with `blockSize=4` and the second flush failing returns `(8, err)` when only 4 bytes actually landed, and `io.Copy` accumulates that count before it checks the error. I'd return `total - len(p) - len(f.buf)` so we only count what was flushed. The regression test discards the count (`_, err = out.Write(...)`), which is why this slips through, so worth asserting `n` there too.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,583 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+
+	// ErrOutputFileClosed is returned by [standardOutputFile.Write] when
+	// called after Close, or after a previous flush has poisoned the writer.
+	ErrOutputFileClosed = errors.New("encryption: write to closed StandardEncryptionManager output file")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+	switch m.dekLength {
+	case 16, 24, 32:
+	default:
+		return nil, fmt.Errorf("%w: DEK length must be 16, 24, or 32 bytes; got %d", ErrInvalidKeyLength, m.dekLength)
+	}
+
+	// The (key, nonce) uniqueness this block format relies on requires a
+	// freshly generated DEK for every file: the nonce is only 4 random bytes
+	// plus a block index, so reusing a DEK across files would reuse (DEK,
+	// nonce) pairs and break AES-GCM's security guarantees. Never cache or
+	// reuse plainDEK/wrappedDEK across calls to NewEncryptedOutputFile.
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 {
+		return nil, fmt.Errorf("%w: block-size must be positive, got %d", ErrInvalidKeyMetadata, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}
+	if len(meta.NoncePrefix) != 4 {
+		return nil, fmt.Errorf("%w: nonce-prefix must be 4 bytes, got %d", ErrInvalidKeyMetadata, len(meta.NoncePrefix))
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	return &standardInputFile{
+		underlying:      file,
+		aead:            aead,
+		noncePrefix:     meta.NoncePrefix,
+		blockSize:       meta.BlockSize,
+		plaintextLength: meta.PlaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newStandardAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %w", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// standardBlockNonce derives the AES-GCM nonce for blockIndex: the 4-byte
+// per-file random prefix followed by the 8-byte big-endian block index.
+// Uniqueness of the (key, nonce) pair across every block ever sealed with a
+// given DEK depends entirely on the DEK being freshly generated per file;
+// see the caution in [StandardEncryptionManager.NewEncryptedOutputFile].
+func standardBlockNonce(prefix []byte, blockIndex uint64) []byte {
+	nonce := make([]byte, 12)
+	copy(nonce, prefix)
+	binary.BigEndian.PutUint64(nonce[4:], blockIndex)
+
+	return nonce
+}
+
+// standardOutputFile is an [EncryptedOutputFile] that seals fixed-size
+// plaintext blocks with AES-GCM as they are written.
+type standardOutputFile struct {
+	icebergio.FileWriter
+
+	aead        cipher.AEAD
+	noncePrefix []byte
+	blockSize   int
+	keyID       string
+	wrappedKey  []byte
+
+	buf        []byte
+	blockIndex uint64
+	written    int64
+	closed     bool
+	err        error
+
+	keyMetadata EncryptionKeyMetadata
+}
+
+var _ EncryptedOutputFile = (*standardOutputFile)(nil)
+
+func (f *standardOutputFile) Write(p []byte) (int, error) {
+	if f.err != nil {
+		return 0, f.err
+	}
+	if f.closed {
+		return 0, ErrOutputFileClosed
+	}
+
+	total := len(p)
+	for len(p) > 0 {
+		space := f.blockSize - len(f.buf)
+		n := min(space, len(p))
+		f.buf = append(f.buf, p[:n]...)
+		p = p[n:]
+		if len(f.buf) == f.blockSize {
+			if err := f.flushBlock(); err != nil {
+				f.err = err
+
+				return total - len(p), err
+			}
+		}
+	}
+
+	return total, nil
+}
+
+// flushBlock seals and writes the currently buffered plaintext block.
+// f.written is only advanced once the ciphertext has actually reached the
+// underlying writer, so a failed flush never overcounts PlaintextLength.
+func (f *standardOutputFile) flushBlock() error {
+	ciphertext := f.aead.Seal(nil, standardBlockNonce(f.noncePrefix, f.blockIndex), f.buf, nil)
+	if _, err := f.FileWriter.Write(ciphertext); err != nil {
+		return fmt.Errorf("encryption: failed to write encrypted block: %w", err)
+	}
+	f.written += int64(len(f.buf))
+	f.blockIndex++
+	f.buf = f.buf[:0]
+
+	return nil
+}
+
+// ReadFrom copies from r, encrypting as data is written, satisfying
+// io.ReaderFrom (required by [icebergio.FileWriter]).
+func (f *standardOutputFile) ReadFrom(r io.Reader) (int64, error) {
+	buf := make([]byte, max(32*1024, f.blockSize))
+	var total int64
+	for {
+		n, err := r.Read(buf)
+		if n > 0 {
+			wn, werr := f.Write(buf[:n])
+			total += int64(wn)
+			if werr != nil {
+				return total, werr
+			}
+		}
+		if err == io.EOF {
+			break
+		}
+		if err != nil {
+			return total, err
+		}
+	}
+
+	return total, nil
+}
+
+// Close flushes any buffered partial block and finalizes the key metadata.
+// closed is only set once everything, including the underlying Close, has
+// succeeded; a failed Close poisons the writer (via f.err) so a retry
+// reliably reports the same error instead of masking the failure as success.
+func (f *standardOutputFile) Close() error {
+	if f.err != nil {
+		return f.err
+	}
+	if f.closed {
+		return nil
+	}
+
+	if len(f.buf) > 0 {
+		if err := f.flushBlock(); err != nil {
+			f.err = err
+			_ = f.FileWriter.Close()
+
+			return err
+		}
+	}
+
+	if f.keyMetadata == nil {
+		meta := standardKeyMetadata{
+			Version:         standardKeyMetadataVersion,
+			KeyID:           f.keyID,
+			WrappedKey:      f.wrappedKey,
+			NoncePrefix:     f.noncePrefix,
+			BlockSize:       f.blockSize,
+			PlaintextLength: f.written,
+		}
+		encoded, err := json.Marshal(meta)
+		if err != nil {
+			f.err = fmt.Errorf("encryption: failed to encode key metadata: %w", err)
+			_ = f.FileWriter.Close()
+
+			return f.err
+		}
+		f.keyMetadata = encoded
+	}
+
+	if err := f.FileWriter.Close(); err != nil {
+		return fmt.Errorf("encryption: failed to close underlying writer: %w", err)
+	}
+	f.closed = true
+
+	return nil
+}

Review Comment:
   This is the other half of the write/close note from last round, still open on the close path. We assign `f.keyMetadata` before calling `f.FileWriter.Close()`, and when that underlying Close fails we return the error but never set `f.err`. So a caller that reads `KeyMetadata()` after a failed Close gets a fully-populated blob for a file that never committed, and a retried Close sails past the `f.err` guard, calls the underlying Close a second time, and returns nil, masking the original failure. I'd set `f.err` on the underlying-close failure and clear `keyMetadata` (or gate `KeyMetadata()` on `f.closed`), so the failure sticks and the metadata only surfaces once the file's actually down. wdyt?



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,583 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+
+	// ErrOutputFileClosed is returned by [standardOutputFile.Write] when
+	// called after Close, or after a previous flush has poisoned the writer.
+	ErrOutputFileClosed = errors.New("encryption: write to closed StandardEncryptionManager output file")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+	switch m.dekLength {
+	case 16, 24, 32:
+	default:
+		return nil, fmt.Errorf("%w: DEK length must be 16, 24, or 32 bytes; got %d", ErrInvalidKeyLength, m.dekLength)
+	}
+
+	// The (key, nonce) uniqueness this block format relies on requires a
+	// freshly generated DEK for every file: the nonce is only 4 random bytes
+	// plus a block index, so reusing a DEK across files would reuse (DEK,
+	// nonce) pairs and break AES-GCM's security guarantees. Never cache or
+	// reuse plainDEK/wrappedDEK across calls to NewEncryptedOutputFile.
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 {
+		return nil, fmt.Errorf("%w: block-size must be positive, got %d", ErrInvalidKeyMetadata, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}
+	if len(meta.NoncePrefix) != 4 {

Review Comment:
   `block-size` comes off untrusted JSON and we only check `<= 0`. With no upper bound it feeds two bad spots: `physicalOffset` does `f.blockSize + f.aead.Overhead()` as an int add before the int64 cast, so a large decoded block-size overflows to a negative offset we then hand to `ReadAt`; and `readBlock` sizes `make([]byte, wantLen)` off it, so a 1 GiB block-size means a 1 GiB allocation per block read, an OOM any malformed manifest entry can trigger. I'd add an upper bound here (a few tens of MiB) and do the offset add in int64. Fails closed the way the rest of the read path does now.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat(encryption): add StandardEncryptionManager [iceberg-go]

Posted by "tanmayrauth (via GitHub)" <gi...@apache.org>.
tanmayrauth commented on code in PR #1620:
URL: https://github.com/apache/iceberg-go/pull/1620#discussion_r3693024310


##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,488 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	return &standardInputFile{
+		underlying:      file,
+		aead:            aead,
+		noncePrefix:     meta.NoncePrefix,
+		blockSize:       meta.BlockSize,

Review Comment:
   Minor robustness nit: NewDecryptedInputFile checks the version but doesn't validate the rest of the decoded metadata. A well-formed-JSON key_metadata with "block-size":0 and non-zero "plaintext-length" builds fine here, then the first Read/ReadAt panics with integer divide by zero (numBlocks at :379, curOff / int64(f.blockSize) at :423). Not reachable from this manager's own output today, but it's untrusted input on a crypto read path — better to fail  closed than panic. Validate meta.BlockSize > 0, meta.PlaintextLength >= 0, and len(meta.NoncePrefix) == 4 right after the version check (:198) and return a wrapped error. The existing "malformed key metadata" test only covers  invalid JSON, so add a well-formed-but-block-size-0 case.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat(encryption): add StandardEncryptionManager [iceberg-go]

Posted by "hectar-glitches (via GitHub)" <gi...@apache.org>.
hectar-glitches commented on code in PR #1620:
URL: https://github.com/apache/iceberg-go/pull/1620#discussion_r3972305605


##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,883 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+	"math"
+	"sync"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [GoEnvelopeEncryptionManager].
+const (
+	// GoEnvelopeDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	GoEnvelopeDefaultDEKLength = 32
+
+	// GoEnvelopeDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	//
+	// This is not Java's Ciphers.PLAIN_BLOCK_SIZE (1 MiB, a compile-time
+	// constant there); see the [GoEnvelopeEncryptionManager] doc comment.
+	GoEnvelopeDefaultBlockSize = 64 * 1024
+
+	// GoEnvelopeMaxBlockSize is the largest plaintext block size accepted
+	// from the AES GCM Stream header on read, and the largest that
+	// [WithBlockSize] will configure for writing. The header's block-length
+	// field is unauthenticated, untrusted data (the Iceberg AES GCM Stream
+	// spec's "File length" note applies equally here); without a ceiling, a
+	// crafted header claiming e.g. 1<<40 bytes would force a huge
+	// allocation (see readBlock) before any authentication check can run.
+	GoEnvelopeMaxBlockSize = 128 * 1024 * 1024
+)
+
+// Sentinel errors returned by [GoEnvelopeEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile] when keyID is
+	// empty. GoEnvelopeEncryptionManager always encrypts, so it requires a
+	// KEK to wrap the generated DEK; use [PlaintextEncryptionManager] for
+	// unencrypted tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when keyMetadata
+	// is empty. GoEnvelopeEncryptionManager always decrypts, so it requires
+	// the per-file key metadata produced by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured block size is not
+	// positive or exceeds [GoEnvelopeMaxBlockSize].
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive and at most GoEnvelopeMaxBlockSize")
+
+	// ErrInvalidStreamHeader is returned when the AES GCM Stream header
+	// (the "AGS1" magic and little-endian block-length fields at the start
+	// of an encrypted file, per the Iceberg AES GCM Stream spec) is
+	// missing, truncated, or specifies a block length outside the
+	// supported range.
+	ErrInvalidStreamHeader = errors.New("encryption: invalid AES GCM Stream header")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a missing AAD prefix). Key metadata is untrusted input on a crypto
+	// read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+
+	// ErrOutputFileClosed is returned by [goEnvelopeOutputFile.Write] when
+	// called after Close, or after a previous flush has poisoned the writer.
+	// It wraps [fs.ErrClosed] so callers can test with errors.Is(err, fs.ErrClosed).
+	ErrOutputFileClosed = fmt.Errorf("encryption: write to closed GoEnvelopeEncryptionManager output file: %w", fs.ErrClosed)
+
+	// ErrBlockTruncated is returned by [goEnvelopeInputFile.ReadAt] when the
+	// underlying storage returns fewer ciphertext bytes for a block than its
+	// recorded length requires, indicating the file was truncated at rest.
+	// This is distinct from [ErrCiphertextTooShort], which [KeyManagementClient]
+	// implementations use for a too-short wrapped key or KMS-encrypted
+	// payload; keeping them separate lets a caller tell a malformed KMS blob
+	// apart from a short block read.
+	ErrBlockTruncated = errors.New("encryption: block truncated: read fewer ciphertext bytes than expected")
+)
+
+// Constants describing the Iceberg AES GCM Stream ("AGS1") wire format used
+// for the ciphertext produced by [GoEnvelopeEncryptionManager]. See
+// https://iceberg.apache.org/gcm-stream-spec/ for the full specification.
+const (
+	// gcmStreamMagic identifies an AES GCM Stream version 1 file.
+	gcmStreamMagic = "AGS1"
+
+	// gcmStreamHeaderLength is the length, in bytes, of the magic plus the
+	// little-endian block-length field written at the start of every file.
+	gcmStreamHeaderLength = len(gcmStreamMagic) + 4
+
+	// gcmStreamNonceLength is the length, in bytes, of the random AES-GCM
+	// nonce stored at the start of every cipher block.
+	gcmStreamNonceLength = 12
+
+	// gcmStreamTagLength is the length, in bytes, of the AES-GCM
+	// authentication tag appended to every cipher block's ciphertext.
+	gcmStreamTagLength = 16
+
+	// gcmStreamBlockOverhead is the number of ciphertext bytes added to
+	// each block beyond its plaintext length (nonce + tag).
+	gcmStreamBlockOverhead = gcmStreamNonceLength + gcmStreamTagLength
+
+	// gcmStreamAADPrefixLength is the length, in bytes, of the random
+	// per-file AAD prefix generated for new output files.
+	gcmStreamAADPrefixLength = 16
+)
+
+// goEnvelopeKeyMetadataVersion is the current encoding version written by
+// [GoEnvelopeEncryptionManager]. It is bumped whenever the on-disk layout of
+// goEnvelopeKeyMetadata changes incompatibly.
+const goEnvelopeKeyMetadataVersion = 1
+
+// goEnvelopeKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [GoEnvelopeEncryptionManager].
+//
+// This encoding is Go-specific, not Java's Avro-encoded StandardKeyMetadata;
+// see the [GoEnvelopeEncryptionManager] doc comment. Per the table spec,
+// DataFile/ManifestFile key_metadata is explicitly "implementation-specific";
+// what must be Iceberg AES GCM Stream compliant - and is - is the wire
+// format of the encrypted byte stream itself (magic, block framing, nonce
+// placement, and AAD; see the constants above).
+type goEnvelopeKeyMetadata struct {
+	Version    int    `json:"v"`
+	KeyID      string `json:"key-id"`
+	WrappedKey []byte `json:"wrapped-key"`
+
+	// BlockSize is the trusted plaintext block size the file was written
+	// with. It is validated bounded before any file I/O, and is what's
+	// actually used to size reads; the stream header's block-length field
+	// is untrusted (unauthenticated, attacker-influenced storage bytes) and
+	// is only compared against this value, never used directly to size an
+	// allocation.
+	BlockSize int64 `json:"block-size"`
+
+	// AADPrefix is combined with each block's little-endian index to form
+	// the AES GCM Stream additional authenticated data, binding every
+	// ciphertext block to this file and to its position so that blocks
+	// cannot be silently reordered, replayed from another file, or spliced
+	// in from elsewhere in the same file. It is not secret.
+	AADPrefix []byte `json:"aad-prefix"`
+
+	// PlaintextLength is the trusted total plaintext size used to compute
+	// the block count on read. Per the AES GCM Stream spec's "File length"
+	// note, a reader must use a length from a trusted source rather than
+	// the underlying storage's reported size, since storage size alone
+	// cannot distinguish a genuinely short file from one truncated by an
+	// attacker who does not also control this metadata.
+	PlaintextLength int64 `json:"plaintext-length"`
+}
+
+// GoEnvelopeEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks and written using the
+// Iceberg AES GCM Stream ("AGS1") format: a magic/block-length header
+// followed by independently authenticated blocks, each carrying its own
+// random nonce and authenticated with an AAD that binds it to the file and
+// to its position. This bounds memory usage and supports random access
+// (Seek/ReadAt) on the decrypted file without buffering or decrypting more
+// than the requested blocks.
+//
+// GoEnvelopeEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+//
+// Not interoperable with Java's StandardEncryptionManager: the AGS1 byte
+// stream framing (magic, block layout, nonce placement, AAD) matches the
+// spec, but the two implementations are not cross-readable. Java's reader
+// hard-requires a 1 MiB header block size (a compile-time constant there),
+// while [GoEnvelopeDefaultBlockSize] is 64 KiB, and Java decodes key
+// metadata as a 1-byte version plus Avro-encoded StandardKeyMetadata, while
+// this type encodes key metadata as JSON (goEnvelopeKeyMetadata). Files
+// written by one are not readable by the other.
+type GoEnvelopeEncryptionManager struct {
+	kms       KeyManagementClient

Review Comment:
   Added `TestGoEnvelopeEncryptionManager_BlockNoncesAreUnique` that seals the 8 identical-plaintext blocks, extracts each nonce from the AGS1 layout, asserts all 8 are pairwise distinct, and that block 0's ciphertext differs from every other block's. Mutation-verified against your exact repro: substituting a constant all-zero nonce leaves the rest of the suite green and only this test catches it.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat(encryption): add StandardEncryptionManager [iceberg-go]

Posted by "rambleraptor (via GitHub)" <gi...@apache.org>.
rambleraptor commented on PR #1620:
URL: https://github.com/apache/iceberg-go/pull/1620#issuecomment-5256772424

   @hectar-glitches are you able to make the changes on this PR? I'd love to move forward with encryption support!


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat(encryption): add StandardEncryptionManager [iceberg-go]

Posted by "hectar-glitches (via GitHub)" <gi...@apache.org>.
hectar-glitches commented on PR #1620:
URL: https://github.com/apache/iceberg-go/pull/1620#issuecomment-5295914597

   @rambleraptor @zeroshade on it! sorry for the delay
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat(encryption): add StandardEncryptionManager for generic file envelope encryption [iceberg-go]

Posted by "zeroshade (via GitHub)" <gi...@apache.org>.
zeroshade commented on code in PR #1620:
URL: https://github.com/apache/iceberg-go/pull/1620#discussion_r4257658873


##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,862 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+	"math"
+	"slices"
+	"sync"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// StandardDefaultDataKeyLength is the default length, in bytes, of the
+// per-file data encryption key (DEK). It is 128-bit, matching the default of
+// the encryption.data-key-length table property in the Java and Rust
+// implementations.
+const StandardDefaultDataKeyLength = 16
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires the table's
+	// encryption key ID; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by
+	// [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata starts
+	// with a version byte other than the one this package understands.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidStreamHeader is returned when the AES GCM Stream header (the
+	// "AGS1" magic and little-endian plain block length at the start of an
+	// encrypted file, per the Iceberg AES GCM Stream spec) is missing,
+	// truncated, or declares a block length other than the fixed 1 MiB.
+	ErrInvalidStreamHeader = errors.New("encryption: invalid AES GCM Stream header")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when key metadata is
+	// not a well-formed StandardKeyMetadata record or fails basic sanity
+	// checks (e.g. a truncated record, a missing or wrong-sized AAD prefix, or
+	// a missing or impossible file length). Key metadata is untrusted input on
+	// a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+
+	// ErrOutputFileClosed is returned by [standardOutputFile.Write] when
+	// called after a successful Close. It wraps [fs.ErrClosed] so callers can
+	// test with errors.Is(err, fs.ErrClosed). A Write after a failed flush or
+	// a failed Close returns that original error instead.
+	ErrOutputFileClosed = fmt.Errorf("encryption: write to closed StandardEncryptionManager output file: %w", fs.ErrClosed)
+
+	// ErrBlockTruncated is returned by [standardInputFile.ReadAt] when the
+	// underlying storage returns fewer ciphertext bytes for a block than its
+	// recorded length requires, indicating the file was truncated at rest.
+	// This is distinct from [ErrCiphertextTooShort], which [KeyManagementClient]
+	// implementations use for a too-short wrapped key or KMS-encrypted
+	// payload; keeping them separate lets a caller tell a malformed KMS blob
+	// apart from a short block read.
+	ErrBlockTruncated = errors.New("encryption: block truncated: read fewer ciphertext bytes than expected")
+)
+
+// Constants describing the Iceberg AES GCM Stream ("AGS1") wire format used
+// for the ciphertext produced by [StandardEncryptionManager]. See
+// https://iceberg.apache.org/gcm-stream-spec/ for the full specification.
+const (
+	// gcmStreamMagic identifies an AES GCM Stream version 1 file.
+	gcmStreamMagic = "AGS1"
+
+	// gcmStreamHeaderLength is the length, in bytes, of the magic plus the
+	// 4-byte little-endian plain block length written at the start of every
+	// file.
+	gcmStreamHeaderLength = 8
+
+	// gcmStreamPlainBlockSize is the plaintext block size. It is fixed:
+	// Java's Ciphers.PLAIN_BLOCK_SIZE and iceberg-rust's PLAIN_BLOCK_SIZE are
+	// both 1 MiB, and Java's AesGcmInputStream rejects any other value in the
+	// header, so a stream with a different block size is unreadable there.
+	gcmStreamPlainBlockSize = 1024 * 1024
+
+	// gcmStreamNonceLength is the length, in bytes, of the random AES-GCM
+	// nonce stored at the start of every cipher block.
+	gcmStreamNonceLength = 12
+
+	// gcmStreamTagLength is the length, in bytes, of the AES-GCM
+	// authentication tag appended to every cipher block's ciphertext.
+	gcmStreamTagLength = 16
+
+	// gcmStreamBlockOverhead is the number of ciphertext bytes added to
+	// each block beyond its plaintext length (nonce + tag).
+	gcmStreamBlockOverhead = gcmStreamNonceLength + gcmStreamTagLength
+
+	// gcmStreamCipherBlockSize is the on-disk length of a full block.
+	gcmStreamCipherBlockSize = gcmStreamPlainBlockSize + gcmStreamBlockOverhead
+
+	// gcmStreamMinLength is the length of the smallest valid stream: the
+	// header followed by one block holding no plaintext. Java and iceberg-rust
+	// always write block 0, even for an empty file, and iceberg-rust rejects
+	// anything shorter.
+	gcmStreamMinLength = gcmStreamHeaderLength + gcmStreamBlockOverhead
+
+	// gcmStreamAADPrefixLength is the length, in bytes, of the random
+	// per-file AAD prefix. It matches Java's ENCRYPTION_AAD_LENGTH_DEFAULT.
+	gcmStreamAADPrefixLength = 16
+)
+
+// standardKeyMetadataVersion is the leading version byte of Iceberg's
+// StandardKeyMetadata encoding.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the decoded form of Iceberg's StandardKeyMetadata:
+// a version byte followed by an Avro binary record
+//
+//	{encryption_key: bytes, aad_prefix: ["null", bytes], file_length: ["null", long]}
+//
+// This is the key_metadata encoding Java's StandardEncryptionManager,
+// iceberg-rust and pyiceberg read and write. It holds the raw DEK, so it is a
+// secret and must be protected by whatever stores it.
+type standardKeyMetadata struct {
+	encryptionKey []byte
+
+	// aadPrefix is combined with each block's little-endian index to form
+	// the AES GCM Stream additional authenticated data, binding every
+	// ciphertext block to this file and to its position so that blocks
+	// cannot be silently reordered, replayed from another file, or spliced
+	// in from elsewhere in the same file. It is not secret. It is nil when
+	// the record omits it.
+	aadPrefix []byte
+
+	// fileLength is the length of the encrypted stream, header included.
+	// Per the AES GCM Stream spec's "File length" note, a reader must take
+	// the length from a trusted source rather than the underlying storage's
+	// reported size, since storage size alone cannot distinguish a genuinely
+	// short file from one truncated by an attacker who does not also control
+	// this metadata. hasFileLength is false when the record omits it.
+	fileLength    int64
+	hasFileLength bool
+}
+
+// encodeStandardKeyMetadata encodes the version byte and Avro record for a
+// file, with both optional fields present.
+func encodeStandardKeyMetadata(encryptionKey, aadPrefix []byte, fileLength int64) EncryptionKeyMetadata {
+	b := []byte{standardKeyMetadataVersion}
+	b = binary.AppendVarint(b, int64(len(encryptionKey)))
+	b = append(b, encryptionKey...)
+	b = binary.AppendVarint(b, 1) // union branch 1 (bytes): aad_prefix is present
+	b = binary.AppendVarint(b, int64(len(aadPrefix)))
+	b = append(b, aadPrefix...)
+	b = binary.AppendVarint(b, 1) // union branch 1 (long): file_length is present
+	b = binary.AppendVarint(b, fileLength)
+
+	return b
+}
+
+// decodeStandardKeyMetadata decodes the version byte and Avro record written
+// by [encodeStandardKeyMetadata] or by Java's StandardKeyMetadata.buffer().
+func decodeStandardKeyMetadata(b []byte) (standardKeyMetadata, error) {
+	if b[0] != standardKeyMetadataVersion {
+		return standardKeyMetadata{}, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, b[0])
+	}
+
+	r := avroReader{buf: b[1:]}
+	var k standardKeyMetadata
+	k.encryptionKey = r.bytes()
+	if r.present() {
+		k.aadPrefix = r.bytes()
+	}
+	if r.present() {
+		k.fileLength = r.long()
+		k.hasFileLength = true
+	}
+	if r.err == nil && len(r.buf) != 0 {
+		r.err = fmt.Errorf("%d unexpected trailing bytes", len(r.buf))
+	}
+	if r.err != nil {
+		return standardKeyMetadata{}, fmt.Errorf("%w: %w", ErrInvalidKeyMetadata, r.err)
+	}
+
+	return k, nil
+}
+
+// avroReader decodes the few Avro binary primitives StandardKeyMetadata uses,
+// remembering the first error. Avro longs are zig-zag varints, which is what
+// encoding/binary's Varint implements.
+type avroReader struct {
+	buf []byte
+	err error
+}
+
+func (r *avroReader) long() int64 {
+	if r.err != nil {
+		return 0
+	}
+	v, n := binary.Varint(r.buf)
+	if n <= 0 {
+		r.err = errors.New("truncated or oversized varint")
+
+		return 0
+	}
+	r.buf = r.buf[n:]
+
+	return v
+}
+
+func (r *avroReader) bytes() []byte {
+	n := r.long()
+	if r.err != nil {
+		return nil
+	}
+	if n < 0 || n > int64(len(r.buf)) {
+		r.err = fmt.Errorf("bytes length %d out of range (%d bytes remain)", n, len(r.buf))
+
+		return nil
+	}
+	out := slices.Clone(r.buf[:n])
+	r.buf = r.buf[n:]
+
+	return out
+}
+
+// present reads the branch index of a ["null", T] union and reports whether
+// the value is present (branch 1) rather than null (branch 0).
+func (r *avroReader) present() bool {
+	branch := r.long()
+	if r.err != nil {
+		return false
+	}
+	if branch != 0 && branch != 1 {
+		r.err = fmt.Errorf("unexpected union branch %d", branch)
+
+		return false
+	}
+
+	return branch == 1
+}
+
+// plaintextLengthFromStreamLength derives the plaintext length from the
+// length of the encrypted stream, the way Java's
+// AesGcmInputStream.calculatePlaintextLength does. It accepts the 36-byte
+// form of an empty file (header plus one empty block) and rejects lengths no
+// writer could have produced.
+func plaintextLengthFromStreamLength(streamLength int64) (int64, error) {
+	if streamLength < gcmStreamMinLength {
+		return 0, fmt.Errorf("%w: file-length %d is shorter than the %d-byte minimum stream", ErrInvalidKeyMetadata, streamLength, gcmStreamMinLength)
+	}
+
+	body := streamLength - gcmStreamHeaderLength
+	plainLength := body / gcmStreamCipherBlockSize * gcmStreamPlainBlockSize
+	if lastBlock := body % gcmStreamCipherBlockSize; lastBlock != 0 {
+		if lastBlock < gcmStreamBlockOverhead {
+			return 0, fmt.Errorf("%w: file-length %d ends in a %d-byte block, shorter than its %d-byte nonce and tag", ErrInvalidKeyMetadata, streamLength, lastBlock, gcmStreamBlockOverhead)
+		}
+		plainLength += lastBlock - gcmStreamBlockOverhead
+	}
+
+	return plainLength, nil
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// for arbitrary files (e.g. manifests, manifest lists, Puffin statistics). It
+// reads and writes the same bytes as Java's StandardEncryptionManager,
+// iceberg-rust and pyiceberg: an Iceberg AES GCM Stream ("AGS1") with fixed
+// 1 MiB plaintext blocks, and key metadata in Iceberg's StandardKeyMetadata
+// encoding.
+//
+// Each file is encrypted under a fresh random data encryption key (DEK),
+// generated locally with no KMS call. Each block carries its own random nonce
+// and is authenticated with an AAD that binds it to the file and to its
+// position. This bounds memory usage and supports random access
+// (Seek/ReadAt) on the decrypted file without buffering or decrypting more
+// than the requested blocks.
+//
+// The key metadata returned by Close contains the raw DEK, so it is a secret:
+// persist it only where something protects it, such as a manifest or manifest
+// list that is itself encrypted under a key encryption key. Wrapping the DEK
+// that way is not done by this type.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	dataKeyLength int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithStandardDataKeyLength sets the length, in bytes, of the per-file data
+// encryption key. It corresponds to the encryption.data-key-length table
+// property. Valid AES key lengths are 16, 24, or 32 bytes; the default is
+// [StandardDefaultDataKeyLength].
+func WithStandardDataKeyLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dataKeyLength = length }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager].
+func NewStandardEncryptionManager(opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{dataKeyLength: StandardDefaultDataKeyLength}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID is the table's encryption key ID and must be non-empty; otherwise
+// [ErrKeyIDRequired] is returned. It is not recorded in the file's key
+// metadata.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(_ context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	switch m.dataKeyLength {
+	case 16, 24, 32:
+	default:
+		return nil, fmt.Errorf("%w: DEK length must be 16, 24, or 32 bytes; got %d", ErrInvalidKeyLength, m.dataKeyLength)
+	}
+
+	// A fresh DEK per file keeps the number of random-nonce encryptions under
+	// any one key within the 2^32 limit NIST SP 800-38D sets for random
+	// 96-bit nonces: a file holds at most 2^32-1 blocks.
+	dek := make([]byte, m.dataKeyLength)
+	if _, err := io.ReadFull(rand.Reader, dek); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(dek)
+	if err != nil {
+		return nil, err
+	}
+
+	aadPrefix := make([]byte, gcmStreamAADPrefixLength)
+	if _, err := io.ReadFull(rand.Reader, aadPrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate AAD prefix: %w", err)
+	}
+
+	// Write the AES GCM Stream header (magic + little-endian block length)
+	// up front, before any ciphertext blocks, per the format spec.
+	header := make([]byte, gcmStreamHeaderLength)
+	copy(header, gcmStreamMagic)
+	binary.LittleEndian.PutUint32(header[len(gcmStreamMagic):], gcmStreamPlainBlockSize)
+	if _, err := writer.Write(header); err != nil {
+		return nil, fmt.Errorf("encryption: failed to write stream header: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:      writer,
+		aead:            aead,
+		dek:             dek,
+		aadPrefix:       aadPrefix,
+		encryptedLength: gcmStreamHeaderLength,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty StandardKeyMetadata blob
+// produced by [StandardEncryptionManager.NewEncryptedOutputFile] or by another
+// Iceberg implementation; otherwise [ErrKeyMetadataRequired] is returned.
+//
+// The plaintext length is derived from the file length recorded in key
+// metadata, never from the underlying file's size. Key metadata without a file
+// length is rejected, because there is no other trusted source for it here.
+// Key metadata without an AAD prefix, which the encoding permits, is rejected
+// too: the prefix is what binds a block to its file.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(_ context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	meta, err := decodeStandardKeyMetadata(keyMetadata)
+	if err != nil {
+		return nil, err
+	}
+	// Java, iceberg-rust and this writer all emit 16-byte prefixes. Bounding
+	// it also keeps the per-block AAD allocation in readBlock small.
+	if len(meta.aadPrefix) != gcmStreamAADPrefixLength {
+		return nil, fmt.Errorf("%w: aad-prefix must be exactly %d bytes, got %d", ErrInvalidKeyMetadata, gcmStreamAADPrefixLength, len(meta.aadPrefix))
+	}
+	if !meta.hasFileLength {

Review Comment:
   **Major.** Java's `StandardEncryptionManager` writes `new StandardKeyMetadata(fileDek, aadPrefix)` with no `file_length` (`StandardEncryptionManager.java:259`). `AesGcmInputFile` then takes the encrypted length from the source `InputFile`, which `EncryptingFileIO` builds from `ManifestFile.length()` or `DataFile.fileSizeInBytes()`; only manifest lists carry `file_length`, via `copyWithLength`. So this check rejects every Java-written encrypted data file and manifest.
   
   As on 10-01: when the field is absent, the trusted length has to come from the caller (not `Stat().Size()`). `NewDecryptedInputFile` has no length parameter, so add a length-aware entry point, e.g. `(*StandardEncryptionManager).NewDecryptedInputFileWithLength(ctx, file, encryptedLength, keyMetadata)` or an `EncryptionManager`-level variant the upcoming `EncryptingFileIO` can call. Use `file_length` when present, the caller's length otherwise, and fail only when neither exists. Replace the `missing file length` test case (`standard_manager_test.go:572`) with a Java-shaped record plus caller length that reads correctly, and the same record with no length that is rejected.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,862 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+	"math"
+	"slices"
+	"sync"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// StandardDefaultDataKeyLength is the default length, in bytes, of the
+// per-file data encryption key (DEK). It is 128-bit, matching the default of
+// the encryption.data-key-length table property in the Java and Rust
+// implementations.
+const StandardDefaultDataKeyLength = 16
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires the table's
+	// encryption key ID; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by
+	// [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata starts
+	// with a version byte other than the one this package understands.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidStreamHeader is returned when the AES GCM Stream header (the
+	// "AGS1" magic and little-endian plain block length at the start of an
+	// encrypted file, per the Iceberg AES GCM Stream spec) is missing,
+	// truncated, or declares a block length other than the fixed 1 MiB.
+	ErrInvalidStreamHeader = errors.New("encryption: invalid AES GCM Stream header")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when key metadata is
+	// not a well-formed StandardKeyMetadata record or fails basic sanity
+	// checks (e.g. a truncated record, a missing or wrong-sized AAD prefix, or
+	// a missing or impossible file length). Key metadata is untrusted input on
+	// a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+
+	// ErrOutputFileClosed is returned by [standardOutputFile.Write] when
+	// called after a successful Close. It wraps [fs.ErrClosed] so callers can
+	// test with errors.Is(err, fs.ErrClosed). A Write after a failed flush or
+	// a failed Close returns that original error instead.
+	ErrOutputFileClosed = fmt.Errorf("encryption: write to closed StandardEncryptionManager output file: %w", fs.ErrClosed)
+
+	// ErrBlockTruncated is returned by [standardInputFile.ReadAt] when the
+	// underlying storage returns fewer ciphertext bytes for a block than its
+	// recorded length requires, indicating the file was truncated at rest.
+	// This is distinct from [ErrCiphertextTooShort], which [KeyManagementClient]
+	// implementations use for a too-short wrapped key or KMS-encrypted
+	// payload; keeping them separate lets a caller tell a malformed KMS blob
+	// apart from a short block read.
+	ErrBlockTruncated = errors.New("encryption: block truncated: read fewer ciphertext bytes than expected")
+)
+
+// Constants describing the Iceberg AES GCM Stream ("AGS1") wire format used
+// for the ciphertext produced by [StandardEncryptionManager]. See
+// https://iceberg.apache.org/gcm-stream-spec/ for the full specification.
+const (
+	// gcmStreamMagic identifies an AES GCM Stream version 1 file.
+	gcmStreamMagic = "AGS1"
+
+	// gcmStreamHeaderLength is the length, in bytes, of the magic plus the
+	// 4-byte little-endian plain block length written at the start of every
+	// file.
+	gcmStreamHeaderLength = 8
+
+	// gcmStreamPlainBlockSize is the plaintext block size. It is fixed:
+	// Java's Ciphers.PLAIN_BLOCK_SIZE and iceberg-rust's PLAIN_BLOCK_SIZE are
+	// both 1 MiB, and Java's AesGcmInputStream rejects any other value in the
+	// header, so a stream with a different block size is unreadable there.
+	gcmStreamPlainBlockSize = 1024 * 1024
+
+	// gcmStreamNonceLength is the length, in bytes, of the random AES-GCM
+	// nonce stored at the start of every cipher block.
+	gcmStreamNonceLength = 12
+
+	// gcmStreamTagLength is the length, in bytes, of the AES-GCM
+	// authentication tag appended to every cipher block's ciphertext.
+	gcmStreamTagLength = 16
+
+	// gcmStreamBlockOverhead is the number of ciphertext bytes added to
+	// each block beyond its plaintext length (nonce + tag).
+	gcmStreamBlockOverhead = gcmStreamNonceLength + gcmStreamTagLength
+
+	// gcmStreamCipherBlockSize is the on-disk length of a full block.
+	gcmStreamCipherBlockSize = gcmStreamPlainBlockSize + gcmStreamBlockOverhead
+
+	// gcmStreamMinLength is the length of the smallest valid stream: the
+	// header followed by one block holding no plaintext. Java and iceberg-rust
+	// always write block 0, even for an empty file, and iceberg-rust rejects
+	// anything shorter.
+	gcmStreamMinLength = gcmStreamHeaderLength + gcmStreamBlockOverhead
+
+	// gcmStreamAADPrefixLength is the length, in bytes, of the random
+	// per-file AAD prefix. It matches Java's ENCRYPTION_AAD_LENGTH_DEFAULT.
+	gcmStreamAADPrefixLength = 16
+)
+
+// standardKeyMetadataVersion is the leading version byte of Iceberg's
+// StandardKeyMetadata encoding.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the decoded form of Iceberg's StandardKeyMetadata:
+// a version byte followed by an Avro binary record
+//
+//	{encryption_key: bytes, aad_prefix: ["null", bytes], file_length: ["null", long]}
+//
+// This is the key_metadata encoding Java's StandardEncryptionManager,
+// iceberg-rust and pyiceberg read and write. It holds the raw DEK, so it is a
+// secret and must be protected by whatever stores it.
+type standardKeyMetadata struct {
+	encryptionKey []byte
+
+	// aadPrefix is combined with each block's little-endian index to form
+	// the AES GCM Stream additional authenticated data, binding every
+	// ciphertext block to this file and to its position so that blocks
+	// cannot be silently reordered, replayed from another file, or spliced
+	// in from elsewhere in the same file. It is not secret. It is nil when
+	// the record omits it.
+	aadPrefix []byte
+
+	// fileLength is the length of the encrypted stream, header included.
+	// Per the AES GCM Stream spec's "File length" note, a reader must take
+	// the length from a trusted source rather than the underlying storage's
+	// reported size, since storage size alone cannot distinguish a genuinely
+	// short file from one truncated by an attacker who does not also control
+	// this metadata. hasFileLength is false when the record omits it.
+	fileLength    int64
+	hasFileLength bool
+}
+
+// encodeStandardKeyMetadata encodes the version byte and Avro record for a
+// file, with both optional fields present.
+func encodeStandardKeyMetadata(encryptionKey, aadPrefix []byte, fileLength int64) EncryptionKeyMetadata {
+	b := []byte{standardKeyMetadataVersion}
+	b = binary.AppendVarint(b, int64(len(encryptionKey)))
+	b = append(b, encryptionKey...)
+	b = binary.AppendVarint(b, 1) // union branch 1 (bytes): aad_prefix is present
+	b = binary.AppendVarint(b, int64(len(aadPrefix)))
+	b = append(b, aadPrefix...)
+	b = binary.AppendVarint(b, 1) // union branch 1 (long): file_length is present
+	b = binary.AppendVarint(b, fileLength)
+
+	return b
+}
+
+// decodeStandardKeyMetadata decodes the version byte and Avro record written
+// by [encodeStandardKeyMetadata] or by Java's StandardKeyMetadata.buffer().
+func decodeStandardKeyMetadata(b []byte) (standardKeyMetadata, error) {
+	if b[0] != standardKeyMetadataVersion {
+		return standardKeyMetadata{}, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, b[0])
+	}
+
+	r := avroReader{buf: b[1:]}
+	var k standardKeyMetadata
+	k.encryptionKey = r.bytes()
+	if r.present() {
+		k.aadPrefix = r.bytes()
+	}
+	if r.present() {
+		k.fileLength = r.long()
+		k.hasFileLength = true
+	}
+	if r.err == nil && len(r.buf) != 0 {
+		r.err = fmt.Errorf("%d unexpected trailing bytes", len(r.buf))
+	}
+	if r.err != nil {
+		return standardKeyMetadata{}, fmt.Errorf("%w: %w", ErrInvalidKeyMetadata, r.err)
+	}
+
+	return k, nil
+}
+
+// avroReader decodes the few Avro binary primitives StandardKeyMetadata uses,
+// remembering the first error. Avro longs are zig-zag varints, which is what
+// encoding/binary's Varint implements.
+type avroReader struct {
+	buf []byte
+	err error
+}
+
+func (r *avroReader) long() int64 {
+	if r.err != nil {
+		return 0
+	}
+	v, n := binary.Varint(r.buf)
+	if n <= 0 {
+		r.err = errors.New("truncated or oversized varint")
+
+		return 0
+	}
+	r.buf = r.buf[n:]
+
+	return v
+}
+
+func (r *avroReader) bytes() []byte {
+	n := r.long()
+	if r.err != nil {
+		return nil
+	}
+	if n < 0 || n > int64(len(r.buf)) {
+		r.err = fmt.Errorf("bytes length %d out of range (%d bytes remain)", n, len(r.buf))
+
+		return nil
+	}
+	out := slices.Clone(r.buf[:n])
+	r.buf = r.buf[n:]
+
+	return out
+}
+
+// present reads the branch index of a ["null", T] union and reports whether
+// the value is present (branch 1) rather than null (branch 0).
+func (r *avroReader) present() bool {
+	branch := r.long()
+	if r.err != nil {
+		return false
+	}
+	if branch != 0 && branch != 1 {
+		r.err = fmt.Errorf("unexpected union branch %d", branch)
+
+		return false
+	}
+
+	return branch == 1
+}
+
+// plaintextLengthFromStreamLength derives the plaintext length from the
+// length of the encrypted stream, the way Java's
+// AesGcmInputStream.calculatePlaintextLength does. It accepts the 36-byte
+// form of an empty file (header plus one empty block) and rejects lengths no
+// writer could have produced.
+func plaintextLengthFromStreamLength(streamLength int64) (int64, error) {
+	if streamLength < gcmStreamMinLength {
+		return 0, fmt.Errorf("%w: file-length %d is shorter than the %d-byte minimum stream", ErrInvalidKeyMetadata, streamLength, gcmStreamMinLength)
+	}
+
+	body := streamLength - gcmStreamHeaderLength
+	plainLength := body / gcmStreamCipherBlockSize * gcmStreamPlainBlockSize
+	if lastBlock := body % gcmStreamCipherBlockSize; lastBlock != 0 {
+		if lastBlock < gcmStreamBlockOverhead {
+			return 0, fmt.Errorf("%w: file-length %d ends in a %d-byte block, shorter than its %d-byte nonce and tag", ErrInvalidKeyMetadata, streamLength, lastBlock, gcmStreamBlockOverhead)
+		}
+		plainLength += lastBlock - gcmStreamBlockOverhead
+	}
+
+	return plainLength, nil
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// for arbitrary files (e.g. manifests, manifest lists, Puffin statistics). It
+// reads and writes the same bytes as Java's StandardEncryptionManager,
+// iceberg-rust and pyiceberg: an Iceberg AES GCM Stream ("AGS1") with fixed
+// 1 MiB plaintext blocks, and key metadata in Iceberg's StandardKeyMetadata
+// encoding.
+//
+// Each file is encrypted under a fresh random data encryption key (DEK),
+// generated locally with no KMS call. Each block carries its own random nonce
+// and is authenticated with an AAD that binds it to the file and to its
+// position. This bounds memory usage and supports random access
+// (Seek/ReadAt) on the decrypted file without buffering or decrypting more
+// than the requested blocks.
+//
+// The key metadata returned by Close contains the raw DEK, so it is a secret:
+// persist it only where something protects it, such as a manifest or manifest
+// list that is itself encrypted under a key encryption key. Wrapping the DEK
+// that way is not done by this type.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	dataKeyLength int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithStandardDataKeyLength sets the length, in bytes, of the per-file data
+// encryption key. It corresponds to the encryption.data-key-length table
+// property. Valid AES key lengths are 16, 24, or 32 bytes; the default is
+// [StandardDefaultDataKeyLength].
+func WithStandardDataKeyLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dataKeyLength = length }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager].
+func NewStandardEncryptionManager(opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{dataKeyLength: StandardDefaultDataKeyLength}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID is the table's encryption key ID and must be non-empty; otherwise
+// [ErrKeyIDRequired] is returned. It is not recorded in the file's key
+// metadata.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(_ context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {

Review Comment:
   Minor: `keyID` is required but no longer used or recorded. Fine until the KEK layer lands, but the `EncryptionManager` doc (`encryption.go:116-117`) says it identifies the KEK used to wrap the DEK, which isn't true for this type yet. Please say so in this method's doc.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,862 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+	"math"
+	"slices"
+	"sync"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// StandardDefaultDataKeyLength is the default length, in bytes, of the
+// per-file data encryption key (DEK). It is 128-bit, matching the default of
+// the encryption.data-key-length table property in the Java and Rust
+// implementations.
+const StandardDefaultDataKeyLength = 16
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires the table's
+	// encryption key ID; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by
+	// [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata starts
+	// with a version byte other than the one this package understands.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidStreamHeader is returned when the AES GCM Stream header (the
+	// "AGS1" magic and little-endian plain block length at the start of an
+	// encrypted file, per the Iceberg AES GCM Stream spec) is missing,
+	// truncated, or declares a block length other than the fixed 1 MiB.
+	ErrInvalidStreamHeader = errors.New("encryption: invalid AES GCM Stream header")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when key metadata is
+	// not a well-formed StandardKeyMetadata record or fails basic sanity
+	// checks (e.g. a truncated record, a missing or wrong-sized AAD prefix, or
+	// a missing or impossible file length). Key metadata is untrusted input on
+	// a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+
+	// ErrOutputFileClosed is returned by [standardOutputFile.Write] when
+	// called after a successful Close. It wraps [fs.ErrClosed] so callers can
+	// test with errors.Is(err, fs.ErrClosed). A Write after a failed flush or
+	// a failed Close returns that original error instead.
+	ErrOutputFileClosed = fmt.Errorf("encryption: write to closed StandardEncryptionManager output file: %w", fs.ErrClosed)
+
+	// ErrBlockTruncated is returned by [standardInputFile.ReadAt] when the
+	// underlying storage returns fewer ciphertext bytes for a block than its
+	// recorded length requires, indicating the file was truncated at rest.
+	// This is distinct from [ErrCiphertextTooShort], which [KeyManagementClient]
+	// implementations use for a too-short wrapped key or KMS-encrypted
+	// payload; keeping them separate lets a caller tell a malformed KMS blob
+	// apart from a short block read.
+	ErrBlockTruncated = errors.New("encryption: block truncated: read fewer ciphertext bytes than expected")
+)
+
+// Constants describing the Iceberg AES GCM Stream ("AGS1") wire format used
+// for the ciphertext produced by [StandardEncryptionManager]. See
+// https://iceberg.apache.org/gcm-stream-spec/ for the full specification.
+const (
+	// gcmStreamMagic identifies an AES GCM Stream version 1 file.
+	gcmStreamMagic = "AGS1"
+
+	// gcmStreamHeaderLength is the length, in bytes, of the magic plus the
+	// 4-byte little-endian plain block length written at the start of every
+	// file.
+	gcmStreamHeaderLength = 8
+
+	// gcmStreamPlainBlockSize is the plaintext block size. It is fixed:
+	// Java's Ciphers.PLAIN_BLOCK_SIZE and iceberg-rust's PLAIN_BLOCK_SIZE are
+	// both 1 MiB, and Java's AesGcmInputStream rejects any other value in the
+	// header, so a stream with a different block size is unreadable there.
+	gcmStreamPlainBlockSize = 1024 * 1024
+
+	// gcmStreamNonceLength is the length, in bytes, of the random AES-GCM
+	// nonce stored at the start of every cipher block.
+	gcmStreamNonceLength = 12
+
+	// gcmStreamTagLength is the length, in bytes, of the AES-GCM
+	// authentication tag appended to every cipher block's ciphertext.
+	gcmStreamTagLength = 16
+
+	// gcmStreamBlockOverhead is the number of ciphertext bytes added to
+	// each block beyond its plaintext length (nonce + tag).
+	gcmStreamBlockOverhead = gcmStreamNonceLength + gcmStreamTagLength
+
+	// gcmStreamCipherBlockSize is the on-disk length of a full block.
+	gcmStreamCipherBlockSize = gcmStreamPlainBlockSize + gcmStreamBlockOverhead
+
+	// gcmStreamMinLength is the length of the smallest valid stream: the
+	// header followed by one block holding no plaintext. Java and iceberg-rust
+	// always write block 0, even for an empty file, and iceberg-rust rejects
+	// anything shorter.
+	gcmStreamMinLength = gcmStreamHeaderLength + gcmStreamBlockOverhead
+
+	// gcmStreamAADPrefixLength is the length, in bytes, of the random
+	// per-file AAD prefix. It matches Java's ENCRYPTION_AAD_LENGTH_DEFAULT.
+	gcmStreamAADPrefixLength = 16
+)
+
+// standardKeyMetadataVersion is the leading version byte of Iceberg's
+// StandardKeyMetadata encoding.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the decoded form of Iceberg's StandardKeyMetadata:
+// a version byte followed by an Avro binary record
+//
+//	{encryption_key: bytes, aad_prefix: ["null", bytes], file_length: ["null", long]}
+//
+// This is the key_metadata encoding Java's StandardEncryptionManager,
+// iceberg-rust and pyiceberg read and write. It holds the raw DEK, so it is a
+// secret and must be protected by whatever stores it.
+type standardKeyMetadata struct {
+	encryptionKey []byte
+
+	// aadPrefix is combined with each block's little-endian index to form
+	// the AES GCM Stream additional authenticated data, binding every
+	// ciphertext block to this file and to its position so that blocks
+	// cannot be silently reordered, replayed from another file, or spliced
+	// in from elsewhere in the same file. It is not secret. It is nil when
+	// the record omits it.
+	aadPrefix []byte
+
+	// fileLength is the length of the encrypted stream, header included.
+	// Per the AES GCM Stream spec's "File length" note, a reader must take
+	// the length from a trusted source rather than the underlying storage's
+	// reported size, since storage size alone cannot distinguish a genuinely
+	// short file from one truncated by an attacker who does not also control
+	// this metadata. hasFileLength is false when the record omits it.
+	fileLength    int64
+	hasFileLength bool
+}
+
+// encodeStandardKeyMetadata encodes the version byte and Avro record for a
+// file, with both optional fields present.
+func encodeStandardKeyMetadata(encryptionKey, aadPrefix []byte, fileLength int64) EncryptionKeyMetadata {
+	b := []byte{standardKeyMetadataVersion}
+	b = binary.AppendVarint(b, int64(len(encryptionKey)))
+	b = append(b, encryptionKey...)
+	b = binary.AppendVarint(b, 1) // union branch 1 (bytes): aad_prefix is present
+	b = binary.AppendVarint(b, int64(len(aadPrefix)))
+	b = append(b, aadPrefix...)
+	b = binary.AppendVarint(b, 1) // union branch 1 (long): file_length is present
+	b = binary.AppendVarint(b, fileLength)
+
+	return b
+}
+
+// decodeStandardKeyMetadata decodes the version byte and Avro record written
+// by [encodeStandardKeyMetadata] or by Java's StandardKeyMetadata.buffer().
+func decodeStandardKeyMetadata(b []byte) (standardKeyMetadata, error) {
+	if b[0] != standardKeyMetadataVersion {
+		return standardKeyMetadata{}, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, b[0])
+	}
+
+	r := avroReader{buf: b[1:]}
+	var k standardKeyMetadata
+	k.encryptionKey = r.bytes()
+	if r.present() {
+		k.aadPrefix = r.bytes()
+	}
+	if r.present() {
+		k.fileLength = r.long()
+		k.hasFileLength = true
+	}
+	if r.err == nil && len(r.buf) != 0 {
+		r.err = fmt.Errorf("%d unexpected trailing bytes", len(r.buf))
+	}
+	if r.err != nil {
+		return standardKeyMetadata{}, fmt.Errorf("%w: %w", ErrInvalidKeyMetadata, r.err)
+	}
+
+	return k, nil
+}
+
+// avroReader decodes the few Avro binary primitives StandardKeyMetadata uses,
+// remembering the first error. Avro longs are zig-zag varints, which is what
+// encoding/binary's Varint implements.
+type avroReader struct {
+	buf []byte
+	err error
+}
+
+func (r *avroReader) long() int64 {
+	if r.err != nil {
+		return 0
+	}
+	v, n := binary.Varint(r.buf)
+	if n <= 0 {
+		r.err = errors.New("truncated or oversized varint")
+
+		return 0
+	}
+	r.buf = r.buf[n:]
+
+	return v
+}
+
+func (r *avroReader) bytes() []byte {
+	n := r.long()
+	if r.err != nil {
+		return nil
+	}
+	if n < 0 || n > int64(len(r.buf)) {
+		r.err = fmt.Errorf("bytes length %d out of range (%d bytes remain)", n, len(r.buf))
+
+		return nil
+	}
+	out := slices.Clone(r.buf[:n])
+	r.buf = r.buf[n:]
+
+	return out
+}
+
+// present reads the branch index of a ["null", T] union and reports whether
+// the value is present (branch 1) rather than null (branch 0).
+func (r *avroReader) present() bool {
+	branch := r.long()
+	if r.err != nil {
+		return false
+	}
+	if branch != 0 && branch != 1 {
+		r.err = fmt.Errorf("unexpected union branch %d", branch)
+
+		return false
+	}
+
+	return branch == 1
+}
+
+// plaintextLengthFromStreamLength derives the plaintext length from the
+// length of the encrypted stream, the way Java's
+// AesGcmInputStream.calculatePlaintextLength does. It accepts the 36-byte
+// form of an empty file (header plus one empty block) and rejects lengths no
+// writer could have produced.
+func plaintextLengthFromStreamLength(streamLength int64) (int64, error) {
+	if streamLength < gcmStreamMinLength {
+		return 0, fmt.Errorf("%w: file-length %d is shorter than the %d-byte minimum stream", ErrInvalidKeyMetadata, streamLength, gcmStreamMinLength)
+	}
+
+	body := streamLength - gcmStreamHeaderLength
+	plainLength := body / gcmStreamCipherBlockSize * gcmStreamPlainBlockSize
+	if lastBlock := body % gcmStreamCipherBlockSize; lastBlock != 0 {
+		if lastBlock < gcmStreamBlockOverhead {
+			return 0, fmt.Errorf("%w: file-length %d ends in a %d-byte block, shorter than its %d-byte nonce and tag", ErrInvalidKeyMetadata, streamLength, lastBlock, gcmStreamBlockOverhead)
+		}
+		plainLength += lastBlock - gcmStreamBlockOverhead
+	}
+
+	return plainLength, nil
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// for arbitrary files (e.g. manifests, manifest lists, Puffin statistics). It
+// reads and writes the same bytes as Java's StandardEncryptionManager,
+// iceberg-rust and pyiceberg: an Iceberg AES GCM Stream ("AGS1") with fixed
+// 1 MiB plaintext blocks, and key metadata in Iceberg's StandardKeyMetadata
+// encoding.
+//
+// Each file is encrypted under a fresh random data encryption key (DEK),
+// generated locally with no KMS call. Each block carries its own random nonce
+// and is authenticated with an AAD that binds it to the file and to its
+// position. This bounds memory usage and supports random access
+// (Seek/ReadAt) on the decrypted file without buffering or decrypting more
+// than the requested blocks.
+//
+// The key metadata returned by Close contains the raw DEK, so it is a secret:
+// persist it only where something protects it, such as a manifest or manifest
+// list that is itself encrypted under a key encryption key. Wrapping the DEK
+// that way is not done by this type.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	dataKeyLength int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithStandardDataKeyLength sets the length, in bytes, of the per-file data
+// encryption key. It corresponds to the encryption.data-key-length table
+// property. Valid AES key lengths are 16, 24, or 32 bytes; the default is
+// [StandardDefaultDataKeyLength].
+func WithStandardDataKeyLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dataKeyLength = length }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager].
+func NewStandardEncryptionManager(opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{dataKeyLength: StandardDefaultDataKeyLength}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID is the table's encryption key ID and must be non-empty; otherwise
+// [ErrKeyIDRequired] is returned. It is not recorded in the file's key
+// metadata.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(_ context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	switch m.dataKeyLength {
+	case 16, 24, 32:
+	default:
+		return nil, fmt.Errorf("%w: DEK length must be 16, 24, or 32 bytes; got %d", ErrInvalidKeyLength, m.dataKeyLength)
+	}
+
+	// A fresh DEK per file keeps the number of random-nonce encryptions under
+	// any one key within the 2^32 limit NIST SP 800-38D sets for random
+	// 96-bit nonces: a file holds at most 2^32-1 blocks.
+	dek := make([]byte, m.dataKeyLength)
+	if _, err := io.ReadFull(rand.Reader, dek); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(dek)
+	if err != nil {
+		return nil, err
+	}
+
+	aadPrefix := make([]byte, gcmStreamAADPrefixLength)
+	if _, err := io.ReadFull(rand.Reader, aadPrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate AAD prefix: %w", err)
+	}
+
+	// Write the AES GCM Stream header (magic + little-endian block length)
+	// up front, before any ciphertext blocks, per the format spec.
+	header := make([]byte, gcmStreamHeaderLength)
+	copy(header, gcmStreamMagic)
+	binary.LittleEndian.PutUint32(header[len(gcmStreamMagic):], gcmStreamPlainBlockSize)
+	if _, err := writer.Write(header); err != nil {
+		return nil, fmt.Errorf("encryption: failed to write stream header: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:      writer,
+		aead:            aead,
+		dek:             dek,
+		aadPrefix:       aadPrefix,
+		encryptedLength: gcmStreamHeaderLength,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty StandardKeyMetadata blob
+// produced by [StandardEncryptionManager.NewEncryptedOutputFile] or by another
+// Iceberg implementation; otherwise [ErrKeyMetadataRequired] is returned.
+//
+// The plaintext length is derived from the file length recorded in key
+// metadata, never from the underlying file's size. Key metadata without a file
+// length is rejected, because there is no other trusted source for it here.
+// Key metadata without an AAD prefix, which the encoding permits, is rejected
+// too: the prefix is what binds a block to its file.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(_ context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	meta, err := decodeStandardKeyMetadata(keyMetadata)
+	if err != nil {
+		return nil, err
+	}
+	// Java, iceberg-rust and this writer all emit 16-byte prefixes. Bounding
+	// it also keeps the per-block AAD allocation in readBlock small.
+	if len(meta.aadPrefix) != gcmStreamAADPrefixLength {
+		return nil, fmt.Errorf("%w: aad-prefix must be exactly %d bytes, got %d", ErrInvalidKeyMetadata, gcmStreamAADPrefixLength, len(meta.aadPrefix))
+	}
+	if !meta.hasFileLength {
+		return nil, fmt.Errorf("%w: file-length is required; the plaintext length is not taken from the underlying file's size", ErrInvalidKeyMetadata)
+	}
+	plaintextLength, err := plaintextLengthFromStreamLength(meta.fileLength)
+	if err != nil {
+		return nil, err
+	}
+
+	aead, err := newStandardAEAD(meta.encryptionKey)
+	if err != nil {
+		return nil, err
+	}
+
+	if err := validateGCMStreamHeader(file); err != nil {
+		return nil, err
+	}
+
+	return &standardInputFile{
+		underlying:      file,
+		aead:            aead,
+		aadPrefix:       meta.aadPrefix,
+		plaintextLength: plaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newStandardAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %w", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// validateGCMStreamHeader reads the AES GCM Stream header at the start of
+// file and checks that it is the "AGS1" magic followed by the fixed 1 MiB
+// plain block length. The header is unauthenticated storage data, so it is
+// only validated here: the block size comes from [gcmStreamPlainBlockSize],
+// never from the header.
+func validateGCMStreamHeader(file icebergio.File) error {
+	header := make([]byte, gcmStreamHeaderLength)
+	n, err := file.ReadAt(header, 0)
+	if err != nil && !errors.Is(err, io.EOF) {
+		return fmt.Errorf("encryption: failed to read stream header: %w", err)
+	}
+	if n != gcmStreamHeaderLength {
+		return fmt.Errorf("%w: expected %d header bytes, got %d", ErrInvalidStreamHeader, gcmStreamHeaderLength, n)
+	}
+	if string(header[:len(gcmStreamMagic)]) != gcmStreamMagic {
+		return fmt.Errorf("%w: missing %q magic", ErrInvalidStreamHeader, gcmStreamMagic)
+	}
+
+	if blockSize := binary.LittleEndian.Uint32(header[len(gcmStreamMagic):]); blockSize != gcmStreamPlainBlockSize {
+		return fmt.Errorf("%w: block length %d, want %d", ErrInvalidStreamHeader, blockSize, gcmStreamPlainBlockSize)
+	}
+
+	return nil
+}
+
+// gcmStreamBlockAAD derives the AES-GCM additional authenticated data for
+// blockIndex: the per-file AAD prefix followed by the 4-byte little-endian
+// block index, per the Iceberg AES GCM Stream spec. GCM authenticates the AAD
+// along with the ciphertext, so a block only verifies at its own index in its
+// own file: reordered, duplicated, or spliced-in blocks fail authentication.
+func gcmStreamBlockAAD(prefix []byte, blockIndex uint32) []byte {
+	aad := make([]byte, len(prefix)+4)
+	copy(aad, prefix)
+	binary.LittleEndian.PutUint32(aad[len(prefix):], blockIndex)
+
+	return aad
+}
+
+// standardOutputFile is an [EncryptedOutputFile] that seals fixed-size
+// plaintext blocks with AES-GCM as they are written, using the Iceberg AES
+// GCM Stream ("AGS1") wire format.
+type standardOutputFile struct {
+	icebergio.FileWriter
+
+	aead      cipher.AEAD
+	dek       []byte
+	aadPrefix []byte
+
+	buf        []byte
+	blockIndex uint32
+	closed     bool
+	err        error
+
+	// encryptedLength is the number of bytes written to the underlying
+	// writer so far, header included. It becomes file_length in the key
+	// metadata, and only advances once a block has been written.
+	encryptedLength int64
+
+	// underlyingClosed records that FileWriter.Close has been called, so the
+	// underlying writer is closed at most once.
+	underlyingClosed bool
+
+	keyMetadata EncryptionKeyMetadata
+}
+
+var _ EncryptedOutputFile = (*standardOutputFile)(nil)
+
+// closeUnderlyingIgnoringError closes the underlying writer at most once.
+// The error is ignored: the caller is already reporting a more specific
+// failure (a flush error), and this is best-effort cleanup so a poisoned
+// writer never leaks its underlying file descriptor or connection.
+func (f *standardOutputFile) closeUnderlyingIgnoringError() {
+	if f.underlyingClosed {
+		return
+	}
+	f.underlyingClosed = true
+	_ = f.FileWriter.Close()
+}
+
+func (f *standardOutputFile) Write(p []byte) (int, error) {
+	if f.err != nil {
+		return 0, f.err
+	}
+	if f.closed {
+		return 0, ErrOutputFileClosed
+	}
+
+	total := len(p)
+	consumed := 0 // bytes of p appended into f.buf so far in this call
+	accepted := 0 // bytes of p known to be durably flushed; reported on failure
+	for len(p) > 0 {
+		space := gcmStreamPlainBlockSize - len(f.buf)
+		n := min(space, len(p))
+		f.buf = append(f.buf, p[:n]...)
+		p = p[n:]
+		consumed += n
+		if len(f.buf) == gcmStreamPlainBlockSize {
+			if err := f.flushBlock(); err != nil {
+				f.err = err
+				f.closeUnderlyingIgnoringError()
+
+				return accepted, err
+			}
+			accepted = consumed
+		}
+	}
+
+	return total, nil
+}
+
+// flushBlock seals and writes the currently buffered plaintext block using a
+// fresh random nonce, per the Iceberg AES GCM Stream format.
+// f.encryptedLength only advances once the ciphertext has reached the
+// underlying writer, so file_length never counts a block that failed to write.
+func (f *standardOutputFile) flushBlock() error {
+	if f.blockIndex == math.MaxUint32 {
+		return errors.New("encryption: cannot write block: exceeded maximum block count")
+	}
+
+	nonce := make([]byte, gcmStreamNonceLength)
+	if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
+		return fmt.Errorf("encryption: failed to generate block nonce: %w", err)
+	}
+
+	aad := gcmStreamBlockAAD(f.aadPrefix, f.blockIndex)
+	sealed := f.aead.Seal(nonce, nonce, f.buf, aad)

Review Comment:
   Minor: `Seal(nonce, nonce, ...)` reallocates ~1 MiB per block because `nonce` has capacity 12. Keep a `make([]byte, 0, gcmStreamCipherBlockSize)` scratch buffer on the writer, and preallocate `f.buf` to 1 MiB rather than growing it via `append`.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,862 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+	"math"
+	"slices"
+	"sync"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// StandardDefaultDataKeyLength is the default length, in bytes, of the
+// per-file data encryption key (DEK). It is 128-bit, matching the default of
+// the encryption.data-key-length table property in the Java and Rust
+// implementations.
+const StandardDefaultDataKeyLength = 16
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires the table's
+	// encryption key ID; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by
+	// [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata starts
+	// with a version byte other than the one this package understands.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidStreamHeader is returned when the AES GCM Stream header (the
+	// "AGS1" magic and little-endian plain block length at the start of an
+	// encrypted file, per the Iceberg AES GCM Stream spec) is missing,
+	// truncated, or declares a block length other than the fixed 1 MiB.
+	ErrInvalidStreamHeader = errors.New("encryption: invalid AES GCM Stream header")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when key metadata is
+	// not a well-formed StandardKeyMetadata record or fails basic sanity
+	// checks (e.g. a truncated record, a missing or wrong-sized AAD prefix, or
+	// a missing or impossible file length). Key metadata is untrusted input on
+	// a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+
+	// ErrOutputFileClosed is returned by [standardOutputFile.Write] when
+	// called after a successful Close. It wraps [fs.ErrClosed] so callers can
+	// test with errors.Is(err, fs.ErrClosed). A Write after a failed flush or
+	// a failed Close returns that original error instead.
+	ErrOutputFileClosed = fmt.Errorf("encryption: write to closed StandardEncryptionManager output file: %w", fs.ErrClosed)
+
+	// ErrBlockTruncated is returned by [standardInputFile.ReadAt] when the
+	// underlying storage returns fewer ciphertext bytes for a block than its
+	// recorded length requires, indicating the file was truncated at rest.
+	// This is distinct from [ErrCiphertextTooShort], which [KeyManagementClient]
+	// implementations use for a too-short wrapped key or KMS-encrypted
+	// payload; keeping them separate lets a caller tell a malformed KMS blob
+	// apart from a short block read.
+	ErrBlockTruncated = errors.New("encryption: block truncated: read fewer ciphertext bytes than expected")
+)
+
+// Constants describing the Iceberg AES GCM Stream ("AGS1") wire format used
+// for the ciphertext produced by [StandardEncryptionManager]. See
+// https://iceberg.apache.org/gcm-stream-spec/ for the full specification.
+const (
+	// gcmStreamMagic identifies an AES GCM Stream version 1 file.
+	gcmStreamMagic = "AGS1"
+
+	// gcmStreamHeaderLength is the length, in bytes, of the magic plus the
+	// 4-byte little-endian plain block length written at the start of every
+	// file.
+	gcmStreamHeaderLength = 8
+
+	// gcmStreamPlainBlockSize is the plaintext block size. It is fixed:
+	// Java's Ciphers.PLAIN_BLOCK_SIZE and iceberg-rust's PLAIN_BLOCK_SIZE are
+	// both 1 MiB, and Java's AesGcmInputStream rejects any other value in the
+	// header, so a stream with a different block size is unreadable there.
+	gcmStreamPlainBlockSize = 1024 * 1024
+
+	// gcmStreamNonceLength is the length, in bytes, of the random AES-GCM
+	// nonce stored at the start of every cipher block.
+	gcmStreamNonceLength = 12
+
+	// gcmStreamTagLength is the length, in bytes, of the AES-GCM
+	// authentication tag appended to every cipher block's ciphertext.
+	gcmStreamTagLength = 16
+
+	// gcmStreamBlockOverhead is the number of ciphertext bytes added to
+	// each block beyond its plaintext length (nonce + tag).
+	gcmStreamBlockOverhead = gcmStreamNonceLength + gcmStreamTagLength
+
+	// gcmStreamCipherBlockSize is the on-disk length of a full block.
+	gcmStreamCipherBlockSize = gcmStreamPlainBlockSize + gcmStreamBlockOverhead
+
+	// gcmStreamMinLength is the length of the smallest valid stream: the
+	// header followed by one block holding no plaintext. Java and iceberg-rust
+	// always write block 0, even for an empty file, and iceberg-rust rejects
+	// anything shorter.
+	gcmStreamMinLength = gcmStreamHeaderLength + gcmStreamBlockOverhead
+
+	// gcmStreamAADPrefixLength is the length, in bytes, of the random
+	// per-file AAD prefix. It matches Java's ENCRYPTION_AAD_LENGTH_DEFAULT.
+	gcmStreamAADPrefixLength = 16
+)
+
+// standardKeyMetadataVersion is the leading version byte of Iceberg's
+// StandardKeyMetadata encoding.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the decoded form of Iceberg's StandardKeyMetadata:
+// a version byte followed by an Avro binary record
+//
+//	{encryption_key: bytes, aad_prefix: ["null", bytes], file_length: ["null", long]}
+//
+// This is the key_metadata encoding Java's StandardEncryptionManager,
+// iceberg-rust and pyiceberg read and write. It holds the raw DEK, so it is a
+// secret and must be protected by whatever stores it.
+type standardKeyMetadata struct {
+	encryptionKey []byte
+
+	// aadPrefix is combined with each block's little-endian index to form
+	// the AES GCM Stream additional authenticated data, binding every
+	// ciphertext block to this file and to its position so that blocks
+	// cannot be silently reordered, replayed from another file, or spliced
+	// in from elsewhere in the same file. It is not secret. It is nil when
+	// the record omits it.
+	aadPrefix []byte
+
+	// fileLength is the length of the encrypted stream, header included.
+	// Per the AES GCM Stream spec's "File length" note, a reader must take
+	// the length from a trusted source rather than the underlying storage's
+	// reported size, since storage size alone cannot distinguish a genuinely
+	// short file from one truncated by an attacker who does not also control
+	// this metadata. hasFileLength is false when the record omits it.
+	fileLength    int64
+	hasFileLength bool
+}
+
+// encodeStandardKeyMetadata encodes the version byte and Avro record for a
+// file, with both optional fields present.
+func encodeStandardKeyMetadata(encryptionKey, aadPrefix []byte, fileLength int64) EncryptionKeyMetadata {
+	b := []byte{standardKeyMetadataVersion}
+	b = binary.AppendVarint(b, int64(len(encryptionKey)))
+	b = append(b, encryptionKey...)
+	b = binary.AppendVarint(b, 1) // union branch 1 (bytes): aad_prefix is present
+	b = binary.AppendVarint(b, int64(len(aadPrefix)))
+	b = append(b, aadPrefix...)
+	b = binary.AppendVarint(b, 1) // union branch 1 (long): file_length is present
+	b = binary.AppendVarint(b, fileLength)
+
+	return b
+}
+
+// decodeStandardKeyMetadata decodes the version byte and Avro record written
+// by [encodeStandardKeyMetadata] or by Java's StandardKeyMetadata.buffer().
+func decodeStandardKeyMetadata(b []byte) (standardKeyMetadata, error) {
+	if b[0] != standardKeyMetadataVersion {
+		return standardKeyMetadata{}, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, b[0])
+	}
+
+	r := avroReader{buf: b[1:]}
+	var k standardKeyMetadata
+	k.encryptionKey = r.bytes()
+	if r.present() {
+		k.aadPrefix = r.bytes()
+	}
+	if r.present() {
+		k.fileLength = r.long()
+		k.hasFileLength = true
+	}
+	if r.err == nil && len(r.buf) != 0 {
+		r.err = fmt.Errorf("%d unexpected trailing bytes", len(r.buf))
+	}
+	if r.err != nil {
+		return standardKeyMetadata{}, fmt.Errorf("%w: %w", ErrInvalidKeyMetadata, r.err)
+	}
+
+	return k, nil
+}
+
+// avroReader decodes the few Avro binary primitives StandardKeyMetadata uses,
+// remembering the first error. Avro longs are zig-zag varints, which is what
+// encoding/binary's Varint implements.
+type avroReader struct {
+	buf []byte
+	err error
+}
+
+func (r *avroReader) long() int64 {
+	if r.err != nil {
+		return 0
+	}
+	v, n := binary.Varint(r.buf)
+	if n <= 0 {
+		r.err = errors.New("truncated or oversized varint")
+
+		return 0
+	}
+	r.buf = r.buf[n:]
+
+	return v
+}
+
+func (r *avroReader) bytes() []byte {
+	n := r.long()
+	if r.err != nil {
+		return nil
+	}
+	if n < 0 || n > int64(len(r.buf)) {
+		r.err = fmt.Errorf("bytes length %d out of range (%d bytes remain)", n, len(r.buf))
+
+		return nil
+	}
+	out := slices.Clone(r.buf[:n])
+	r.buf = r.buf[n:]
+
+	return out
+}
+
+// present reads the branch index of a ["null", T] union and reports whether
+// the value is present (branch 1) rather than null (branch 0).
+func (r *avroReader) present() bool {
+	branch := r.long()
+	if r.err != nil {
+		return false
+	}
+	if branch != 0 && branch != 1 {
+		r.err = fmt.Errorf("unexpected union branch %d", branch)
+
+		return false
+	}
+
+	return branch == 1
+}
+
+// plaintextLengthFromStreamLength derives the plaintext length from the
+// length of the encrypted stream, the way Java's
+// AesGcmInputStream.calculatePlaintextLength does. It accepts the 36-byte
+// form of an empty file (header plus one empty block) and rejects lengths no
+// writer could have produced.
+func plaintextLengthFromStreamLength(streamLength int64) (int64, error) {
+	if streamLength < gcmStreamMinLength {
+		return 0, fmt.Errorf("%w: file-length %d is shorter than the %d-byte minimum stream", ErrInvalidKeyMetadata, streamLength, gcmStreamMinLength)
+	}
+
+	body := streamLength - gcmStreamHeaderLength
+	plainLength := body / gcmStreamCipherBlockSize * gcmStreamPlainBlockSize
+	if lastBlock := body % gcmStreamCipherBlockSize; lastBlock != 0 {
+		if lastBlock < gcmStreamBlockOverhead {
+			return 0, fmt.Errorf("%w: file-length %d ends in a %d-byte block, shorter than its %d-byte nonce and tag", ErrInvalidKeyMetadata, streamLength, lastBlock, gcmStreamBlockOverhead)
+		}
+		plainLength += lastBlock - gcmStreamBlockOverhead
+	}
+
+	return plainLength, nil
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// for arbitrary files (e.g. manifests, manifest lists, Puffin statistics). It
+// reads and writes the same bytes as Java's StandardEncryptionManager,
+// iceberg-rust and pyiceberg: an Iceberg AES GCM Stream ("AGS1") with fixed
+// 1 MiB plaintext blocks, and key metadata in Iceberg's StandardKeyMetadata
+// encoding.
+//
+// Each file is encrypted under a fresh random data encryption key (DEK),
+// generated locally with no KMS call. Each block carries its own random nonce
+// and is authenticated with an AAD that binds it to the file and to its
+// position. This bounds memory usage and supports random access
+// (Seek/ReadAt) on the decrypted file without buffering or decrypting more
+// than the requested blocks.
+//
+// The key metadata returned by Close contains the raw DEK, so it is a secret:
+// persist it only where something protects it, such as a manifest or manifest
+// list that is itself encrypted under a key encryption key. Wrapping the DEK
+// that way is not done by this type.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	dataKeyLength int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithStandardDataKeyLength sets the length, in bytes, of the per-file data
+// encryption key. It corresponds to the encryption.data-key-length table
+// property. Valid AES key lengths are 16, 24, or 32 bytes; the default is
+// [StandardDefaultDataKeyLength].
+func WithStandardDataKeyLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dataKeyLength = length }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager].
+func NewStandardEncryptionManager(opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{dataKeyLength: StandardDefaultDataKeyLength}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID is the table's encryption key ID and must be non-empty; otherwise
+// [ErrKeyIDRequired] is returned. It is not recorded in the file's key
+// metadata.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(_ context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	switch m.dataKeyLength {
+	case 16, 24, 32:
+	default:
+		return nil, fmt.Errorf("%w: DEK length must be 16, 24, or 32 bytes; got %d", ErrInvalidKeyLength, m.dataKeyLength)
+	}
+
+	// A fresh DEK per file keeps the number of random-nonce encryptions under
+	// any one key within the 2^32 limit NIST SP 800-38D sets for random
+	// 96-bit nonces: a file holds at most 2^32-1 blocks.
+	dek := make([]byte, m.dataKeyLength)
+	if _, err := io.ReadFull(rand.Reader, dek); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(dek)
+	if err != nil {
+		return nil, err
+	}
+
+	aadPrefix := make([]byte, gcmStreamAADPrefixLength)
+	if _, err := io.ReadFull(rand.Reader, aadPrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate AAD prefix: %w", err)
+	}
+
+	// Write the AES GCM Stream header (magic + little-endian block length)
+	// up front, before any ciphertext blocks, per the format spec.
+	header := make([]byte, gcmStreamHeaderLength)
+	copy(header, gcmStreamMagic)
+	binary.LittleEndian.PutUint32(header[len(gcmStreamMagic):], gcmStreamPlainBlockSize)
+	if _, err := writer.Write(header); err != nil {

Review Comment:
   Minor (carried from 09-02): if the header write fails, `writer` isn't closed, unlike the other failure paths.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,862 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+	"math"
+	"slices"
+	"sync"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// StandardDefaultDataKeyLength is the default length, in bytes, of the
+// per-file data encryption key (DEK). It is 128-bit, matching the default of
+// the encryption.data-key-length table property in the Java and Rust
+// implementations.
+const StandardDefaultDataKeyLength = 16
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires the table's
+	// encryption key ID; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by
+	// [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata starts
+	// with a version byte other than the one this package understands.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidStreamHeader is returned when the AES GCM Stream header (the
+	// "AGS1" magic and little-endian plain block length at the start of an
+	// encrypted file, per the Iceberg AES GCM Stream spec) is missing,
+	// truncated, or declares a block length other than the fixed 1 MiB.
+	ErrInvalidStreamHeader = errors.New("encryption: invalid AES GCM Stream header")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when key metadata is
+	// not a well-formed StandardKeyMetadata record or fails basic sanity
+	// checks (e.g. a truncated record, a missing or wrong-sized AAD prefix, or
+	// a missing or impossible file length). Key metadata is untrusted input on
+	// a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+
+	// ErrOutputFileClosed is returned by [standardOutputFile.Write] when
+	// called after a successful Close. It wraps [fs.ErrClosed] so callers can
+	// test with errors.Is(err, fs.ErrClosed). A Write after a failed flush or
+	// a failed Close returns that original error instead.
+	ErrOutputFileClosed = fmt.Errorf("encryption: write to closed StandardEncryptionManager output file: %w", fs.ErrClosed)
+
+	// ErrBlockTruncated is returned by [standardInputFile.ReadAt] when the
+	// underlying storage returns fewer ciphertext bytes for a block than its
+	// recorded length requires, indicating the file was truncated at rest.
+	// This is distinct from [ErrCiphertextTooShort], which [KeyManagementClient]
+	// implementations use for a too-short wrapped key or KMS-encrypted
+	// payload; keeping them separate lets a caller tell a malformed KMS blob
+	// apart from a short block read.
+	ErrBlockTruncated = errors.New("encryption: block truncated: read fewer ciphertext bytes than expected")
+)
+
+// Constants describing the Iceberg AES GCM Stream ("AGS1") wire format used
+// for the ciphertext produced by [StandardEncryptionManager]. See
+// https://iceberg.apache.org/gcm-stream-spec/ for the full specification.
+const (
+	// gcmStreamMagic identifies an AES GCM Stream version 1 file.
+	gcmStreamMagic = "AGS1"
+
+	// gcmStreamHeaderLength is the length, in bytes, of the magic plus the
+	// 4-byte little-endian plain block length written at the start of every
+	// file.
+	gcmStreamHeaderLength = 8
+
+	// gcmStreamPlainBlockSize is the plaintext block size. It is fixed:
+	// Java's Ciphers.PLAIN_BLOCK_SIZE and iceberg-rust's PLAIN_BLOCK_SIZE are
+	// both 1 MiB, and Java's AesGcmInputStream rejects any other value in the
+	// header, so a stream with a different block size is unreadable there.
+	gcmStreamPlainBlockSize = 1024 * 1024
+
+	// gcmStreamNonceLength is the length, in bytes, of the random AES-GCM
+	// nonce stored at the start of every cipher block.
+	gcmStreamNonceLength = 12
+
+	// gcmStreamTagLength is the length, in bytes, of the AES-GCM
+	// authentication tag appended to every cipher block's ciphertext.
+	gcmStreamTagLength = 16
+
+	// gcmStreamBlockOverhead is the number of ciphertext bytes added to
+	// each block beyond its plaintext length (nonce + tag).
+	gcmStreamBlockOverhead = gcmStreamNonceLength + gcmStreamTagLength
+
+	// gcmStreamCipherBlockSize is the on-disk length of a full block.
+	gcmStreamCipherBlockSize = gcmStreamPlainBlockSize + gcmStreamBlockOverhead
+
+	// gcmStreamMinLength is the length of the smallest valid stream: the
+	// header followed by one block holding no plaintext. Java and iceberg-rust
+	// always write block 0, even for an empty file, and iceberg-rust rejects
+	// anything shorter.
+	gcmStreamMinLength = gcmStreamHeaderLength + gcmStreamBlockOverhead
+
+	// gcmStreamAADPrefixLength is the length, in bytes, of the random
+	// per-file AAD prefix. It matches Java's ENCRYPTION_AAD_LENGTH_DEFAULT.
+	gcmStreamAADPrefixLength = 16
+)
+
+// standardKeyMetadataVersion is the leading version byte of Iceberg's
+// StandardKeyMetadata encoding.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the decoded form of Iceberg's StandardKeyMetadata:
+// a version byte followed by an Avro binary record
+//
+//	{encryption_key: bytes, aad_prefix: ["null", bytes], file_length: ["null", long]}
+//
+// This is the key_metadata encoding Java's StandardEncryptionManager,
+// iceberg-rust and pyiceberg read and write. It holds the raw DEK, so it is a
+// secret and must be protected by whatever stores it.
+type standardKeyMetadata struct {
+	encryptionKey []byte
+
+	// aadPrefix is combined with each block's little-endian index to form
+	// the AES GCM Stream additional authenticated data, binding every
+	// ciphertext block to this file and to its position so that blocks
+	// cannot be silently reordered, replayed from another file, or spliced
+	// in from elsewhere in the same file. It is not secret. It is nil when
+	// the record omits it.
+	aadPrefix []byte
+
+	// fileLength is the length of the encrypted stream, header included.
+	// Per the AES GCM Stream spec's "File length" note, a reader must take
+	// the length from a trusted source rather than the underlying storage's
+	// reported size, since storage size alone cannot distinguish a genuinely
+	// short file from one truncated by an attacker who does not also control
+	// this metadata. hasFileLength is false when the record omits it.
+	fileLength    int64
+	hasFileLength bool
+}
+
+// encodeStandardKeyMetadata encodes the version byte and Avro record for a
+// file, with both optional fields present.
+func encodeStandardKeyMetadata(encryptionKey, aadPrefix []byte, fileLength int64) EncryptionKeyMetadata {
+	b := []byte{standardKeyMetadataVersion}
+	b = binary.AppendVarint(b, int64(len(encryptionKey)))
+	b = append(b, encryptionKey...)
+	b = binary.AppendVarint(b, 1) // union branch 1 (bytes): aad_prefix is present
+	b = binary.AppendVarint(b, int64(len(aadPrefix)))
+	b = append(b, aadPrefix...)
+	b = binary.AppendVarint(b, 1) // union branch 1 (long): file_length is present
+	b = binary.AppendVarint(b, fileLength)
+
+	return b
+}
+
+// decodeStandardKeyMetadata decodes the version byte and Avro record written
+// by [encodeStandardKeyMetadata] or by Java's StandardKeyMetadata.buffer().
+func decodeStandardKeyMetadata(b []byte) (standardKeyMetadata, error) {
+	if b[0] != standardKeyMetadataVersion {
+		return standardKeyMetadata{}, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, b[0])
+	}
+
+	r := avroReader{buf: b[1:]}
+	var k standardKeyMetadata
+	k.encryptionKey = r.bytes()
+	if r.present() {
+		k.aadPrefix = r.bytes()
+	}
+	if r.present() {
+		k.fileLength = r.long()
+		k.hasFileLength = true
+	}
+	if r.err == nil && len(r.buf) != 0 {
+		r.err = fmt.Errorf("%d unexpected trailing bytes", len(r.buf))
+	}
+	if r.err != nil {
+		return standardKeyMetadata{}, fmt.Errorf("%w: %w", ErrInvalidKeyMetadata, r.err)
+	}
+
+	return k, nil
+}
+
+// avroReader decodes the few Avro binary primitives StandardKeyMetadata uses,
+// remembering the first error. Avro longs are zig-zag varints, which is what
+// encoding/binary's Varint implements.
+type avroReader struct {
+	buf []byte
+	err error
+}
+
+func (r *avroReader) long() int64 {
+	if r.err != nil {
+		return 0
+	}
+	v, n := binary.Varint(r.buf)
+	if n <= 0 {
+		r.err = errors.New("truncated or oversized varint")
+
+		return 0
+	}
+	r.buf = r.buf[n:]
+
+	return v
+}
+
+func (r *avroReader) bytes() []byte {
+	n := r.long()
+	if r.err != nil {
+		return nil
+	}
+	if n < 0 || n > int64(len(r.buf)) {
+		r.err = fmt.Errorf("bytes length %d out of range (%d bytes remain)", n, len(r.buf))
+
+		return nil
+	}
+	out := slices.Clone(r.buf[:n])
+	r.buf = r.buf[n:]
+
+	return out
+}
+
+// present reads the branch index of a ["null", T] union and reports whether
+// the value is present (branch 1) rather than null (branch 0).
+func (r *avroReader) present() bool {
+	branch := r.long()
+	if r.err != nil {
+		return false
+	}
+	if branch != 0 && branch != 1 {
+		r.err = fmt.Errorf("unexpected union branch %d", branch)
+
+		return false
+	}
+
+	return branch == 1
+}
+
+// plaintextLengthFromStreamLength derives the plaintext length from the
+// length of the encrypted stream, the way Java's
+// AesGcmInputStream.calculatePlaintextLength does. It accepts the 36-byte
+// form of an empty file (header plus one empty block) and rejects lengths no
+// writer could have produced.
+func plaintextLengthFromStreamLength(streamLength int64) (int64, error) {
+	if streamLength < gcmStreamMinLength {
+		return 0, fmt.Errorf("%w: file-length %d is shorter than the %d-byte minimum stream", ErrInvalidKeyMetadata, streamLength, gcmStreamMinLength)
+	}
+
+	body := streamLength - gcmStreamHeaderLength
+	plainLength := body / gcmStreamCipherBlockSize * gcmStreamPlainBlockSize
+	if lastBlock := body % gcmStreamCipherBlockSize; lastBlock != 0 {
+		if lastBlock < gcmStreamBlockOverhead {
+			return 0, fmt.Errorf("%w: file-length %d ends in a %d-byte block, shorter than its %d-byte nonce and tag", ErrInvalidKeyMetadata, streamLength, lastBlock, gcmStreamBlockOverhead)
+		}
+		plainLength += lastBlock - gcmStreamBlockOverhead
+	}
+
+	return plainLength, nil
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// for arbitrary files (e.g. manifests, manifest lists, Puffin statistics). It
+// reads and writes the same bytes as Java's StandardEncryptionManager,
+// iceberg-rust and pyiceberg: an Iceberg AES GCM Stream ("AGS1") with fixed
+// 1 MiB plaintext blocks, and key metadata in Iceberg's StandardKeyMetadata
+// encoding.
+//
+// Each file is encrypted under a fresh random data encryption key (DEK),
+// generated locally with no KMS call. Each block carries its own random nonce
+// and is authenticated with an AAD that binds it to the file and to its
+// position. This bounds memory usage and supports random access
+// (Seek/ReadAt) on the decrypted file without buffering or decrypting more
+// than the requested blocks.
+//
+// The key metadata returned by Close contains the raw DEK, so it is a secret:
+// persist it only where something protects it, such as a manifest or manifest
+// list that is itself encrypted under a key encryption key. Wrapping the DEK
+// that way is not done by this type.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	dataKeyLength int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithStandardDataKeyLength sets the length, in bytes, of the per-file data
+// encryption key. It corresponds to the encryption.data-key-length table
+// property. Valid AES key lengths are 16, 24, or 32 bytes; the default is
+// [StandardDefaultDataKeyLength].
+func WithStandardDataKeyLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dataKeyLength = length }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager].
+func NewStandardEncryptionManager(opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{dataKeyLength: StandardDefaultDataKeyLength}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID is the table's encryption key ID and must be non-empty; otherwise
+// [ErrKeyIDRequired] is returned. It is not recorded in the file's key
+// metadata.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(_ context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	switch m.dataKeyLength {
+	case 16, 24, 32:
+	default:
+		return nil, fmt.Errorf("%w: DEK length must be 16, 24, or 32 bytes; got %d", ErrInvalidKeyLength, m.dataKeyLength)
+	}
+
+	// A fresh DEK per file keeps the number of random-nonce encryptions under
+	// any one key within the 2^32 limit NIST SP 800-38D sets for random
+	// 96-bit nonces: a file holds at most 2^32-1 blocks.
+	dek := make([]byte, m.dataKeyLength)
+	if _, err := io.ReadFull(rand.Reader, dek); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(dek)
+	if err != nil {
+		return nil, err
+	}
+
+	aadPrefix := make([]byte, gcmStreamAADPrefixLength)
+	if _, err := io.ReadFull(rand.Reader, aadPrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate AAD prefix: %w", err)
+	}
+
+	// Write the AES GCM Stream header (magic + little-endian block length)
+	// up front, before any ciphertext blocks, per the format spec.
+	header := make([]byte, gcmStreamHeaderLength)
+	copy(header, gcmStreamMagic)
+	binary.LittleEndian.PutUint32(header[len(gcmStreamMagic):], gcmStreamPlainBlockSize)
+	if _, err := writer.Write(header); err != nil {
+		return nil, fmt.Errorf("encryption: failed to write stream header: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:      writer,
+		aead:            aead,
+		dek:             dek,
+		aadPrefix:       aadPrefix,
+		encryptedLength: gcmStreamHeaderLength,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty StandardKeyMetadata blob
+// produced by [StandardEncryptionManager.NewEncryptedOutputFile] or by another
+// Iceberg implementation; otherwise [ErrKeyMetadataRequired] is returned.
+//
+// The plaintext length is derived from the file length recorded in key
+// metadata, never from the underlying file's size. Key metadata without a file
+// length is rejected, because there is no other trusted source for it here.
+// Key metadata without an AAD prefix, which the encoding permits, is rejected
+// too: the prefix is what binds a block to its file.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(_ context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	meta, err := decodeStandardKeyMetadata(keyMetadata)
+	if err != nil {
+		return nil, err
+	}
+	// Java, iceberg-rust and this writer all emit 16-byte prefixes. Bounding
+	// it also keeps the per-block AAD allocation in readBlock small.
+	if len(meta.aadPrefix) != gcmStreamAADPrefixLength {
+		return nil, fmt.Errorf("%w: aad-prefix must be exactly %d bytes, got %d", ErrInvalidKeyMetadata, gcmStreamAADPrefixLength, len(meta.aadPrefix))
+	}
+	if !meta.hasFileLength {
+		return nil, fmt.Errorf("%w: file-length is required; the plaintext length is not taken from the underlying file's size", ErrInvalidKeyMetadata)
+	}
+	plaintextLength, err := plaintextLengthFromStreamLength(meta.fileLength)
+	if err != nil {
+		return nil, err
+	}
+
+	aead, err := newStandardAEAD(meta.encryptionKey)
+	if err != nil {
+		return nil, err
+	}
+
+	if err := validateGCMStreamHeader(file); err != nil {
+		return nil, err
+	}
+
+	return &standardInputFile{
+		underlying:      file,
+		aead:            aead,
+		aadPrefix:       meta.aadPrefix,
+		plaintextLength: plaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newStandardAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %w", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// validateGCMStreamHeader reads the AES GCM Stream header at the start of
+// file and checks that it is the "AGS1" magic followed by the fixed 1 MiB
+// plain block length. The header is unauthenticated storage data, so it is
+// only validated here: the block size comes from [gcmStreamPlainBlockSize],
+// never from the header.
+func validateGCMStreamHeader(file icebergio.File) error {
+	header := make([]byte, gcmStreamHeaderLength)
+	n, err := file.ReadAt(header, 0)
+	if err != nil && !errors.Is(err, io.EOF) {
+		return fmt.Errorf("encryption: failed to read stream header: %w", err)
+	}
+	if n != gcmStreamHeaderLength {
+		return fmt.Errorf("%w: expected %d header bytes, got %d", ErrInvalidStreamHeader, gcmStreamHeaderLength, n)
+	}
+	if string(header[:len(gcmStreamMagic)]) != gcmStreamMagic {
+		return fmt.Errorf("%w: missing %q magic", ErrInvalidStreamHeader, gcmStreamMagic)
+	}
+
+	if blockSize := binary.LittleEndian.Uint32(header[len(gcmStreamMagic):]); blockSize != gcmStreamPlainBlockSize {
+		return fmt.Errorf("%w: block length %d, want %d", ErrInvalidStreamHeader, blockSize, gcmStreamPlainBlockSize)
+	}
+
+	return nil
+}
+
+// gcmStreamBlockAAD derives the AES-GCM additional authenticated data for
+// blockIndex: the per-file AAD prefix followed by the 4-byte little-endian
+// block index, per the Iceberg AES GCM Stream spec. GCM authenticates the AAD
+// along with the ciphertext, so a block only verifies at its own index in its
+// own file: reordered, duplicated, or spliced-in blocks fail authentication.
+func gcmStreamBlockAAD(prefix []byte, blockIndex uint32) []byte {
+	aad := make([]byte, len(prefix)+4)
+	copy(aad, prefix)
+	binary.LittleEndian.PutUint32(aad[len(prefix):], blockIndex)
+
+	return aad
+}
+
+// standardOutputFile is an [EncryptedOutputFile] that seals fixed-size
+// plaintext blocks with AES-GCM as they are written, using the Iceberg AES
+// GCM Stream ("AGS1") wire format.
+type standardOutputFile struct {
+	icebergio.FileWriter
+
+	aead      cipher.AEAD
+	dek       []byte
+	aadPrefix []byte
+
+	buf        []byte
+	blockIndex uint32
+	closed     bool
+	err        error
+
+	// encryptedLength is the number of bytes written to the underlying
+	// writer so far, header included. It becomes file_length in the key
+	// metadata, and only advances once a block has been written.
+	encryptedLength int64
+
+	// underlyingClosed records that FileWriter.Close has been called, so the
+	// underlying writer is closed at most once.
+	underlyingClosed bool
+
+	keyMetadata EncryptionKeyMetadata
+}
+
+var _ EncryptedOutputFile = (*standardOutputFile)(nil)
+
+// closeUnderlyingIgnoringError closes the underlying writer at most once.
+// The error is ignored: the caller is already reporting a more specific
+// failure (a flush error), and this is best-effort cleanup so a poisoned
+// writer never leaks its underlying file descriptor or connection.
+func (f *standardOutputFile) closeUnderlyingIgnoringError() {
+	if f.underlyingClosed {
+		return
+	}
+	f.underlyingClosed = true
+	_ = f.FileWriter.Close()
+}
+
+func (f *standardOutputFile) Write(p []byte) (int, error) {
+	if f.err != nil {
+		return 0, f.err
+	}
+	if f.closed {
+		return 0, ErrOutputFileClosed
+	}
+
+	total := len(p)
+	consumed := 0 // bytes of p appended into f.buf so far in this call
+	accepted := 0 // bytes of p known to be durably flushed; reported on failure
+	for len(p) > 0 {
+		space := gcmStreamPlainBlockSize - len(f.buf)
+		n := min(space, len(p))
+		f.buf = append(f.buf, p[:n]...)
+		p = p[n:]
+		consumed += n
+		if len(f.buf) == gcmStreamPlainBlockSize {
+			if err := f.flushBlock(); err != nil {
+				f.err = err
+				f.closeUnderlyingIgnoringError()
+
+				return accepted, err
+			}
+			accepted = consumed
+		}
+	}
+
+	return total, nil
+}
+
+// flushBlock seals and writes the currently buffered plaintext block using a
+// fresh random nonce, per the Iceberg AES GCM Stream format.
+// f.encryptedLength only advances once the ciphertext has reached the
+// underlying writer, so file_length never counts a block that failed to write.
+func (f *standardOutputFile) flushBlock() error {
+	if f.blockIndex == math.MaxUint32 {
+		return errors.New("encryption: cannot write block: exceeded maximum block count")
+	}
+
+	nonce := make([]byte, gcmStreamNonceLength)
+	if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
+		return fmt.Errorf("encryption: failed to generate block nonce: %w", err)
+	}
+
+	aad := gcmStreamBlockAAD(f.aadPrefix, f.blockIndex)
+	sealed := f.aead.Seal(nonce, nonce, f.buf, aad)
+	if _, err := f.FileWriter.Write(sealed); err != nil {
+		return fmt.Errorf("encryption: failed to write encrypted block: %w", err)
+	}
+	f.encryptedLength += int64(len(sealed))
+	f.blockIndex++
+	f.buf = f.buf[:0]
+
+	return nil
+}
+
+// ReadFrom copies from r, encrypting as data is written, satisfying
+// io.ReaderFrom (required by [icebergio.FileWriter]).
+func (f *standardOutputFile) ReadFrom(r io.Reader) (int64, error) {
+	buf := make([]byte, gcmStreamPlainBlockSize)
+	var total int64
+	for {
+		n, err := r.Read(buf)
+		if n > 0 {
+			wn, werr := f.Write(buf[:n])
+			total += int64(wn)
+			if werr != nil {
+				return total, werr
+			}
+		}
+		if err == io.EOF {
+			break
+		}
+		if err != nil {
+			return total, err
+		}
+	}
+
+	return total, nil
+}
+
+// Close flushes any buffered partial block, writes an empty block 0 if the
+// file is empty, and finalizes the key metadata. closed is set, and
+// keyMetadata published, only once everything, including the underlying
+// Close, has succeeded. A failed Close poisons the writer (via f.err): a retry
+// returns the same error, and no key metadata is exposed for an output that
+// never finished.
+func (f *standardOutputFile) Close() error {
+	if f.err != nil {
+		return f.err
+	}
+	if f.closed {
+		return nil
+	}
+
+	// Java and iceberg-rust write block 0 even when the file is empty, so an
+	// empty file is 36 bytes (a header plus one 28-byte block), and
+	// iceberg-rust rejects anything shorter. Match them.
+	if len(f.buf) > 0 || f.blockIndex == 0 {
+		if err := f.flushBlock(); err != nil {
+			f.err = err
+			f.closeUnderlyingIgnoringError()
+
+			return err
+		}
+	}
+
+	if err := f.FileWriter.Close(); err != nil {
+		f.underlyingClosed = true
+		f.err = fmt.Errorf("encryption: failed to close underlying writer: %w", err)
+
+		return f.err
+	}
+	f.underlyingClosed = true
+
+	f.keyMetadata = encodeStandardKeyMetadata(f.dek, f.aadPrefix, f.encryptedLength)
+	f.closed = true
+
+	return nil
+}
+
+// KeyMetadata returns the finalized per-file key metadata. It is only
+// populated after Close has succeeded. It contains the raw DEK.
+func (f *standardOutputFile) KeyMetadata() EncryptionKeyMetadata { return f.keyMetadata }
+
+// standardInputFile is an [EncryptedInputFile] that decrypts fixed-size
+// AES-GCM blocks on demand, supporting random access via ReadAt/Seek.
+//
+// The plaintext length comes from the trusted file length in key metadata, so
+// ciphertext appended after the last block is ignored, and truncating the
+// ciphertext while also editing that metadata cannot be detected. Both follow
+// from the AES GCM Stream spec's "File length" rule.
+//
+// ReadAt is safe, and intended, for concurrent use, matching the io.ReaderAt
+// contract: readBlock only holds cacheMu around the cache check/publish, not
+// across the underlying ReadAt or AEAD decryption, so concurrent calls for
+// distinct blocks run in parallel. A lost cache race (two goroutines
+// decrypting the same block) is harmless, just wasted work. Read and Seek
+// mutate the shared cursor (pos) and are not concurrent-safe; do not call them
+// from multiple goroutines on the same instance.
+//
+// The single-entry cache retains one decrypted block (1 MiB) for the lifetime
+// of the input file, not just the lifetime of a single read call.
+type standardInputFile struct {
+	underlying      icebergio.File
+	aead            cipher.AEAD
+	aadPrefix       []byte
+	plaintextLength int64
+	keyMetadata     EncryptionKeyMetadata
+
+	pos int64
+
+	// cacheMu guards cacheIdx/cacheBlock/cacheValid below. It is only held
+	// around the cache check and the cache publish, never across the
+	// underlying ReadAt or AEAD decryption in readBlock.
+	cacheMu    sync.Mutex
+	cacheIdx   int64
+	cacheBlock []byte
+	cacheValid bool
+}
+
+var _ EncryptedInputFile = (*standardInputFile)(nil)
+
+func (f *standardInputFile) numBlocks() int64 {
+	if f.plaintextLength == 0 {
+		return 0
+	}
+
+	// plaintextLength is derived from a file length in key metadata, so it
+	// can be close to math.MaxInt64; 1 + (n-1)/size avoids the overflow that
+	// (n + size - 1)/size would hit there.
+	return 1 + (f.plaintextLength-1)/gcmStreamPlainBlockSize
+}
+
+// blockPlainLen returns the plaintext length of block idx, given the total
+// number of blocks.
+func (f *standardInputFile) blockPlainLen(idx, numBlocks int64) int64 {
+	if idx == numBlocks-1 {
+		return f.plaintextLength - idx*gcmStreamPlainBlockSize
+	}
+
+	return gcmStreamPlainBlockSize
+}
+
+// readBlock decrypts block idx, or returns it from the single-entry cache
+// if it was the most recently decrypted block. It checks the byte count
+// returned by ReadAt: a short read is reported as [ErrBlockTruncated]
+// (truncated storage), since zero-padding it into the AEAD would surface as a
+// misleading [ErrAuthenticationFailed].
+//
+// cacheMu is only held around the cache check and the cache publish at the
+// end, never across the underlying ReadAt or aead.Open below: holding it
+// across I/O would serialize all concurrent readers, including remote
+// backends. A lost race between two goroutines decrypting the same block is
+// harmless (redundant work, not a correctness issue).
+func (f *standardInputFile) readBlock(idx int64) ([]byte, error) {
+	f.cacheMu.Lock()
+	if f.cacheValid && f.cacheIdx == idx {
+		block := f.cacheBlock
+		f.cacheMu.Unlock()
+
+		return block, nil
+	}
+	f.cacheMu.Unlock()
+
+	numBlocks := f.numBlocks()
+	if idx < 0 || idx >= numBlocks {
+		return nil, fmt.Errorf("%w: block index %d out of range [0, %d)", ErrInvalidKeyMetadata, idx, numBlocks)
+	}
+	// The AAD carries the block index as 32 bits, and a file-length near
+	// math.MaxInt64 would otherwise imply more blocks than that.
+	if idx > math.MaxUint32 {
+		return nil, fmt.Errorf("%w: block index %d exceeds the maximum supported block count", ErrInvalidKeyMetadata, idx)
+	}
+
+	// idx < numBlocks and plaintextLength was derived from an int64 stream
+	// length, so this offset is no larger than that length and cannot
+	// overflow.
+	offset := gcmStreamHeaderLength + idx*gcmStreamCipherBlockSize
+
+	wantLen := f.blockPlainLen(idx, numBlocks) + gcmStreamBlockOverhead
+	ciphertext := make([]byte, wantLen)
+	n, err := f.underlying.ReadAt(ciphertext, offset)
+	if err != nil && !errors.Is(err, io.EOF) {
+		return nil, fmt.Errorf("encryption: failed to read block %d: %w", idx, err)
+	}
+	if int64(n) != wantLen {
+		return nil, fmt.Errorf("%w: block %d: read %d of %d expected ciphertext bytes", ErrBlockTruncated, idx, n, wantLen)
+	}
+
+	nonce, sealed := ciphertext[:gcmStreamNonceLength], ciphertext[gcmStreamNonceLength:]
+	aad := gcmStreamBlockAAD(f.aadPrefix, uint32(idx))
+
+	plaintext, err := f.aead.Open(nil, nonce, sealed, aad)

Review Comment:
   Minor: `f.aead.Open(sealed[:0], nonce, sealed, aad)` decrypts in place into the freshly allocated `ciphertext`, saving a 1 MiB allocation per block read.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat(encryption): add StandardEncryptionManager [iceberg-go]

Posted by "zeroshade (via GitHub)" <gi...@apache.org>.
zeroshade commented on code in PR #1620:
URL: https://github.com/apache/iceberg-go/pull/1620#discussion_r3960997143


##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,883 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file

Review Comment:
   **nit** — File name no longer matches the type it defines
   
   standard_manager.go and standard_manager_test.go now contain GoEnvelopeEncryptionManager and its helpers exclusively; the 'standard' name is a leftover from the pre-rename design and will send readers looking for a StandardEncryptionManager that does not exist. Renaming to go_envelope_manager.go / go_envelope_manager_test.go would keep grep honest.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,883 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+	"math"
+	"sync"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [GoEnvelopeEncryptionManager].
+const (
+	// GoEnvelopeDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	GoEnvelopeDefaultDEKLength = 32
+
+	// GoEnvelopeDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	//
+	// This is not Java's Ciphers.PLAIN_BLOCK_SIZE (1 MiB, a compile-time
+	// constant there); see the [GoEnvelopeEncryptionManager] doc comment.
+	GoEnvelopeDefaultBlockSize = 64 * 1024
+
+	// GoEnvelopeMaxBlockSize is the largest plaintext block size accepted
+	// from the AES GCM Stream header on read, and the largest that
+	// [WithBlockSize] will configure for writing. The header's block-length
+	// field is unauthenticated, untrusted data (the Iceberg AES GCM Stream
+	// spec's "File length" note applies equally here); without a ceiling, a
+	// crafted header claiming e.g. 1<<40 bytes would force a huge
+	// allocation (see readBlock) before any authentication check can run.
+	GoEnvelopeMaxBlockSize = 128 * 1024 * 1024
+)
+
+// Sentinel errors returned by [GoEnvelopeEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile] when keyID is
+	// empty. GoEnvelopeEncryptionManager always encrypts, so it requires a
+	// KEK to wrap the generated DEK; use [PlaintextEncryptionManager] for
+	// unencrypted tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when keyMetadata
+	// is empty. GoEnvelopeEncryptionManager always decrypts, so it requires
+	// the per-file key metadata produced by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured block size is not
+	// positive or exceeds [GoEnvelopeMaxBlockSize].
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive and at most GoEnvelopeMaxBlockSize")
+
+	// ErrInvalidStreamHeader is returned when the AES GCM Stream header
+	// (the "AGS1" magic and little-endian block-length fields at the start
+	// of an encrypted file, per the Iceberg AES GCM Stream spec) is
+	// missing, truncated, or specifies a block length outside the
+	// supported range.
+	ErrInvalidStreamHeader = errors.New("encryption: invalid AES GCM Stream header")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a missing AAD prefix). Key metadata is untrusted input on a crypto
+	// read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+
+	// ErrOutputFileClosed is returned by [goEnvelopeOutputFile.Write] when
+	// called after Close, or after a previous flush has poisoned the writer.
+	// It wraps [fs.ErrClosed] so callers can test with errors.Is(err, fs.ErrClosed).
+	ErrOutputFileClosed = fmt.Errorf("encryption: write to closed GoEnvelopeEncryptionManager output file: %w", fs.ErrClosed)
+
+	// ErrBlockTruncated is returned by [goEnvelopeInputFile.ReadAt] when the
+	// underlying storage returns fewer ciphertext bytes for a block than its
+	// recorded length requires, indicating the file was truncated at rest.
+	// This is distinct from [ErrCiphertextTooShort], which [KeyManagementClient]
+	// implementations use for a too-short wrapped key or KMS-encrypted
+	// payload; keeping them separate lets a caller tell a malformed KMS blob
+	// apart from a short block read.
+	ErrBlockTruncated = errors.New("encryption: block truncated: read fewer ciphertext bytes than expected")
+)
+
+// Constants describing the Iceberg AES GCM Stream ("AGS1") wire format used
+// for the ciphertext produced by [GoEnvelopeEncryptionManager]. See
+// https://iceberg.apache.org/gcm-stream-spec/ for the full specification.
+const (
+	// gcmStreamMagic identifies an AES GCM Stream version 1 file.
+	gcmStreamMagic = "AGS1"
+
+	// gcmStreamHeaderLength is the length, in bytes, of the magic plus the
+	// little-endian block-length field written at the start of every file.
+	gcmStreamHeaderLength = len(gcmStreamMagic) + 4
+
+	// gcmStreamNonceLength is the length, in bytes, of the random AES-GCM
+	// nonce stored at the start of every cipher block.
+	gcmStreamNonceLength = 12
+
+	// gcmStreamTagLength is the length, in bytes, of the AES-GCM
+	// authentication tag appended to every cipher block's ciphertext.
+	gcmStreamTagLength = 16
+
+	// gcmStreamBlockOverhead is the number of ciphertext bytes added to
+	// each block beyond its plaintext length (nonce + tag).
+	gcmStreamBlockOverhead = gcmStreamNonceLength + gcmStreamTagLength
+
+	// gcmStreamAADPrefixLength is the length, in bytes, of the random
+	// per-file AAD prefix generated for new output files.
+	gcmStreamAADPrefixLength = 16
+)
+
+// goEnvelopeKeyMetadataVersion is the current encoding version written by
+// [GoEnvelopeEncryptionManager]. It is bumped whenever the on-disk layout of
+// goEnvelopeKeyMetadata changes incompatibly.
+const goEnvelopeKeyMetadataVersion = 1
+
+// goEnvelopeKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [GoEnvelopeEncryptionManager].
+//
+// This encoding is Go-specific, not Java's Avro-encoded StandardKeyMetadata;
+// see the [GoEnvelopeEncryptionManager] doc comment. Per the table spec,
+// DataFile/ManifestFile key_metadata is explicitly "implementation-specific";
+// what must be Iceberg AES GCM Stream compliant - and is - is the wire
+// format of the encrypted byte stream itself (magic, block framing, nonce
+// placement, and AAD; see the constants above).
+type goEnvelopeKeyMetadata struct {
+	Version    int    `json:"v"`
+	KeyID      string `json:"key-id"`
+	WrappedKey []byte `json:"wrapped-key"`
+
+	// BlockSize is the trusted plaintext block size the file was written
+	// with. It is validated bounded before any file I/O, and is what's
+	// actually used to size reads; the stream header's block-length field
+	// is untrusted (unauthenticated, attacker-influenced storage bytes) and
+	// is only compared against this value, never used directly to size an
+	// allocation.
+	BlockSize int64 `json:"block-size"`
+
+	// AADPrefix is combined with each block's little-endian index to form
+	// the AES GCM Stream additional authenticated data, binding every
+	// ciphertext block to this file and to its position so that blocks
+	// cannot be silently reordered, replayed from another file, or spliced
+	// in from elsewhere in the same file. It is not secret.
+	AADPrefix []byte `json:"aad-prefix"`
+
+	// PlaintextLength is the trusted total plaintext size used to compute
+	// the block count on read. Per the AES GCM Stream spec's "File length"
+	// note, a reader must use a length from a trusted source rather than
+	// the underlying storage's reported size, since storage size alone
+	// cannot distinguish a genuinely short file from one truncated by an
+	// attacker who does not also control this metadata.
+	PlaintextLength int64 `json:"plaintext-length"`
+}
+
+// GoEnvelopeEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks and written using the
+// Iceberg AES GCM Stream ("AGS1") format: a magic/block-length header
+// followed by independently authenticated blocks, each carrying its own
+// random nonce and authenticated with an AAD that binds it to the file and
+// to its position. This bounds memory usage and supports random access
+// (Seek/ReadAt) on the decrypted file without buffering or decrypting more
+// than the requested blocks.
+//
+// GoEnvelopeEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+//
+// Not interoperable with Java's StandardEncryptionManager: the AGS1 byte
+// stream framing (magic, block layout, nonce placement, AAD) matches the
+// spec, but the two implementations are not cross-readable. Java's reader
+// hard-requires a 1 MiB header block size (a compile-time constant there),
+// while [GoEnvelopeDefaultBlockSize] is 64 KiB, and Java decodes key
+// metadata as a 1-byte version plus Avro-encoded StandardKeyMetadata, while
+// this type encodes key metadata as JSON (goEnvelopeKeyMetadata). Files
+// written by one are not readable by the other.
+type GoEnvelopeEncryptionManager struct {
+	kms       KeyManagementClient

Review Comment:
   **minor** — PR title and description describe the superseded design, not the code at head
   
   The PR body states blocks are sealed 'using a unique nonce (per-file random prefix combined with the block index)' and that key metadata carries a 'nonce prefix' — that is the derived-nonce scheme reviewers flagged, which this head replaced with per-block random nonces and an AAD prefix. The body also omits the headline change (adoption of AGS1 framing: magic + block-length header, inline nonce, AAD=prefix||index), and the title still names StandardEncryptionManager, a type that no longer exists (now GoEnvelopeEncryptionManager). A reviewer calibrating on the description would audit the wrong scheme and could wrongly re-raise the nonce-reuse blocker. Update title and body to match the implementation.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,883 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+	"math"
+	"sync"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [GoEnvelopeEncryptionManager].
+const (
+	// GoEnvelopeDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	GoEnvelopeDefaultDEKLength = 32
+
+	// GoEnvelopeDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	//
+	// This is not Java's Ciphers.PLAIN_BLOCK_SIZE (1 MiB, a compile-time
+	// constant there); see the [GoEnvelopeEncryptionManager] doc comment.
+	GoEnvelopeDefaultBlockSize = 64 * 1024
+
+	// GoEnvelopeMaxBlockSize is the largest plaintext block size accepted
+	// from the AES GCM Stream header on read, and the largest that
+	// [WithBlockSize] will configure for writing. The header's block-length
+	// field is unauthenticated, untrusted data (the Iceberg AES GCM Stream
+	// spec's "File length" note applies equally here); without a ceiling, a
+	// crafted header claiming e.g. 1<<40 bytes would force a huge
+	// allocation (see readBlock) before any authentication check can run.
+	GoEnvelopeMaxBlockSize = 128 * 1024 * 1024
+)
+
+// Sentinel errors returned by [GoEnvelopeEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile] when keyID is
+	// empty. GoEnvelopeEncryptionManager always encrypts, so it requires a
+	// KEK to wrap the generated DEK; use [PlaintextEncryptionManager] for
+	// unencrypted tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when keyMetadata
+	// is empty. GoEnvelopeEncryptionManager always decrypts, so it requires
+	// the per-file key metadata produced by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured block size is not
+	// positive or exceeds [GoEnvelopeMaxBlockSize].
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive and at most GoEnvelopeMaxBlockSize")
+
+	// ErrInvalidStreamHeader is returned when the AES GCM Stream header
+	// (the "AGS1" magic and little-endian block-length fields at the start
+	// of an encrypted file, per the Iceberg AES GCM Stream spec) is
+	// missing, truncated, or specifies a block length outside the
+	// supported range.
+	ErrInvalidStreamHeader = errors.New("encryption: invalid AES GCM Stream header")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a missing AAD prefix). Key metadata is untrusted input on a crypto
+	// read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+
+	// ErrOutputFileClosed is returned by [goEnvelopeOutputFile.Write] when
+	// called after Close, or after a previous flush has poisoned the writer.
+	// It wraps [fs.ErrClosed] so callers can test with errors.Is(err, fs.ErrClosed).
+	ErrOutputFileClosed = fmt.Errorf("encryption: write to closed GoEnvelopeEncryptionManager output file: %w", fs.ErrClosed)
+
+	// ErrBlockTruncated is returned by [goEnvelopeInputFile.ReadAt] when the
+	// underlying storage returns fewer ciphertext bytes for a block than its
+	// recorded length requires, indicating the file was truncated at rest.
+	// This is distinct from [ErrCiphertextTooShort], which [KeyManagementClient]
+	// implementations use for a too-short wrapped key or KMS-encrypted
+	// payload; keeping them separate lets a caller tell a malformed KMS blob
+	// apart from a short block read.
+	ErrBlockTruncated = errors.New("encryption: block truncated: read fewer ciphertext bytes than expected")
+)
+
+// Constants describing the Iceberg AES GCM Stream ("AGS1") wire format used
+// for the ciphertext produced by [GoEnvelopeEncryptionManager]. See
+// https://iceberg.apache.org/gcm-stream-spec/ for the full specification.
+const (
+	// gcmStreamMagic identifies an AES GCM Stream version 1 file.
+	gcmStreamMagic = "AGS1"
+
+	// gcmStreamHeaderLength is the length, in bytes, of the magic plus the
+	// little-endian block-length field written at the start of every file.
+	gcmStreamHeaderLength = len(gcmStreamMagic) + 4
+
+	// gcmStreamNonceLength is the length, in bytes, of the random AES-GCM
+	// nonce stored at the start of every cipher block.
+	gcmStreamNonceLength = 12
+
+	// gcmStreamTagLength is the length, in bytes, of the AES-GCM
+	// authentication tag appended to every cipher block's ciphertext.
+	gcmStreamTagLength = 16
+
+	// gcmStreamBlockOverhead is the number of ciphertext bytes added to
+	// each block beyond its plaintext length (nonce + tag).
+	gcmStreamBlockOverhead = gcmStreamNonceLength + gcmStreamTagLength
+
+	// gcmStreamAADPrefixLength is the length, in bytes, of the random
+	// per-file AAD prefix generated for new output files.
+	gcmStreamAADPrefixLength = 16
+)
+
+// goEnvelopeKeyMetadataVersion is the current encoding version written by
+// [GoEnvelopeEncryptionManager]. It is bumped whenever the on-disk layout of
+// goEnvelopeKeyMetadata changes incompatibly.
+const goEnvelopeKeyMetadataVersion = 1
+
+// goEnvelopeKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [GoEnvelopeEncryptionManager].
+//
+// This encoding is Go-specific, not Java's Avro-encoded StandardKeyMetadata;
+// see the [GoEnvelopeEncryptionManager] doc comment. Per the table spec,
+// DataFile/ManifestFile key_metadata is explicitly "implementation-specific";
+// what must be Iceberg AES GCM Stream compliant - and is - is the wire
+// format of the encrypted byte stream itself (magic, block framing, nonce
+// placement, and AAD; see the constants above).
+type goEnvelopeKeyMetadata struct {
+	Version    int    `json:"v"`
+	KeyID      string `json:"key-id"`
+	WrappedKey []byte `json:"wrapped-key"`
+
+	// BlockSize is the trusted plaintext block size the file was written
+	// with. It is validated bounded before any file I/O, and is what's
+	// actually used to size reads; the stream header's block-length field
+	// is untrusted (unauthenticated, attacker-influenced storage bytes) and
+	// is only compared against this value, never used directly to size an
+	// allocation.
+	BlockSize int64 `json:"block-size"`
+
+	// AADPrefix is combined with each block's little-endian index to form
+	// the AES GCM Stream additional authenticated data, binding every
+	// ciphertext block to this file and to its position so that blocks
+	// cannot be silently reordered, replayed from another file, or spliced
+	// in from elsewhere in the same file. It is not secret.
+	AADPrefix []byte `json:"aad-prefix"`
+
+	// PlaintextLength is the trusted total plaintext size used to compute
+	// the block count on read. Per the AES GCM Stream spec's "File length"
+	// note, a reader must use a length from a trusted source rather than
+	// the underlying storage's reported size, since storage size alone
+	// cannot distinguish a genuinely short file from one truncated by an
+	// attacker who does not also control this metadata.
+	PlaintextLength int64 `json:"plaintext-length"`
+}
+
+// GoEnvelopeEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks and written using the
+// Iceberg AES GCM Stream ("AGS1") format: a magic/block-length header
+// followed by independently authenticated blocks, each carrying its own
+// random nonce and authenticated with an AAD that binds it to the file and
+// to its position. This bounds memory usage and supports random access
+// (Seek/ReadAt) on the decrypted file without buffering or decrypting more
+// than the requested blocks.
+//
+// GoEnvelopeEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+//
+// Not interoperable with Java's StandardEncryptionManager: the AGS1 byte
+// stream framing (magic, block layout, nonce placement, AAD) matches the
+// spec, but the two implementations are not cross-readable. Java's reader
+// hard-requires a 1 MiB header block size (a compile-time constant there),
+// while [GoEnvelopeDefaultBlockSize] is 64 KiB, and Java decodes key
+// metadata as a 1-byte version plus Avro-encoded StandardKeyMetadata, while
+// this type encodes key metadata as JSON (goEnvelopeKeyMetadata). Files
+// written by one are not readable by the other.
+type GoEnvelopeEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*GoEnvelopeEncryptionManager)(nil)
+
+// GoEnvelopeManagerOption configures a [GoEnvelopeEncryptionManager] created
+// by [NewGoEnvelopeEncryptionManager].
+type GoEnvelopeManagerOption func(*GoEnvelopeEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) GoEnvelopeManagerOption {
+	return func(m *GoEnvelopeEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication. size must be
+// positive and at most [GoEnvelopeMaxBlockSize].
+func WithBlockSize(size int) GoEnvelopeManagerOption {
+	return func(m *GoEnvelopeEncryptionManager) { m.blockSize = size }
+}
+
+// NewGoEnvelopeEncryptionManager creates a [GoEnvelopeEncryptionManager]
+// backed by kms. kms must not be nil; NewGoEnvelopeEncryptionManager panics
+// if it is.
+func NewGoEnvelopeEncryptionManager(kms KeyManagementClient, opts ...GoEnvelopeManagerOption) *GoEnvelopeEncryptionManager {
+	if kms == nil {
+		panic("encryption: NewGoEnvelopeEncryptionManager: kms must not be nil")
+	}
+
+	m := &GoEnvelopeEncryptionManager{
+		kms:       kms,
+		dekLength: GoEnvelopeDefaultDEKLength,
+		blockSize: GoEnvelopeDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *GoEnvelopeEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 || m.blockSize > GoEnvelopeMaxBlockSize {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+	switch m.dekLength {
+	case 16, 24, 32:
+	default:
+		return nil, fmt.Errorf("%w: DEK length must be 16, 24, or 32 bytes; got %d", ErrInvalidKeyLength, m.dekLength)
+	}
+
+	// The (key, nonce) uniqueness this block format relies on requires a
+	// freshly generated DEK for every file: never cache or reuse
+	// plainDEK/wrappedDEK across calls to NewEncryptedOutputFile.
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = io.ReadFull(rand.Reader, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newGoEnvelopeAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	aadPrefix := make([]byte, gcmStreamAADPrefixLength)
+	if _, err := io.ReadFull(rand.Reader, aadPrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate AAD prefix: %w", err)
+	}
+
+	// Write the AES GCM Stream header (magic + little-endian block length)
+	// up front, before any ciphertext blocks, per the format spec.
+	header := make([]byte, gcmStreamHeaderLength)
+	copy(header, gcmStreamMagic)
+	binary.LittleEndian.PutUint32(header[len(gcmStreamMagic):], uint32(m.blockSize)) //nolint:gosec // bounded by ErrInvalidBlockSize above
+	if _, err := writer.Write(header); err != nil {
+		return nil, fmt.Errorf("encryption: failed to write stream header: %w", err)
+	}
+
+	return &goEnvelopeOutputFile{
+		FileWriter: writer,
+		aead:       aead,
+		aadPrefix:  aadPrefix,
+		blockSize:  m.blockSize,
+		keyID:      keyID,
+		wrappedKey: wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *GoEnvelopeEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta goEnvelopeKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != goEnvelopeKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 || meta.BlockSize > GoEnvelopeMaxBlockSize {
+		return nil, fmt.Errorf("%w: block-size must be positive and at most %d, got %d", ErrInvalidKeyMetadata, GoEnvelopeMaxBlockSize, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}

Review Comment:
   **nit** — aad-prefix has a lower bound but no upper bound
   
   NewDecryptedInputFile rejects an empty AADPrefix but accepts an arbitrarily large one, and gcmStreamBlockAAD allocates len(prefix)+4 bytes on every readBlock call. A 4 MiB prefix is accepted at construction and then re-allocated per block read. Bounded by the metadata blob's own size and classified as malformed-input robustness (out of scope per SECURITY-THREAT-MODEL.md), so this is cheap insurance rather than a defect: bound it alongside the existing block-size ceiling, ideally to the 16 bytes the writer actually emits.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,883 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+	"math"
+	"sync"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [GoEnvelopeEncryptionManager].
+const (
+	// GoEnvelopeDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	GoEnvelopeDefaultDEKLength = 32
+
+	// GoEnvelopeDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	//
+	// This is not Java's Ciphers.PLAIN_BLOCK_SIZE (1 MiB, a compile-time
+	// constant there); see the [GoEnvelopeEncryptionManager] doc comment.
+	GoEnvelopeDefaultBlockSize = 64 * 1024
+
+	// GoEnvelopeMaxBlockSize is the largest plaintext block size accepted
+	// from the AES GCM Stream header on read, and the largest that
+	// [WithBlockSize] will configure for writing. The header's block-length
+	// field is unauthenticated, untrusted data (the Iceberg AES GCM Stream
+	// spec's "File length" note applies equally here); without a ceiling, a
+	// crafted header claiming e.g. 1<<40 bytes would force a huge
+	// allocation (see readBlock) before any authentication check can run.
+	GoEnvelopeMaxBlockSize = 128 * 1024 * 1024
+)
+
+// Sentinel errors returned by [GoEnvelopeEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile] when keyID is
+	// empty. GoEnvelopeEncryptionManager always encrypts, so it requires a
+	// KEK to wrap the generated DEK; use [PlaintextEncryptionManager] for
+	// unencrypted tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when keyMetadata
+	// is empty. GoEnvelopeEncryptionManager always decrypts, so it requires
+	// the per-file key metadata produced by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured block size is not
+	// positive or exceeds [GoEnvelopeMaxBlockSize].
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive and at most GoEnvelopeMaxBlockSize")
+
+	// ErrInvalidStreamHeader is returned when the AES GCM Stream header
+	// (the "AGS1" magic and little-endian block-length fields at the start
+	// of an encrypted file, per the Iceberg AES GCM Stream spec) is
+	// missing, truncated, or specifies a block length outside the
+	// supported range.
+	ErrInvalidStreamHeader = errors.New("encryption: invalid AES GCM Stream header")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a missing AAD prefix). Key metadata is untrusted input on a crypto
+	// read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+
+	// ErrOutputFileClosed is returned by [goEnvelopeOutputFile.Write] when
+	// called after Close, or after a previous flush has poisoned the writer.
+	// It wraps [fs.ErrClosed] so callers can test with errors.Is(err, fs.ErrClosed).
+	ErrOutputFileClosed = fmt.Errorf("encryption: write to closed GoEnvelopeEncryptionManager output file: %w", fs.ErrClosed)
+
+	// ErrBlockTruncated is returned by [goEnvelopeInputFile.ReadAt] when the
+	// underlying storage returns fewer ciphertext bytes for a block than its
+	// recorded length requires, indicating the file was truncated at rest.
+	// This is distinct from [ErrCiphertextTooShort], which [KeyManagementClient]
+	// implementations use for a too-short wrapped key or KMS-encrypted
+	// payload; keeping them separate lets a caller tell a malformed KMS blob
+	// apart from a short block read.
+	ErrBlockTruncated = errors.New("encryption: block truncated: read fewer ciphertext bytes than expected")
+)
+
+// Constants describing the Iceberg AES GCM Stream ("AGS1") wire format used
+// for the ciphertext produced by [GoEnvelopeEncryptionManager]. See
+// https://iceberg.apache.org/gcm-stream-spec/ for the full specification.
+const (
+	// gcmStreamMagic identifies an AES GCM Stream version 1 file.
+	gcmStreamMagic = "AGS1"
+
+	// gcmStreamHeaderLength is the length, in bytes, of the magic plus the
+	// little-endian block-length field written at the start of every file.
+	gcmStreamHeaderLength = len(gcmStreamMagic) + 4
+
+	// gcmStreamNonceLength is the length, in bytes, of the random AES-GCM
+	// nonce stored at the start of every cipher block.
+	gcmStreamNonceLength = 12
+
+	// gcmStreamTagLength is the length, in bytes, of the AES-GCM
+	// authentication tag appended to every cipher block's ciphertext.
+	gcmStreamTagLength = 16
+
+	// gcmStreamBlockOverhead is the number of ciphertext bytes added to
+	// each block beyond its plaintext length (nonce + tag).
+	gcmStreamBlockOverhead = gcmStreamNonceLength + gcmStreamTagLength
+
+	// gcmStreamAADPrefixLength is the length, in bytes, of the random
+	// per-file AAD prefix generated for new output files.
+	gcmStreamAADPrefixLength = 16
+)
+
+// goEnvelopeKeyMetadataVersion is the current encoding version written by
+// [GoEnvelopeEncryptionManager]. It is bumped whenever the on-disk layout of
+// goEnvelopeKeyMetadata changes incompatibly.
+const goEnvelopeKeyMetadataVersion = 1
+
+// goEnvelopeKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [GoEnvelopeEncryptionManager].
+//
+// This encoding is Go-specific, not Java's Avro-encoded StandardKeyMetadata;
+// see the [GoEnvelopeEncryptionManager] doc comment. Per the table spec,
+// DataFile/ManifestFile key_metadata is explicitly "implementation-specific";
+// what must be Iceberg AES GCM Stream compliant - and is - is the wire
+// format of the encrypted byte stream itself (magic, block framing, nonce
+// placement, and AAD; see the constants above).
+type goEnvelopeKeyMetadata struct {
+	Version    int    `json:"v"`
+	KeyID      string `json:"key-id"`
+	WrappedKey []byte `json:"wrapped-key"`
+
+	// BlockSize is the trusted plaintext block size the file was written
+	// with. It is validated bounded before any file I/O, and is what's
+	// actually used to size reads; the stream header's block-length field
+	// is untrusted (unauthenticated, attacker-influenced storage bytes) and
+	// is only compared against this value, never used directly to size an
+	// allocation.
+	BlockSize int64 `json:"block-size"`
+
+	// AADPrefix is combined with each block's little-endian index to form
+	// the AES GCM Stream additional authenticated data, binding every
+	// ciphertext block to this file and to its position so that blocks
+	// cannot be silently reordered, replayed from another file, or spliced
+	// in from elsewhere in the same file. It is not secret.
+	AADPrefix []byte `json:"aad-prefix"`
+
+	// PlaintextLength is the trusted total plaintext size used to compute
+	// the block count on read. Per the AES GCM Stream spec's "File length"
+	// note, a reader must use a length from a trusted source rather than
+	// the underlying storage's reported size, since storage size alone
+	// cannot distinguish a genuinely short file from one truncated by an
+	// attacker who does not also control this metadata.
+	PlaintextLength int64 `json:"plaintext-length"`
+}
+
+// GoEnvelopeEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks and written using the
+// Iceberg AES GCM Stream ("AGS1") format: a magic/block-length header
+// followed by independently authenticated blocks, each carrying its own
+// random nonce and authenticated with an AAD that binds it to the file and
+// to its position. This bounds memory usage and supports random access
+// (Seek/ReadAt) on the decrypted file without buffering or decrypting more
+// than the requested blocks.
+//
+// GoEnvelopeEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+//
+// Not interoperable with Java's StandardEncryptionManager: the AGS1 byte
+// stream framing (magic, block layout, nonce placement, AAD) matches the
+// spec, but the two implementations are not cross-readable. Java's reader
+// hard-requires a 1 MiB header block size (a compile-time constant there),
+// while [GoEnvelopeDefaultBlockSize] is 64 KiB, and Java decodes key
+// metadata as a 1-byte version plus Avro-encoded StandardKeyMetadata, while
+// this type encodes key metadata as JSON (goEnvelopeKeyMetadata). Files
+// written by one are not readable by the other.
+type GoEnvelopeEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*GoEnvelopeEncryptionManager)(nil)
+
+// GoEnvelopeManagerOption configures a [GoEnvelopeEncryptionManager] created
+// by [NewGoEnvelopeEncryptionManager].
+type GoEnvelopeManagerOption func(*GoEnvelopeEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) GoEnvelopeManagerOption {
+	return func(m *GoEnvelopeEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication. size must be
+// positive and at most [GoEnvelopeMaxBlockSize].
+func WithBlockSize(size int) GoEnvelopeManagerOption {
+	return func(m *GoEnvelopeEncryptionManager) { m.blockSize = size }
+}
+
+// NewGoEnvelopeEncryptionManager creates a [GoEnvelopeEncryptionManager]
+// backed by kms. kms must not be nil; NewGoEnvelopeEncryptionManager panics
+// if it is.
+func NewGoEnvelopeEncryptionManager(kms KeyManagementClient, opts ...GoEnvelopeManagerOption) *GoEnvelopeEncryptionManager {
+	if kms == nil {
+		panic("encryption: NewGoEnvelopeEncryptionManager: kms must not be nil")
+	}
+
+	m := &GoEnvelopeEncryptionManager{
+		kms:       kms,
+		dekLength: GoEnvelopeDefaultDEKLength,
+		blockSize: GoEnvelopeDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *GoEnvelopeEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 || m.blockSize > GoEnvelopeMaxBlockSize {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+	switch m.dekLength {
+	case 16, 24, 32:
+	default:
+		return nil, fmt.Errorf("%w: DEK length must be 16, 24, or 32 bytes; got %d", ErrInvalidKeyLength, m.dekLength)
+	}
+
+	// The (key, nonce) uniqueness this block format relies on requires a
+	// freshly generated DEK for every file: never cache or reuse
+	// plainDEK/wrappedDEK across calls to NewEncryptedOutputFile.
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = io.ReadFull(rand.Reader, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newGoEnvelopeAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	aadPrefix := make([]byte, gcmStreamAADPrefixLength)
+	if _, err := io.ReadFull(rand.Reader, aadPrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate AAD prefix: %w", err)
+	}
+
+	// Write the AES GCM Stream header (magic + little-endian block length)
+	// up front, before any ciphertext blocks, per the format spec.
+	header := make([]byte, gcmStreamHeaderLength)
+	copy(header, gcmStreamMagic)
+	binary.LittleEndian.PutUint32(header[len(gcmStreamMagic):], uint32(m.blockSize)) //nolint:gosec // bounded by ErrInvalidBlockSize above
+	if _, err := writer.Write(header); err != nil {
+		return nil, fmt.Errorf("encryption: failed to write stream header: %w", err)
+	}
+
+	return &goEnvelopeOutputFile{
+		FileWriter: writer,
+		aead:       aead,
+		aadPrefix:  aadPrefix,
+		blockSize:  m.blockSize,
+		keyID:      keyID,
+		wrappedKey: wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *GoEnvelopeEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta goEnvelopeKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != goEnvelopeKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 || meta.BlockSize > GoEnvelopeMaxBlockSize {
+		return nil, fmt.Errorf("%w: block-size must be positive and at most %d, got %d", ErrInvalidKeyMetadata, GoEnvelopeMaxBlockSize, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}
+	if len(meta.AADPrefix) == 0 {
+		return nil, fmt.Errorf("%w: aad-prefix must not be empty", ErrInvalidKeyMetadata)
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newGoEnvelopeAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	// headerBlockSize is untrusted (unauthenticated bytes read from
+	// storage): it is only ever compared against the trusted, already
+	// bounded meta.BlockSize below, never used to size a read or allocation.
+	headerBlockSize, err := readGCMStreamHeader(file)
+	if err != nil {
+		return nil, err
+	}
+	if headerBlockSize != meta.BlockSize {
+		return nil, fmt.Errorf("%w: stream header block length %d does not match key metadata block-size %d", ErrInvalidStreamHeader, headerBlockSize, meta.BlockSize)
+	}
+
+	return &goEnvelopeInputFile{
+		underlying:      file,
+		aead:            aead,
+		aadPrefix:       meta.AADPrefix,
+		blockSize:       meta.BlockSize,
+		plaintextLength: meta.PlaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newGoEnvelopeAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %w", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// readGCMStreamHeader reads and validates the AES GCM Stream magic and
+// block-length header at the start of file, returning the plaintext block
+// length. The header is untrusted, unauthenticated data, so the returned
+// length is bounded to [GoEnvelopeMaxBlockSize] before any allocation sized
+// by it takes place.
+func readGCMStreamHeader(file icebergio.File) (int64, error) {
+	header := make([]byte, gcmStreamHeaderLength)
+	n, err := file.ReadAt(header, 0)
+	if err != nil && !errors.Is(err, io.EOF) {
+		return 0, fmt.Errorf("encryption: failed to read stream header: %w", err)
+	}
+	if n != gcmStreamHeaderLength {
+		return 0, fmt.Errorf("%w: expected %d header bytes, got %d", ErrInvalidStreamHeader, gcmStreamHeaderLength, n)
+	}
+	if string(header[:len(gcmStreamMagic)]) != gcmStreamMagic {
+		return 0, fmt.Errorf("%w: missing %q magic", ErrInvalidStreamHeader, gcmStreamMagic)
+	}
+
+	blockSize := int64(binary.LittleEndian.Uint32(header[len(gcmStreamMagic):]))
+	if blockSize <= 0 || blockSize > GoEnvelopeMaxBlockSize {
+		return 0, fmt.Errorf("%w: block length %d out of supported range (0, %d]", ErrInvalidStreamHeader, blockSize, GoEnvelopeMaxBlockSize)
+	}
+
+	return blockSize, nil
+}
+
+// gcmStreamBlockAAD derives the AES-GCM additional authenticated data for
+// blockIndex: the per-file AAD prefix followed by the 4-byte little-endian
+// block index, per the Iceberg AES GCM Stream spec. This binds every
+// ciphertext block to this file and to its position, which matters because
+// blocks carry independent random nonces (rather than a nonce derived from
+// the block index): without the index in the AAD, an attacker able to
+// tamper with ciphertext at rest could silently reorder or splice blocks.
+func gcmStreamBlockAAD(prefix []byte, blockIndex uint32) []byte {
+	aad := make([]byte, len(prefix)+4)
+	copy(aad, prefix)
+	binary.LittleEndian.PutUint32(aad[len(prefix):], blockIndex)
+
+	return aad
+}
+
+// checkedMulInt64 returns a*b and true, or (0, false) if the multiplication
+// overflows int64.
+func checkedMulInt64(a, b int64) (int64, bool) {
+	if a == 0 || b == 0 {
+		return 0, true
+	}
+	result := a * b
+	if result/b != a {
+		return 0, false
+	}
+
+	return result, true
+}
+
+// checkedAddInt64 returns a+b and true, or (0, false) if the addition
+// overflows int64.
+func checkedAddInt64(a, b int64) (int64, bool) {
+	result := a + b
+	if (b > 0 && result < a) || (b < 0 && result > a) {
+		return 0, false
+	}
+
+	return result, true
+}
+
+// goEnvelopeOutputFile is an [EncryptedOutputFile] that seals fixed-size
+// plaintext blocks with AES-GCM as they are written, using the Iceberg AES
+// GCM Stream ("AGS1") wire format.
+type goEnvelopeOutputFile struct {
+	icebergio.FileWriter
+
+	aead       cipher.AEAD
+	aadPrefix  []byte
+	blockSize  int
+	keyID      string
+	wrappedKey []byte
+
+	buf        []byte
+	blockIndex uint32
+	written    int64
+	closed     bool
+	err        error
+
+	// underlyingClosed tracks whether FileWriter.Close has already been
+	// attempted, so a poisoned writer is closed exactly once regardless of
+	// whether the failure is first observed in Write or in Close.
+	underlyingClosed bool
+
+	keyMetadata EncryptionKeyMetadata
+}
+
+var _ EncryptedOutputFile = (*goEnvelopeOutputFile)(nil)
+
+// closeUnderlyingIgnoringError closes the underlying writer at most once.
+// The error is ignored: the caller is already reporting a more specific
+// failure (a flush or encode error), and this is best-effort cleanup so a
+// poisoned writer never leaks its underlying file descriptor or connection.
+//
+// defensive: today every call site sets f.err before calling this, and
+// Write/Close both bail out early once f.err is set, so the
+// underlyingClosed guard never actually stops a second Close in practice.
+// It stays as a hard invariant in case a future call site is added that
+// doesn't follow that pattern.
+func (f *goEnvelopeOutputFile) closeUnderlyingIgnoringError() {
+	if f.underlyingClosed {
+		return
+	}
+	f.underlyingClosed = true
+	_ = f.FileWriter.Close()
+}
+
+func (f *goEnvelopeOutputFile) Write(p []byte) (int, error) {
+	if f.err != nil {
+		return 0, f.err
+	}
+	if f.closed {
+		return 0, ErrOutputFileClosed
+	}
+
+	total := len(p)
+	consumed := 0 // bytes of p appended into f.buf so far in this call
+	accepted := 0 // bytes of p known to be durably flushed; reported on failure
+	for len(p) > 0 {
+		space := f.blockSize - len(f.buf)
+		n := min(space, len(p))
+		f.buf = append(f.buf, p[:n]...)
+		p = p[n:]
+		consumed += n
+		if len(f.buf) == f.blockSize {
+			if err := f.flushBlock(); err != nil {
+				f.err = err
+				f.closeUnderlyingIgnoringError()
+
+				return accepted, err
+			}
+			accepted = consumed
+		}
+	}
+
+	return total, nil
+}
+
+// flushBlock seals and writes the currently buffered plaintext block using a
+// fresh random nonce, per the Iceberg AES GCM Stream format. f.written is
+// only advanced once the ciphertext has actually reached the underlying
+// writer, so a failed flush never overcounts PlaintextLength.
+func (f *goEnvelopeOutputFile) flushBlock() error {
+	if f.blockIndex == math.MaxUint32 {
+		return errors.New("encryption: cannot write block: exceeded maximum block count")
+	}
+
+	nonce := make([]byte, gcmStreamNonceLength)
+	if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
+		return fmt.Errorf("encryption: failed to generate block nonce: %w", err)

Review Comment:
   **major** — Per-block nonce uniqueness is pinned by no test — a constant nonce passes the entire suite
   
   flushBlock correctly draws a fresh 12-byte nonce per block from crypto/rand, and I confirmed by probe that head produces distinct nonces (64/64) and distinct ciphertext for identical plaintext blocks. But nothing in the suite enforces it. Nonce reuse under a single GCM key leaks the plaintext XOR and the GHASH authentication key — it is the most catastrophic failure mode this file can have, and it is invisible to every round-trip, tamper, and reorder test because reusing a nonce still decrypts correctly. Every other guarantee in this file (AAD binding, auth enforcement, truncation detection, Write count, sticky Close) is mutation-pinned by a named test; this one is not. Add a test that seals a multi-block file with repeating plaintext and asserts all block nonces at offset 8+i*(blockSize+28) are pairwise distinct, and that two blocks of identical plaintext yield different ciphertext.
   
   <details><summary>Evidence</summary>
   
   ```text
   Replaced the nonce derivation with a hardcoded all-zero nonce (`nonce := make([]byte, gcmStreamNonceLength)`, rand read deleted) and ran the full package: `ok github.com/apache/iceberg-go/encryption 0.242s` — zero failures. Contrast with the AAD mutation, which immediately reds ReorderedBlocksFailAuthentication.
   ```
   
   </details>



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat(encryption): add GoEnvelopeEncryptionManager for generic file envelope encryption [iceberg-go]

Posted by "hectar-glitches (via GitHub)" <gi...@apache.org>.
hectar-glitches commented on code in PR #1620:
URL: https://github.com/apache/iceberg-go/pull/1620#discussion_r3972465841


##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,883 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+	"math"
+	"sync"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [GoEnvelopeEncryptionManager].
+const (
+	// GoEnvelopeDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	GoEnvelopeDefaultDEKLength = 32
+
+	// GoEnvelopeDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	//
+	// This is not Java's Ciphers.PLAIN_BLOCK_SIZE (1 MiB, a compile-time
+	// constant there); see the [GoEnvelopeEncryptionManager] doc comment.
+	GoEnvelopeDefaultBlockSize = 64 * 1024
+
+	// GoEnvelopeMaxBlockSize is the largest plaintext block size accepted
+	// from the AES GCM Stream header on read, and the largest that
+	// [WithBlockSize] will configure for writing. The header's block-length
+	// field is unauthenticated, untrusted data (the Iceberg AES GCM Stream
+	// spec's "File length" note applies equally here); without a ceiling, a
+	// crafted header claiming e.g. 1<<40 bytes would force a huge
+	// allocation (see readBlock) before any authentication check can run.
+	GoEnvelopeMaxBlockSize = 128 * 1024 * 1024
+)
+
+// Sentinel errors returned by [GoEnvelopeEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile] when keyID is
+	// empty. GoEnvelopeEncryptionManager always encrypts, so it requires a
+	// KEK to wrap the generated DEK; use [PlaintextEncryptionManager] for
+	// unencrypted tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when keyMetadata
+	// is empty. GoEnvelopeEncryptionManager always decrypts, so it requires
+	// the per-file key metadata produced by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured block size is not
+	// positive or exceeds [GoEnvelopeMaxBlockSize].
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive and at most GoEnvelopeMaxBlockSize")
+
+	// ErrInvalidStreamHeader is returned when the AES GCM Stream header
+	// (the "AGS1" magic and little-endian block-length fields at the start
+	// of an encrypted file, per the Iceberg AES GCM Stream spec) is
+	// missing, truncated, or specifies a block length outside the
+	// supported range.
+	ErrInvalidStreamHeader = errors.New("encryption: invalid AES GCM Stream header")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a missing AAD prefix). Key metadata is untrusted input on a crypto
+	// read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+
+	// ErrOutputFileClosed is returned by [goEnvelopeOutputFile.Write] when
+	// called after Close, or after a previous flush has poisoned the writer.
+	// It wraps [fs.ErrClosed] so callers can test with errors.Is(err, fs.ErrClosed).
+	ErrOutputFileClosed = fmt.Errorf("encryption: write to closed GoEnvelopeEncryptionManager output file: %w", fs.ErrClosed)
+
+	// ErrBlockTruncated is returned by [goEnvelopeInputFile.ReadAt] when the
+	// underlying storage returns fewer ciphertext bytes for a block than its
+	// recorded length requires, indicating the file was truncated at rest.
+	// This is distinct from [ErrCiphertextTooShort], which [KeyManagementClient]
+	// implementations use for a too-short wrapped key or KMS-encrypted
+	// payload; keeping them separate lets a caller tell a malformed KMS blob
+	// apart from a short block read.
+	ErrBlockTruncated = errors.New("encryption: block truncated: read fewer ciphertext bytes than expected")
+)
+
+// Constants describing the Iceberg AES GCM Stream ("AGS1") wire format used
+// for the ciphertext produced by [GoEnvelopeEncryptionManager]. See
+// https://iceberg.apache.org/gcm-stream-spec/ for the full specification.
+const (
+	// gcmStreamMagic identifies an AES GCM Stream version 1 file.
+	gcmStreamMagic = "AGS1"
+
+	// gcmStreamHeaderLength is the length, in bytes, of the magic plus the
+	// little-endian block-length field written at the start of every file.
+	gcmStreamHeaderLength = len(gcmStreamMagic) + 4
+
+	// gcmStreamNonceLength is the length, in bytes, of the random AES-GCM
+	// nonce stored at the start of every cipher block.
+	gcmStreamNonceLength = 12
+
+	// gcmStreamTagLength is the length, in bytes, of the AES-GCM
+	// authentication tag appended to every cipher block's ciphertext.
+	gcmStreamTagLength = 16
+
+	// gcmStreamBlockOverhead is the number of ciphertext bytes added to
+	// each block beyond its plaintext length (nonce + tag).
+	gcmStreamBlockOverhead = gcmStreamNonceLength + gcmStreamTagLength
+
+	// gcmStreamAADPrefixLength is the length, in bytes, of the random
+	// per-file AAD prefix generated for new output files.
+	gcmStreamAADPrefixLength = 16
+)
+
+// goEnvelopeKeyMetadataVersion is the current encoding version written by
+// [GoEnvelopeEncryptionManager]. It is bumped whenever the on-disk layout of
+// goEnvelopeKeyMetadata changes incompatibly.
+const goEnvelopeKeyMetadataVersion = 1
+
+// goEnvelopeKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [GoEnvelopeEncryptionManager].
+//
+// This encoding is Go-specific, not Java's Avro-encoded StandardKeyMetadata;
+// see the [GoEnvelopeEncryptionManager] doc comment. Per the table spec,
+// DataFile/ManifestFile key_metadata is explicitly "implementation-specific";
+// what must be Iceberg AES GCM Stream compliant - and is - is the wire
+// format of the encrypted byte stream itself (magic, block framing, nonce
+// placement, and AAD; see the constants above).
+type goEnvelopeKeyMetadata struct {
+	Version    int    `json:"v"`
+	KeyID      string `json:"key-id"`
+	WrappedKey []byte `json:"wrapped-key"`
+
+	// BlockSize is the trusted plaintext block size the file was written
+	// with. It is validated bounded before any file I/O, and is what's
+	// actually used to size reads; the stream header's block-length field
+	// is untrusted (unauthenticated, attacker-influenced storage bytes) and
+	// is only compared against this value, never used directly to size an
+	// allocation.
+	BlockSize int64 `json:"block-size"`
+
+	// AADPrefix is combined with each block's little-endian index to form
+	// the AES GCM Stream additional authenticated data, binding every
+	// ciphertext block to this file and to its position so that blocks
+	// cannot be silently reordered, replayed from another file, or spliced
+	// in from elsewhere in the same file. It is not secret.
+	AADPrefix []byte `json:"aad-prefix"`
+
+	// PlaintextLength is the trusted total plaintext size used to compute
+	// the block count on read. Per the AES GCM Stream spec's "File length"
+	// note, a reader must use a length from a trusted source rather than
+	// the underlying storage's reported size, since storage size alone
+	// cannot distinguish a genuinely short file from one truncated by an
+	// attacker who does not also control this metadata.
+	PlaintextLength int64 `json:"plaintext-length"`
+}
+
+// GoEnvelopeEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks and written using the
+// Iceberg AES GCM Stream ("AGS1") format: a magic/block-length header
+// followed by independently authenticated blocks, each carrying its own
+// random nonce and authenticated with an AAD that binds it to the file and
+// to its position. This bounds memory usage and supports random access
+// (Seek/ReadAt) on the decrypted file without buffering or decrypting more
+// than the requested blocks.
+//
+// GoEnvelopeEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+//
+// Not interoperable with Java's StandardEncryptionManager: the AGS1 byte
+// stream framing (magic, block layout, nonce placement, AAD) matches the
+// spec, but the two implementations are not cross-readable. Java's reader
+// hard-requires a 1 MiB header block size (a compile-time constant there),
+// while [GoEnvelopeDefaultBlockSize] is 64 KiB, and Java decodes key
+// metadata as a 1-byte version plus Avro-encoded StandardKeyMetadata, while
+// this type encodes key metadata as JSON (goEnvelopeKeyMetadata). Files
+// written by one are not readable by the other.
+type GoEnvelopeEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*GoEnvelopeEncryptionManager)(nil)
+
+// GoEnvelopeManagerOption configures a [GoEnvelopeEncryptionManager] created
+// by [NewGoEnvelopeEncryptionManager].
+type GoEnvelopeManagerOption func(*GoEnvelopeEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) GoEnvelopeManagerOption {
+	return func(m *GoEnvelopeEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication. size must be
+// positive and at most [GoEnvelopeMaxBlockSize].
+func WithBlockSize(size int) GoEnvelopeManagerOption {
+	return func(m *GoEnvelopeEncryptionManager) { m.blockSize = size }
+}
+
+// NewGoEnvelopeEncryptionManager creates a [GoEnvelopeEncryptionManager]
+// backed by kms. kms must not be nil; NewGoEnvelopeEncryptionManager panics
+// if it is.
+func NewGoEnvelopeEncryptionManager(kms KeyManagementClient, opts ...GoEnvelopeManagerOption) *GoEnvelopeEncryptionManager {
+	if kms == nil {
+		panic("encryption: NewGoEnvelopeEncryptionManager: kms must not be nil")
+	}
+
+	m := &GoEnvelopeEncryptionManager{
+		kms:       kms,
+		dekLength: GoEnvelopeDefaultDEKLength,
+		blockSize: GoEnvelopeDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *GoEnvelopeEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 || m.blockSize > GoEnvelopeMaxBlockSize {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+	switch m.dekLength {
+	case 16, 24, 32:
+	default:
+		return nil, fmt.Errorf("%w: DEK length must be 16, 24, or 32 bytes; got %d", ErrInvalidKeyLength, m.dekLength)
+	}
+
+	// The (key, nonce) uniqueness this block format relies on requires a
+	// freshly generated DEK for every file: never cache or reuse
+	// plainDEK/wrappedDEK across calls to NewEncryptedOutputFile.
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = io.ReadFull(rand.Reader, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newGoEnvelopeAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	aadPrefix := make([]byte, gcmStreamAADPrefixLength)
+	if _, err := io.ReadFull(rand.Reader, aadPrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate AAD prefix: %w", err)
+	}
+
+	// Write the AES GCM Stream header (magic + little-endian block length)
+	// up front, before any ciphertext blocks, per the format spec.
+	header := make([]byte, gcmStreamHeaderLength)
+	copy(header, gcmStreamMagic)
+	binary.LittleEndian.PutUint32(header[len(gcmStreamMagic):], uint32(m.blockSize)) //nolint:gosec // bounded by ErrInvalidBlockSize above
+	if _, err := writer.Write(header); err != nil {
+		return nil, fmt.Errorf("encryption: failed to write stream header: %w", err)
+	}
+
+	return &goEnvelopeOutputFile{
+		FileWriter: writer,
+		aead:       aead,
+		aadPrefix:  aadPrefix,
+		blockSize:  m.blockSize,
+		keyID:      keyID,
+		wrappedKey: wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *GoEnvelopeEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta goEnvelopeKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != goEnvelopeKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 || meta.BlockSize > GoEnvelopeMaxBlockSize {
+		return nil, fmt.Errorf("%w: block-size must be positive and at most %d, got %d", ErrInvalidKeyMetadata, GoEnvelopeMaxBlockSize, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}

Review Comment:
   aad-prefix now requires 16 bytes



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat(encryption): add GoEnvelopeEncryptionManager for generic file envelope encryption [iceberg-go]

Posted by "hectar-glitches (via GitHub)" <gi...@apache.org>.
hectar-glitches commented on code in PR #1620:
URL: https://github.com/apache/iceberg-go/pull/1620#discussion_r3972396485


##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,883 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file

Review Comment:
   fixed the naming



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat(encryption): add GoEnvelopeEncryptionManager for generic file envelope encryption [iceberg-go]

Posted by "hectar-glitches (via GitHub)" <gi...@apache.org>.
hectar-glitches commented on PR #1620:
URL: https://github.com/apache/iceberg-go/pull/1620#issuecomment-5720612339

   @zeroshade what do you think?
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat(encryption): add StandardEncryptionManager [iceberg-go]

Posted by "laskoviymishka (via GitHub)" <gi...@apache.org>.
laskoviymishka commented on code in PR #1620:
URL: https://github.com/apache/iceberg-go/pull/1620#discussion_r3719801410


##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,511 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+

Review Comment:
   agreed with tanmayrauth's call to validate the decoded metadata right after this version check — I'd add one belt-and-suspenders guard on top.
   
   Even with the constructor validation, `readBlock` itself does `make([]byte, plainLen+overhead)` with no floor on `plainLen` and no check that `idx` is in `[0, numBlocks())`. It's the actual crypto read path taking numbers derived from untrusted metadata, so I'd have it fail closed there too rather than relying solely on the constructor. Cheap insurance against a future caller that constructs a `standardInputFile` some other way.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,511 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)

Review Comment:
   This is safe today, but the safety is entirely load-bearing on the DEK being fresh per file, and the 4-byte prefix leaves less room than I'd like.
   
   The nonce is 4 random bytes + 8-byte block index, so uniqueness holds only because a new DEK is generated per file — the moment anyone adds DEK caching or reuse, prefix+index collides and GCM nonce reuse is catastrophic. Right now that invariant lives implicitly in the code, not in a comment.
   
   I'd either widen the prefix to 8 bytes to buy margin, or at minimum make the invariant explicit at the generation site ("security relies on the DEK being unique per file; do not reuse a DEK across files") so a future change doesn't quietly break it. wdyt?



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,511 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.

Review Comment:
   agreed with tanmayrauth's blockSize-guard call — the DEK length has the same shape and is the net-new piece I'd add alongside it.
   
   `WithDEKLength(17)` is accepted here silently and only blows up much later at `aes.NewCipher` on the first write. Java validates 16/24/32 up front. Since the constructor doesn't return an error, I'd validate both `blockSize` and `dekLength` in `NewEncryptedOutputFile` (which already returns one), or change the constructor to return `(*StandardEncryptionManager, error)`. Either's fine, but I'd rather reject a bad length at construction than at first write.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,511 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 {
+		return nil, fmt.Errorf("%w: block-size must be positive, got %d", ErrInvalidKeyMetadata, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}
+	if len(meta.NoncePrefix) != 4 {
+		return nil, fmt.Errorf("%w: nonce-prefix must be 4 bytes, got %d", ErrInvalidKeyMetadata, len(meta.NoncePrefix))
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	return &standardInputFile{
+		underlying:      file,
+		aead:            aead,
+		noncePrefix:     meta.NoncePrefix,
+		blockSize:       meta.BlockSize,
+		plaintextLength: meta.PlaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newStandardAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %v", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// standardBlockNonce derives the AES-GCM nonce for blockIndex: the 4-byte
+// per-file random prefix followed by the 8-byte big-endian block index. The
+// (key, nonce) pair is unique per block since the DEK is fresh per file and
+// no two blocks in the same file share an index.
+func standardBlockNonce(prefix []byte, blockIndex uint64) []byte {
+	nonce := make([]byte, 12)
+	copy(nonce, prefix)
+	binary.BigEndian.PutUint64(nonce[4:], blockIndex)
+
+	return nonce
+}
+
+// standardOutputFile is an [EncryptedOutputFile] that seals fixed-size
+// plaintext blocks with AES-GCM as they are written.
+type standardOutputFile struct {
+	icebergio.FileWriter
+
+	aead        cipher.AEAD
+	noncePrefix []byte
+	blockSize   int
+	keyID       string
+	wrappedKey  []byte
+
+	buf        []byte
+	blockIndex uint64
+	written    int64
+	closed     bool
+
+	keyMetadata EncryptionKeyMetadata
+}
+
+var _ EncryptedOutputFile = (*standardOutputFile)(nil)
+
+func (f *standardOutputFile) Write(p []byte) (int, error) {
+	total := len(p)
+	for len(p) > 0 {
+		space := f.blockSize - len(f.buf)
+		n := min(space, len(p))
+		f.buf = append(f.buf, p[:n]...)
+		p = p[n:]
+		f.written += int64(n)
+		if len(f.buf) == f.blockSize {
+			if err := f.flushBlock(); err != nil {
+				return total - len(p), err
+			}
+		}
+	}
+
+	return total, nil
+}
+
+func (f *standardOutputFile) flushBlock() error {
+	ciphertext := f.aead.Seal(nil, standardBlockNonce(f.noncePrefix, f.blockIndex), f.buf, nil)
+	if _, err := f.FileWriter.Write(ciphertext); err != nil {
+		return fmt.Errorf("encryption: failed to write encrypted block: %w", err)
+	}
+	f.blockIndex++
+	f.buf = f.buf[:0]
+
+	return nil
+}
+
+// ReadFrom copies from r, encrypting as data is written, satisfying
+// io.ReaderFrom (required by [icebergio.FileWriter]).
+func (f *standardOutputFile) ReadFrom(r io.Reader) (int64, error) {
+	buf := make([]byte, 32*1024)
+	var total int64
+	for {
+		n, err := r.Read(buf)

Review Comment:
   `closed` gets set before the final flush, so a `Close` that fails its flush can't be retried.
   
   The second `Close` hits the `if f.closed { return nil }` guard and returns nil without re-flushing, so the caller sees success on a file that never finished writing (and `KeyMetadata` stays empty). The flush-failure path also drops the `FileWriter.Close()` error via `_ =`.
   
   I'd set `closed = true` only on the success path (or track a sticky `f.err` and return it on every subsequent `Close`). A `failWriter` stub that errors on the Nth block would let us assert `Close` errors, `KeyMetadata()` is nil, and a repeat `Close` still errors.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,511 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 {
+		return nil, fmt.Errorf("%w: block-size must be positive, got %d", ErrInvalidKeyMetadata, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}
+	if len(meta.NoncePrefix) != 4 {
+		return nil, fmt.Errorf("%w: nonce-prefix must be 4 bytes, got %d", ErrInvalidKeyMetadata, len(meta.NoncePrefix))
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	return &standardInputFile{
+		underlying:      file,
+		aead:            aead,
+		noncePrefix:     meta.NoncePrefix,
+		blockSize:       meta.BlockSize,
+		plaintextLength: meta.PlaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newStandardAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %v", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// standardBlockNonce derives the AES-GCM nonce for blockIndex: the 4-byte
+// per-file random prefix followed by the 8-byte big-endian block index. The
+// (key, nonce) pair is unique per block since the DEK is fresh per file and
+// no two blocks in the same file share an index.
+func standardBlockNonce(prefix []byte, blockIndex uint64) []byte {
+	nonce := make([]byte, 12)
+	copy(nonce, prefix)
+	binary.BigEndian.PutUint64(nonce[4:], blockIndex)
+
+	return nonce
+}
+
+// standardOutputFile is an [EncryptedOutputFile] that seals fixed-size
+// plaintext blocks with AES-GCM as they are written.
+type standardOutputFile struct {
+	icebergio.FileWriter
+
+	aead        cipher.AEAD
+	noncePrefix []byte
+	blockSize   int
+	keyID       string
+	wrappedKey  []byte
+
+	buf        []byte
+	blockIndex uint64
+	written    int64
+	closed     bool
+
+	keyMetadata EncryptionKeyMetadata
+}

Review Comment:
   just adding a concrete data point to tanmayrauth's #1289 interop flag, not asking for anything here.
   
   For whoever picks up that discussion, here's the exact byte-level gap vs Java's `AesGcmOutputStream`: no 8-byte "AGS1" + block-size header, block layout is `ciphertext‖tag` with the nonce *derived* rather than Java's inline random 12-byte nonce, AAD is nil vs Java's `fileAadPrefix‖ordinal`, 64 KiB blocks vs 1 MiB, and `key_metadata` is our JSON struct vs Java's Avro `StandardKeyMetadata`. So the formats are byte-incompatible in both directions today.
   
   Two things that lean toward resolving it sooner rather than later: the type reuses the name `StandardEncryptionManager`, which is the canonical cross-engine impl elsewhere, so a reader reasonably assumes interop and gets silently-unreadable tables; and only the DEK is wrapped here — the nonce prefix, block size, and plaintext length ride in cleartext JSON, where Java envelope-encrypts the whole blob. Both are inputs for #1289, not changes for this PR.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,511 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 {
+		return nil, fmt.Errorf("%w: block-size must be positive, got %d", ErrInvalidKeyMetadata, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}
+	if len(meta.NoncePrefix) != 4 {
+		return nil, fmt.Errorf("%w: nonce-prefix must be 4 bytes, got %d", ErrInvalidKeyMetadata, len(meta.NoncePrefix))
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	return &standardInputFile{
+		underlying:      file,
+		aead:            aead,
+		noncePrefix:     meta.NoncePrefix,
+		blockSize:       meta.BlockSize,
+		plaintextLength: meta.PlaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newStandardAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %v", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// standardBlockNonce derives the AES-GCM nonce for blockIndex: the 4-byte
+// per-file random prefix followed by the 8-byte big-endian block index. The
+// (key, nonce) pair is unique per block since the DEK is fresh per file and
+// no two blocks in the same file share an index.
+func standardBlockNonce(prefix []byte, blockIndex uint64) []byte {
+	nonce := make([]byte, 12)
+	copy(nonce, prefix)
+	binary.BigEndian.PutUint64(nonce[4:], blockIndex)
+
+	return nonce
+}
+
+// standardOutputFile is an [EncryptedOutputFile] that seals fixed-size
+// plaintext blocks with AES-GCM as they are written.
+type standardOutputFile struct {
+	icebergio.FileWriter
+
+	aead        cipher.AEAD
+	noncePrefix []byte
+	blockSize   int
+	keyID       string
+	wrappedKey  []byte
+
+	buf        []byte
+	blockIndex uint64
+	written    int64
+	closed     bool
+
+	keyMetadata EncryptionKeyMetadata
+}
+
+var _ EncryptedOutputFile = (*standardOutputFile)(nil)
+
+func (f *standardOutputFile) Write(p []byte) (int, error) {
+	total := len(p)
+	for len(p) > 0 {
+		space := f.blockSize - len(f.buf)
+		n := min(space, len(p))
+		f.buf = append(f.buf, p[:n]...)
+		p = p[n:]
+		f.written += int64(n)
+		if len(f.buf) == f.blockSize {
+			if err := f.flushBlock(); err != nil {
+				return total - len(p), err
+			}
+		}
+	}
+
+	return total, nil
+}
+
+func (f *standardOutputFile) flushBlock() error {
+	ciphertext := f.aead.Seal(nil, standardBlockNonce(f.noncePrefix, f.blockIndex), f.buf, nil)
+	if _, err := f.FileWriter.Write(ciphertext); err != nil {
+		return fmt.Errorf("encryption: failed to write encrypted block: %w", err)
+	}
+	f.blockIndex++
+	f.buf = f.buf[:0]
+
+	return nil
+}
+
+// ReadFrom copies from r, encrypting as data is written, satisfying
+// io.ReaderFrom (required by [icebergio.FileWriter]).
+func (f *standardOutputFile) ReadFrom(r io.Reader) (int64, error) {
+	buf := make([]byte, 32*1024)
+	var total int64
+	for {
+		n, err := r.Read(buf)
+		if n > 0 {
+			wn, werr := f.Write(buf[:n])
+			total += int64(wn)
+			if werr != nil {
+				return total, werr
+			}
+		}
+		if err == io.EOF {
+			break
+		}
+		if err != nil {
+			return total, err
+		}
+	}
+
+	return total, nil
+}
+
+func (f *standardOutputFile) Close() error {
+	if f.closed {
+		return nil
+	}
+	f.closed = true
+
+	if len(f.buf) > 0 {
+		if err := f.flushBlock(); err != nil {
+			_ = f.FileWriter.Close()
+
+			return err
+		}
+	}
+
+	meta := standardKeyMetadata{
+		Version:         standardKeyMetadataVersion,
+		KeyID:           f.keyID,
+		WrappedKey:      f.wrappedKey,
+		NoncePrefix:     f.noncePrefix,
+		BlockSize:       f.blockSize,
+		PlaintextLength: f.written,
+	}
+	encoded, err := json.Marshal(meta)
+	if err != nil {
+		_ = f.FileWriter.Close()
+
+		return fmt.Errorf("encryption: failed to encode key metadata: %w", err)
+	}
+	f.keyMetadata = encoded
+
+	return f.FileWriter.Close()
+}
+
+// KeyMetadata returns the finalized per-file key metadata. It is only
+// populated after Close has been called.
+func (f *standardOutputFile) KeyMetadata() EncryptionKeyMetadata { return f.keyMetadata }
+
+// standardInputFile is an [EncryptedInputFile] that decrypts fixed-size
+// AES-GCM blocks on demand, supporting random access via ReadAt/Seek.
+type standardInputFile struct {
+	underlying      icebergio.File
+	aead            cipher.AEAD
+	noncePrefix     []byte
+	blockSize       int
+	plaintextLength int64
+	keyMetadata     EncryptionKeyMetadata
+
+	pos int64
+}
+
+var _ EncryptedInputFile = (*standardInputFile)(nil)
+
+func (f *standardInputFile) numBlocks() int64 {

Review Comment:
   This discards a short read, and I think it breaks the last block of every file whose size isn't a block multiple on a real backend.
   
   On S3 or the local fs, `ReadAt` fills a partial final block and returns `(n, io.EOF)` with `n < len(ciphertext)`. We drop the EOF here, so `aead.Open` gets a buffer that's zero-padded past `n` and fails auth — which then surfaces as `ErrAuthenticationFailed`, not truncation. The in-memory test file never hits this because `bytes.Reader` fills the whole slice, so the suite is green while real reads fail.
   
   I'd capture `n` and slice `ciphertext = ciphertext[:n]` before `Open`, and treat a genuinely short *non-final* block as a distinct truncation error rather than letting it fall through to auth-failed. Worth a test backed by a reader that returns `(n, io.EOF)` so we actually catch this class.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,511 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 {
+		return nil, fmt.Errorf("%w: block-size must be positive, got %d", ErrInvalidKeyMetadata, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}
+	if len(meta.NoncePrefix) != 4 {
+		return nil, fmt.Errorf("%w: nonce-prefix must be 4 bytes, got %d", ErrInvalidKeyMetadata, len(meta.NoncePrefix))
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	return &standardInputFile{
+		underlying:      file,
+		aead:            aead,
+		noncePrefix:     meta.NoncePrefix,
+		blockSize:       meta.BlockSize,
+		plaintextLength: meta.PlaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newStandardAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %v", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// standardBlockNonce derives the AES-GCM nonce for blockIndex: the 4-byte
+// per-file random prefix followed by the 8-byte big-endian block index. The
+// (key, nonce) pair is unique per block since the DEK is fresh per file and
+// no two blocks in the same file share an index.
+func standardBlockNonce(prefix []byte, blockIndex uint64) []byte {
+	nonce := make([]byte, 12)
+	copy(nonce, prefix)
+	binary.BigEndian.PutUint64(nonce[4:], blockIndex)
+
+	return nonce
+}
+
+// standardOutputFile is an [EncryptedOutputFile] that seals fixed-size
+// plaintext blocks with AES-GCM as they are written.
+type standardOutputFile struct {
+	icebergio.FileWriter
+
+	aead        cipher.AEAD
+	noncePrefix []byte
+	blockSize   int
+	keyID       string
+	wrappedKey  []byte
+
+	buf        []byte
+	blockIndex uint64
+	written    int64
+	closed     bool
+
+	keyMetadata EncryptionKeyMetadata
+}
+
+var _ EncryptedOutputFile = (*standardOutputFile)(nil)
+
+func (f *standardOutputFile) Write(p []byte) (int, error) {
+	total := len(p)
+	for len(p) > 0 {
+		space := f.blockSize - len(f.buf)
+		n := min(space, len(p))
+		f.buf = append(f.buf, p[:n]...)
+		p = p[n:]
+		f.written += int64(n)
+		if len(f.buf) == f.blockSize {
+			if err := f.flushBlock(); err != nil {
+				return total - len(p), err
+			}
+		}
+	}
+
+	return total, nil
+}
+
+func (f *standardOutputFile) flushBlock() error {
+	ciphertext := f.aead.Seal(nil, standardBlockNonce(f.noncePrefix, f.blockIndex), f.buf, nil)
+	if _, err := f.FileWriter.Write(ciphertext); err != nil {
+		return fmt.Errorf("encryption: failed to write encrypted block: %w", err)
+	}
+	f.blockIndex++
+	f.buf = f.buf[:0]
+
+	return nil
+}
+
+// ReadFrom copies from r, encrypting as data is written, satisfying
+// io.ReaderFrom (required by [icebergio.FileWriter]).
+func (f *standardOutputFile) ReadFrom(r io.Reader) (int64, error) {
+	buf := make([]byte, 32*1024)
+	var total int64
+	for {
+		n, err := r.Read(buf)
+		if n > 0 {
+			wn, werr := f.Write(buf[:n])
+			total += int64(wn)
+			if werr != nil {
+				return total, werr
+			}
+		}
+		if err == io.EOF {
+			break
+		}
+		if err != nil {
+			return total, err
+		}
+	}
+
+	return total, nil
+}
+
+func (f *standardOutputFile) Close() error {
+	if f.closed {
+		return nil
+	}
+	f.closed = true
+
+	if len(f.buf) > 0 {
+		if err := f.flushBlock(); err != nil {
+			_ = f.FileWriter.Close()
+
+			return err
+		}
+	}
+
+	meta := standardKeyMetadata{
+		Version:         standardKeyMetadataVersion,
+		KeyID:           f.keyID,
+		WrappedKey:      f.wrappedKey,
+		NoncePrefix:     f.noncePrefix,
+		BlockSize:       f.blockSize,
+		PlaintextLength: f.written,
+	}
+	encoded, err := json.Marshal(meta)
+	if err != nil {
+		_ = f.FileWriter.Close()
+
+		return fmt.Errorf("encryption: failed to encode key metadata: %w", err)
+	}
+	f.keyMetadata = encoded
+
+	return f.FileWriter.Close()
+}
+
+// KeyMetadata returns the finalized per-file key metadata. It is only
+// populated after Close has been called.
+func (f *standardOutputFile) KeyMetadata() EncryptionKeyMetadata { return f.keyMetadata }
+
+// standardInputFile is an [EncryptedInputFile] that decrypts fixed-size
+// AES-GCM blocks on demand, supporting random access via ReadAt/Seek.
+type standardInputFile struct {
+	underlying      icebergio.File
+	aead            cipher.AEAD
+	noncePrefix     []byte
+	blockSize       int
+	plaintextLength int64
+	keyMetadata     EncryptionKeyMetadata
+
+	pos int64
+}
+
+var _ EncryptedInputFile = (*standardInputFile)(nil)
+
+func (f *standardInputFile) numBlocks() int64 {
+	if f.plaintextLength == 0 {
+		return 0
+	}
+
+	return (f.plaintextLength + int64(f.blockSize) - 1) / int64(f.blockSize)
+}
+
+func (f *standardInputFile) blockPlainLen(idx int64) int64 {
+	if idx == f.numBlocks()-1 {
+		return f.plaintextLength - idx*int64(f.blockSize)
+	}
+
+	return int64(f.blockSize)
+}
+
+func (f *standardInputFile) physicalOffset(idx int64) int64 {
+	return idx * int64(f.blockSize+f.aead.Overhead())
+}
+
+func (f *standardInputFile) readBlock(idx int64) ([]byte, error) {
+	plainLen := f.blockPlainLen(idx)
+	ciphertext := make([]byte, plainLen+int64(f.aead.Overhead()))
+	if _, err := f.underlying.ReadAt(ciphertext, f.physicalOffset(idx)); err != nil && !errors.Is(err, io.EOF) {
+		return nil, fmt.Errorf("encryption: failed to read block %d: %w", idx, err)
+	}
+
+	plaintext, err := f.aead.Open(nil, standardBlockNonce(f.noncePrefix, uint64(idx)), ciphertext, nil)
+	if err != nil {
+		return nil, fmt.Errorf("%w: block %d: %v", ErrAuthenticationFailed, idx, err)
+	}
+
+	return plaintext, nil
+}
+
+func (f *standardInputFile) ReadAt(p []byte, off int64) (int, error) {
+	if off < 0 {
+		return 0, errors.New("encryption: ReadAt: negative offset")
+	}
+	if off >= f.plaintextLength {
+		return 0, io.EOF
+	}
+
+	var read int

Review Comment:
   doc nit: `ReadAt` is stateless and safe for concurrent use (and `io.ReaderAt` documents that contract), but `Read`/`Seek` mutate `f.pos` with no synchronization. Same type mixing both is a bit of a trap via `io.Copy`. Worth a comment that `Read`/`Seek` aren't concurrent-safe while `ReadAt` is.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,511 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 {
+		return nil, fmt.Errorf("%w: block-size must be positive, got %d", ErrInvalidKeyMetadata, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}
+	if len(meta.NoncePrefix) != 4 {
+		return nil, fmt.Errorf("%w: nonce-prefix must be 4 bytes, got %d", ErrInvalidKeyMetadata, len(meta.NoncePrefix))
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)

Review Comment:
   tiny consistency nit: this wraps with `%v` while the `NewGCM` error just below uses `%w`. `errors.Is(ErrInvalidKeyLength)` still works, but `%v` drops the inner aes error from the chain. I'd use `%w` for both.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,511 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 {
+		return nil, fmt.Errorf("%w: block-size must be positive, got %d", ErrInvalidKeyMetadata, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}
+	if len(meta.NoncePrefix) != 4 {
+		return nil, fmt.Errorf("%w: nonce-prefix must be 4 bytes, got %d", ErrInvalidKeyMetadata, len(meta.NoncePrefix))
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	return &standardInputFile{
+		underlying:      file,
+		aead:            aead,
+		noncePrefix:     meta.NoncePrefix,
+		blockSize:       meta.BlockSize,
+		plaintextLength: meta.PlaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newStandardAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %v", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// standardBlockNonce derives the AES-GCM nonce for blockIndex: the 4-byte
+// per-file random prefix followed by the 8-byte big-endian block index. The
+// (key, nonce) pair is unique per block since the DEK is fresh per file and
+// no two blocks in the same file share an index.
+func standardBlockNonce(prefix []byte, blockIndex uint64) []byte {
+	nonce := make([]byte, 12)
+	copy(nonce, prefix)
+	binary.BigEndian.PutUint64(nonce[4:], blockIndex)
+
+	return nonce
+}
+
+// standardOutputFile is an [EncryptedOutputFile] that seals fixed-size
+// plaintext blocks with AES-GCM as they are written.
+type standardOutputFile struct {
+	icebergio.FileWriter
+
+	aead        cipher.AEAD
+	noncePrefix []byte
+	blockSize   int
+	keyID       string
+	wrappedKey  []byte
+
+	buf        []byte
+	blockIndex uint64
+	written    int64
+	closed     bool
+
+	keyMetadata EncryptionKeyMetadata
+}
+
+var _ EncryptedOutputFile = (*standardOutputFile)(nil)
+
+func (f *standardOutputFile) Write(p []byte) (int, error) {
+	total := len(p)
+	for len(p) > 0 {
+		space := f.blockSize - len(f.buf)
+		n := min(space, len(p))
+		f.buf = append(f.buf, p[:n]...)
+		p = p[n:]
+		f.written += int64(n)
+		if len(f.buf) == f.blockSize {
+			if err := f.flushBlock(); err != nil {

Review Comment:
   nit: the copy buffer is a fixed 32 KiB regardless of `blockSize`, so with a larger block we do extra Write round-trips through the buffering. `make([]byte, f.blockSize)` (or `max(32*1024, f.blockSize)`) lines it up with the block boundary.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,511 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 {
+		return nil, fmt.Errorf("%w: block-size must be positive, got %d", ErrInvalidKeyMetadata, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}
+	if len(meta.NoncePrefix) != 4 {
+		return nil, fmt.Errorf("%w: nonce-prefix must be 4 bytes, got %d", ErrInvalidKeyMetadata, len(meta.NoncePrefix))
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	return &standardInputFile{
+		underlying:      file,
+		aead:            aead,
+		noncePrefix:     meta.NoncePrefix,
+		blockSize:       meta.BlockSize,
+		plaintextLength: meta.PlaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newStandardAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %v", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// standardBlockNonce derives the AES-GCM nonce for blockIndex: the 4-byte
+// per-file random prefix followed by the 8-byte big-endian block index. The
+// (key, nonce) pair is unique per block since the DEK is fresh per file and
+// no two blocks in the same file share an index.
+func standardBlockNonce(prefix []byte, blockIndex uint64) []byte {
+	nonce := make([]byte, 12)
+	copy(nonce, prefix)
+	binary.BigEndian.PutUint64(nonce[4:], blockIndex)
+
+	return nonce
+}
+
+// standardOutputFile is an [EncryptedOutputFile] that seals fixed-size
+// plaintext blocks with AES-GCM as they are written.
+type standardOutputFile struct {
+	icebergio.FileWriter
+
+	aead        cipher.AEAD
+	noncePrefix []byte
+	blockSize   int
+	keyID       string
+	wrappedKey  []byte
+
+	buf        []byte
+	blockIndex uint64
+	written    int64
+	closed     bool
+
+	keyMetadata EncryptionKeyMetadata
+}
+
+var _ EncryptedOutputFile = (*standardOutputFile)(nil)
+
+func (f *standardOutputFile) Write(p []byte) (int, error) {
+	total := len(p)
+	for len(p) > 0 {
+		space := f.blockSize - len(f.buf)
+		n := min(space, len(p))
+		f.buf = append(f.buf, p[:n]...)
+		p = p[n:]
+		f.written += int64(n)
+		if len(f.buf) == f.blockSize {
+			if err := f.flushBlock(); err != nil {
+				return total - len(p), err
+			}
+		}
+	}
+
+	return total, nil
+}
+
+func (f *standardOutputFile) flushBlock() error {
+	ciphertext := f.aead.Seal(nil, standardBlockNonce(f.noncePrefix, f.blockIndex), f.buf, nil)
+	if _, err := f.FileWriter.Write(ciphertext); err != nil {
+		return fmt.Errorf("encryption: failed to write encrypted block: %w", err)
+	}
+	f.blockIndex++
+	f.buf = f.buf[:0]
+
+	return nil
+}
+
+// ReadFrom copies from r, encrypting as data is written, satisfying
+// io.ReaderFrom (required by [icebergio.FileWriter]).
+func (f *standardOutputFile) ReadFrom(r io.Reader) (int64, error) {
+	buf := make([]byte, 32*1024)
+	var total int64
+	for {
+		n, err := r.Read(buf)
+		if n > 0 {
+			wn, werr := f.Write(buf[:n])
+			total += int64(wn)
+			if werr != nil {
+				return total, werr
+			}
+		}
+		if err == io.EOF {
+			break
+		}
+		if err != nil {
+			return total, err
+		}
+	}
+
+	return total, nil
+}
+
+func (f *standardOutputFile) Close() error {
+	if f.closed {
+		return nil
+	}
+	f.closed = true
+
+	if len(f.buf) > 0 {
+		if err := f.flushBlock(); err != nil {
+			_ = f.FileWriter.Close()
+
+			return err
+		}
+	}
+
+	meta := standardKeyMetadata{
+		Version:         standardKeyMetadataVersion,
+		KeyID:           f.keyID,
+		WrappedKey:      f.wrappedKey,
+		NoncePrefix:     f.noncePrefix,
+		BlockSize:       f.blockSize,
+		PlaintextLength: f.written,
+	}
+	encoded, err := json.Marshal(meta)
+	if err != nil {
+		_ = f.FileWriter.Close()
+
+		return fmt.Errorf("encryption: failed to encode key metadata: %w", err)
+	}
+	f.keyMetadata = encoded
+
+	return f.FileWriter.Close()
+}
+
+// KeyMetadata returns the finalized per-file key metadata. It is only
+// populated after Close has been called.
+func (f *standardOutputFile) KeyMetadata() EncryptionKeyMetadata { return f.keyMetadata }
+
+// standardInputFile is an [EncryptedInputFile] that decrypts fixed-size
+// AES-GCM blocks on demand, supporting random access via ReadAt/Seek.
+type standardInputFile struct {
+	underlying      icebergio.File
+	aead            cipher.AEAD
+	noncePrefix     []byte
+	blockSize       int
+	plaintextLength int64
+	keyMetadata     EncryptionKeyMetadata
+
+	pos int64
+}
+
+var _ EncryptedInputFile = (*standardInputFile)(nil)
+
+func (f *standardInputFile) numBlocks() int64 {
+	if f.plaintextLength == 0 {
+		return 0
+	}
+
+	return (f.plaintextLength + int64(f.blockSize) - 1) / int64(f.blockSize)
+}
+
+func (f *standardInputFile) blockPlainLen(idx int64) int64 {
+	if idx == f.numBlocks()-1 {
+		return f.plaintextLength - idx*int64(f.blockSize)
+	}
+
+	return int64(f.blockSize)
+}
+
+func (f *standardInputFile) physicalOffset(idx int64) int64 {

Review Comment:
   small stdlib-conformance thing: a zero-length read on an empty file returns `io.EOF` here where `bytes.Reader`/`strings.Reader` return `(0, nil)`.
   
   With `plaintextLength` 0, `off >= f.plaintextLength` is `0 >= 0`, so `ReadAt(nil, 0)` reports `io.EOF`. A caller probing an empty file (a valid zero-row manifest) via a zero-length `ReadAt` would misread it as an error. I'd add `if len(p) == 0 { return 0, nil }` ahead of the offset check.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,511 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 {
+		return nil, fmt.Errorf("%w: block-size must be positive, got %d", ErrInvalidKeyMetadata, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}
+	if len(meta.NoncePrefix) != 4 {
+		return nil, fmt.Errorf("%w: nonce-prefix must be 4 bytes, got %d", ErrInvalidKeyMetadata, len(meta.NoncePrefix))
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	return &standardInputFile{
+		underlying:      file,
+		aead:            aead,
+		noncePrefix:     meta.NoncePrefix,
+		blockSize:       meta.BlockSize,
+		plaintextLength: meta.PlaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newStandardAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %v", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// standardBlockNonce derives the AES-GCM nonce for blockIndex: the 4-byte
+// per-file random prefix followed by the 8-byte big-endian block index. The
+// (key, nonce) pair is unique per block since the DEK is fresh per file and
+// no two blocks in the same file share an index.
+func standardBlockNonce(prefix []byte, blockIndex uint64) []byte {
+	nonce := make([]byte, 12)
+	copy(nonce, prefix)
+	binary.BigEndian.PutUint64(nonce[4:], blockIndex)
+
+	return nonce
+}
+
+// standardOutputFile is an [EncryptedOutputFile] that seals fixed-size
+// plaintext blocks with AES-GCM as they are written.
+type standardOutputFile struct {
+	icebergio.FileWriter
+
+	aead        cipher.AEAD

Review Comment:
   We bump `f.written` before the block is actually flushed, and I think that corrupts the file on a mid-write flush failure.
   
   If `flushBlock` fails, we reset `f.buf` but leave `f.written` counting the bytes that never reached the writer, so `Close` records a `PlaintextLength` longer than the ciphertext actually holds — the reader then computes wrong block boundaries and fails to auth the final block. The `return total - len(p)` on the same path also reports buffered-but-unflushed bytes as written, which an `io.Writer` caller treats as durable.
   
   I'd only advance `written` after a successful flush, and make the writer sticky (an `f.err`) so a failed flush poisons subsequent Writes rather than continuing on a half-written stream. While we're here, `Write` has no guard against use after `Close` — a Write after Close happily appends through the closed `FileWriter`. wdyt?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat(encryption): add StandardEncryptionManager [iceberg-go]

Posted by "zeroshade (via GitHub)" <gi...@apache.org>.
zeroshade commented on code in PR #1620:
URL: https://github.com/apache/iceberg-go/pull/1620#discussion_r3806617085


##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,583 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+
+	// ErrOutputFileClosed is returned by [standardOutputFile.Write] when
+	// called after Close, or after a previous flush has poisoned the writer.
+	ErrOutputFileClosed = errors.New("encryption: write to closed StandardEncryptionManager output file")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+	switch m.dekLength {
+	case 16, 24, 32:
+	default:
+		return nil, fmt.Errorf("%w: DEK length must be 16, 24, or 32 bytes; got %d", ErrInvalidKeyLength, m.dekLength)
+	}
+
+	// The (key, nonce) uniqueness this block format relies on requires a
+	// freshly generated DEK for every file: the nonce is only 4 random bytes
+	// plus a block index, so reusing a DEK across files would reuse (DEK,
+	// nonce) pairs and break AES-GCM's security guarantees. Never cache or
+	// reuse plainDEK/wrappedDEK across calls to NewEncryptedOutputFile.
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 {

Review Comment:
   **Blocking robustness: `block-size` remains an unbounded metadata-controlled allocation size.** Positivity alone permits values such as `1 << 40`; construction succeeds and the first read reaches `make([]byte, blockSize+overhead)`. The ceiling-division and physical-offset calculations can overflow as well. Please impose a supported maximum, use overflow-safe arithmetic (`1 + (length-1)/blockSize` plus checked multiplication/addition), and reject metadata whose implied physical layout is impossible. Under the repository threat model this is malformed-input robustness, not an in-scope security vulnerability.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,583 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+
+	// ErrOutputFileClosed is returned by [standardOutputFile.Write] when
+	// called after Close, or after a previous flush has poisoned the writer.
+	ErrOutputFileClosed = errors.New("encryption: write to closed StandardEncryptionManager output file")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+	switch m.dekLength {
+	case 16, 24, 32:
+	default:
+		return nil, fmt.Errorf("%w: DEK length must be 16, 24, or 32 bytes; got %d", ErrInvalidKeyLength, m.dekLength)
+	}
+
+	// The (key, nonce) uniqueness this block format relies on requires a
+	// freshly generated DEK for every file: the nonce is only 4 random bytes
+	// plus a block index, so reusing a DEK across files would reuse (DEK,
+	// nonce) pairs and break AES-GCM's security guarantees. Never cache or
+	// reuse plainDEK/wrappedDEK across calls to NewEncryptedOutputFile.
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 {
+		return nil, fmt.Errorf("%w: block-size must be positive, got %d", ErrInvalidKeyMetadata, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}
+	if len(meta.NoncePrefix) != 4 {
+		return nil, fmt.Errorf("%w: nonce-prefix must be 4 bytes, got %d", ErrInvalidKeyMetadata, len(meta.NoncePrefix))
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	return &standardInputFile{
+		underlying:      file,
+		aead:            aead,
+		noncePrefix:     meta.NoncePrefix,
+		blockSize:       meta.BlockSize,
+		plaintextLength: meta.PlaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newStandardAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %w", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// standardBlockNonce derives the AES-GCM nonce for blockIndex: the 4-byte
+// per-file random prefix followed by the 8-byte big-endian block index.
+// Uniqueness of the (key, nonce) pair across every block ever sealed with a
+// given DEK depends entirely on the DEK being freshly generated per file;
+// see the caution in [StandardEncryptionManager.NewEncryptedOutputFile].
+func standardBlockNonce(prefix []byte, blockIndex uint64) []byte {
+	nonce := make([]byte, 12)
+	copy(nonce, prefix)
+	binary.BigEndian.PutUint64(nonce[4:], blockIndex)
+
+	return nonce
+}
+
+// standardOutputFile is an [EncryptedOutputFile] that seals fixed-size
+// plaintext blocks with AES-GCM as they are written.
+type standardOutputFile struct {
+	icebergio.FileWriter
+
+	aead        cipher.AEAD
+	noncePrefix []byte
+	blockSize   int
+	keyID       string
+	wrappedKey  []byte
+
+	buf        []byte
+	blockIndex uint64
+	written    int64
+	closed     bool
+	err        error
+
+	keyMetadata EncryptionKeyMetadata
+}
+
+var _ EncryptedOutputFile = (*standardOutputFile)(nil)
+
+func (f *standardOutputFile) Write(p []byte) (int, error) {
+	if f.err != nil {
+		return 0, f.err
+	}
+	if f.closed {
+		return 0, ErrOutputFileClosed
+	}
+
+	total := len(p)
+	for len(p) > 0 {
+		space := f.blockSize - len(f.buf)
+		n := min(space, len(p))
+		f.buf = append(f.buf, p[:n]...)
+		p = p[n:]
+		if len(f.buf) == f.blockSize {
+			if err := f.flushBlock(); err != nil {
+				f.err = err
+
+				return total - len(p), err
+			}
+		}
+	}
+
+	return total, nil
+}
+
+// flushBlock seals and writes the currently buffered plaintext block.
+// f.written is only advanced once the ciphertext has actually reached the
+// underlying writer, so a failed flush never overcounts PlaintextLength.
+func (f *standardOutputFile) flushBlock() error {
+	ciphertext := f.aead.Seal(nil, standardBlockNonce(f.noncePrefix, f.blockIndex), f.buf, nil)

Review Comment:
   **Blocking: this is still not Iceberg AES GCM Stream (`AGS1`).** The stream omits the required `AGS1` magic and little-endian block-length header, blocks do not carry their required random 12-byte nonce, `Seal`/`Open` use `nil` AAD rather than `aadPrefix || uint32LE(blockIndex)`, and key metadata is custom JSON rather than Iceberg `StandardKeyMetadata`. This is incompatible with Java/PyIceberg and leaves truncation undetected: I reproduced changing `plaintext-length` from 64 to 32 and truncating after two 16-byte blocks; decryption returned 32 bytes without error. Please implement the specified framing/AAD and add a known-vector or cross-implementation test.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,583 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+
+	// ErrOutputFileClosed is returned by [standardOutputFile.Write] when
+	// called after Close, or after a previous flush has poisoned the writer.
+	ErrOutputFileClosed = errors.New("encryption: write to closed StandardEncryptionManager output file")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+	switch m.dekLength {
+	case 16, 24, 32:
+	default:
+		return nil, fmt.Errorf("%w: DEK length must be 16, 24, or 32 bytes; got %d", ErrInvalidKeyLength, m.dekLength)
+	}
+
+	// The (key, nonce) uniqueness this block format relies on requires a
+	// freshly generated DEK for every file: the nonce is only 4 random bytes
+	// plus a block index, so reusing a DEK across files would reuse (DEK,
+	// nonce) pairs and break AES-GCM's security guarantees. Never cache or
+	// reuse plainDEK/wrappedDEK across calls to NewEncryptedOutputFile.
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 {
+		return nil, fmt.Errorf("%w: block-size must be positive, got %d", ErrInvalidKeyMetadata, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}
+	if len(meta.NoncePrefix) != 4 {
+		return nil, fmt.Errorf("%w: nonce-prefix must be 4 bytes, got %d", ErrInvalidKeyMetadata, len(meta.NoncePrefix))
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	return &standardInputFile{
+		underlying:      file,
+		aead:            aead,
+		noncePrefix:     meta.NoncePrefix,
+		blockSize:       meta.BlockSize,
+		plaintextLength: meta.PlaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newStandardAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %w", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// standardBlockNonce derives the AES-GCM nonce for blockIndex: the 4-byte
+// per-file random prefix followed by the 8-byte big-endian block index.
+// Uniqueness of the (key, nonce) pair across every block ever sealed with a
+// given DEK depends entirely on the DEK being freshly generated per file;
+// see the caution in [StandardEncryptionManager.NewEncryptedOutputFile].
+func standardBlockNonce(prefix []byte, blockIndex uint64) []byte {
+	nonce := make([]byte, 12)
+	copy(nonce, prefix)
+	binary.BigEndian.PutUint64(nonce[4:], blockIndex)
+
+	return nonce
+}
+
+// standardOutputFile is an [EncryptedOutputFile] that seals fixed-size
+// plaintext blocks with AES-GCM as they are written.
+type standardOutputFile struct {
+	icebergio.FileWriter
+
+	aead        cipher.AEAD
+	noncePrefix []byte
+	blockSize   int
+	keyID       string
+	wrappedKey  []byte
+
+	buf        []byte
+	blockIndex uint64
+	written    int64
+	closed     bool
+	err        error
+
+	keyMetadata EncryptionKeyMetadata
+}
+
+var _ EncryptedOutputFile = (*standardOutputFile)(nil)
+
+func (f *standardOutputFile) Write(p []byte) (int, error) {
+	if f.err != nil {
+		return 0, f.err
+	}
+	if f.closed {
+		return 0, ErrOutputFileClosed
+	}
+
+	total := len(p)
+	for len(p) > 0 {
+		space := f.blockSize - len(f.buf)
+		n := min(space, len(p))
+		f.buf = append(f.buf, p[:n]...)
+		p = p[n:]
+		if len(f.buf) == f.blockSize {
+			if err := f.flushBlock(); err != nil {
+				f.err = err
+
+				return total - len(p), err

Review Comment:
   **Major: the previous `Write` count finding is still outstanding.** Bytes are removed from `p` before `flushBlock` succeeds, so with four-byte blocks and a writer that fails on its second call, `Write([]byte("aaaabbbb"))` returns `n=8, err!=nil` although only the first block reached storage and the writer is permanently poisoned. Track the accepted count at the last successful flush boundary and extend the new failure test to assert `n == 4`.



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,583 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured or decoded block
+	// size is not positive.
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a nonce prefix of the wrong size). Key metadata is untrusted input
+	// on a crypto read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+
+	// ErrOutputFileClosed is returned by [standardOutputFile.Write] when
+	// called after Close, or after a previous flush has poisoned the writer.
+	ErrOutputFileClosed = errors.New("encryption: write to closed StandardEncryptionManager output file")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+	switch m.dekLength {
+	case 16, 24, 32:
+	default:
+		return nil, fmt.Errorf("%w: DEK length must be 16, 24, or 32 bytes; got %d", ErrInvalidKeyLength, m.dekLength)
+	}
+
+	// The (key, nonce) uniqueness this block format relies on requires a
+	// freshly generated DEK for every file: the nonce is only 4 random bytes
+	// plus a block index, so reusing a DEK across files would reuse (DEK,
+	// nonce) pairs and break AES-GCM's security guarantees. Never cache or
+	// reuse plainDEK/wrappedDEK across calls to NewEncryptedOutputFile.
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 {
+		return nil, fmt.Errorf("%w: block-size must be positive, got %d", ErrInvalidKeyMetadata, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}
+	if len(meta.NoncePrefix) != 4 {
+		return nil, fmt.Errorf("%w: nonce-prefix must be 4 bytes, got %d", ErrInvalidKeyMetadata, len(meta.NoncePrefix))
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	return &standardInputFile{
+		underlying:      file,
+		aead:            aead,
+		noncePrefix:     meta.NoncePrefix,
+		blockSize:       meta.BlockSize,
+		plaintextLength: meta.PlaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newStandardAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %w", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// standardBlockNonce derives the AES-GCM nonce for blockIndex: the 4-byte
+// per-file random prefix followed by the 8-byte big-endian block index.
+// Uniqueness of the (key, nonce) pair across every block ever sealed with a
+// given DEK depends entirely on the DEK being freshly generated per file;
+// see the caution in [StandardEncryptionManager.NewEncryptedOutputFile].
+func standardBlockNonce(prefix []byte, blockIndex uint64) []byte {
+	nonce := make([]byte, 12)
+	copy(nonce, prefix)
+	binary.BigEndian.PutUint64(nonce[4:], blockIndex)
+
+	return nonce
+}
+
+// standardOutputFile is an [EncryptedOutputFile] that seals fixed-size
+// plaintext blocks with AES-GCM as they are written.
+type standardOutputFile struct {
+	icebergio.FileWriter
+
+	aead        cipher.AEAD
+	noncePrefix []byte
+	blockSize   int
+	keyID       string
+	wrappedKey  []byte
+
+	buf        []byte
+	blockIndex uint64
+	written    int64
+	closed     bool
+	err        error
+
+	keyMetadata EncryptionKeyMetadata
+}
+
+var _ EncryptedOutputFile = (*standardOutputFile)(nil)
+
+func (f *standardOutputFile) Write(p []byte) (int, error) {
+	if f.err != nil {
+		return 0, f.err
+	}
+	if f.closed {
+		return 0, ErrOutputFileClosed
+	}
+
+	total := len(p)
+	for len(p) > 0 {
+		space := f.blockSize - len(f.buf)
+		n := min(space, len(p))
+		f.buf = append(f.buf, p[:n]...)
+		p = p[n:]
+		if len(f.buf) == f.blockSize {
+			if err := f.flushBlock(); err != nil {
+				f.err = err
+
+				return total - len(p), err
+			}
+		}
+	}
+
+	return total, nil
+}
+
+// flushBlock seals and writes the currently buffered plaintext block.
+// f.written is only advanced once the ciphertext has actually reached the
+// underlying writer, so a failed flush never overcounts PlaintextLength.
+func (f *standardOutputFile) flushBlock() error {
+	ciphertext := f.aead.Seal(nil, standardBlockNonce(f.noncePrefix, f.blockIndex), f.buf, nil)
+	if _, err := f.FileWriter.Write(ciphertext); err != nil {
+		return fmt.Errorf("encryption: failed to write encrypted block: %w", err)
+	}
+	f.written += int64(len(f.buf))
+	f.blockIndex++
+	f.buf = f.buf[:0]
+
+	return nil
+}
+
+// ReadFrom copies from r, encrypting as data is written, satisfying
+// io.ReaderFrom (required by [icebergio.FileWriter]).
+func (f *standardOutputFile) ReadFrom(r io.Reader) (int64, error) {
+	buf := make([]byte, max(32*1024, f.blockSize))
+	var total int64
+	for {
+		n, err := r.Read(buf)
+		if n > 0 {
+			wn, werr := f.Write(buf[:n])
+			total += int64(wn)
+			if werr != nil {
+				return total, werr
+			}
+		}
+		if err == io.EOF {
+			break
+		}
+		if err != nil {
+			return total, err
+		}
+	}
+
+	return total, nil
+}
+
+// Close flushes any buffered partial block and finalizes the key metadata.
+// closed is only set once everything, including the underlying Close, has
+// succeeded; a failed Close poisons the writer (via f.err) so a retry
+// reliably reports the same error instead of masking the failure as success.
+func (f *standardOutputFile) Close() error {
+	if f.err != nil {
+		return f.err
+	}
+	if f.closed {
+		return nil
+	}
+
+	if len(f.buf) > 0 {
+		if err := f.flushBlock(); err != nil {
+			f.err = err
+			_ = f.FileWriter.Close()
+
+			return err
+		}
+	}
+
+	if f.keyMetadata == nil {
+		meta := standardKeyMetadata{
+			Version:         standardKeyMetadataVersion,
+			KeyID:           f.keyID,
+			WrappedKey:      f.wrappedKey,
+			NoncePrefix:     f.noncePrefix,
+			BlockSize:       f.blockSize,
+			PlaintextLength: f.written,
+		}
+		encoded, err := json.Marshal(meta)
+		if err != nil {
+			f.err = fmt.Errorf("encryption: failed to encode key metadata: %w", err)
+			_ = f.FileWriter.Close()
+
+			return f.err
+		}
+		f.keyMetadata = encoded
+	}
+
+	if err := f.FileWriter.Close(); err != nil {

Review Comment:
   **Major: direct underlying `Close` failures are not sticky.** This branch returns the error without assigning `f.err`; `keyMetadata` has already been published and `closed` is still false. A fail-once writer therefore makes the first `Close` fail and the second return `nil`, and `Write` is accepted between those calls with stale metadata. I reproduced that retry behavior. Keep this error sticky and avoid publishing final metadata until the underlying close succeeds; add a fail-first-`Close` regression test.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat(encryption): add StandardEncryptionManager [iceberg-go]

Posted by "hectar-glitches (via GitHub)" <gi...@apache.org>.
hectar-glitches commented on code in PR #1620:
URL: https://github.com/apache/iceberg-go/pull/1620#discussion_r3707729221


##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,488 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {

Review Comment:
   I think cross-engine interop isn't a goal for this PR as this is intentionally an iceberg-go-only envelope format for now (no header, 64 KB blocks, derived nonce, nil AAD, JSON key_metadata), not the AGS1 stream Java's StandardEncryptionManager produces. 
   
   If (or when) cross-engine interop becomes a requirement (which I agree it eventually needs to be, for tables written by one engine and read by another), we'd need to either adopt AGS1 directly or add a pluggable format layer. I'll bring this up on #1289.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat(encryption): add StandardEncryptionManager [iceberg-go]

Posted by "hectar-glitches (via GitHub)" <gi...@apache.org>.
hectar-glitches commented on code in PR #1620:
URL: https://github.com/apache/iceberg-go/pull/1620#discussion_r3707717934


##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,488 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	return &standardInputFile{
+		underlying:      file,
+		aead:            aead,
+		noncePrefix:     meta.NoncePrefix,
+		blockSize:       meta.BlockSize,
+		plaintextLength: meta.PlaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newStandardAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %v", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// standardBlockNonce derives the AES-GCM nonce for blockIndex: the 4-byte
+// per-file random prefix followed by the 8-byte big-endian block index. The
+// (key, nonce) pair is unique per block since the DEK is fresh per file and
+// no two blocks in the same file share an index.
+func standardBlockNonce(prefix []byte, blockIndex uint64) []byte {
+	nonce := make([]byte, 12)
+	copy(nonce, prefix)
+	binary.BigEndian.PutUint64(nonce[4:], blockIndex)
+
+	return nonce
+}
+
+// standardOutputFile is an [EncryptedOutputFile] that seals fixed-size
+// plaintext blocks with AES-GCM as they are written.
+type standardOutputFile struct {
+	icebergio.FileWriter
+
+	aead        cipher.AEAD
+	noncePrefix []byte
+	blockSize   int
+	keyID       string
+	wrappedKey  []byte
+
+	buf        []byte
+	blockIndex uint64
+	written    int64
+	closed     bool
+
+	keyMetadata EncryptionKeyMetadata
+}
+
+var _ EncryptedOutputFile = (*standardOutputFile)(nil)
+
+func (f *standardOutputFile) Write(p []byte) (int, error) {
+	total := len(p)
+	for len(p) > 0 {
+		space := f.blockSize - len(f.buf)

Review Comment:
   okay, the new 'NewEncryptedOutputFile' now rejects blockSize <= 0 with 'ErrInvalidBlockSize' before generating a DEK, so both 'WithBlockSize(-1)' (panic) and 'WithBlockSize(0)' (infinite loop) fail closed at construction time instead. Added tests for both cases.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat(encryption): add GoEnvelopeEncryptionManager for generic file envelope encryption [iceberg-go]

Posted by "hectar-glitches (via GitHub)" <gi...@apache.org>.
hectar-glitches commented on code in PR #1620:
URL: https://github.com/apache/iceberg-go/pull/1620#discussion_r3972470565


##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,883 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+	"math"
+	"sync"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [GoEnvelopeEncryptionManager].
+const (
+	// GoEnvelopeDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	GoEnvelopeDefaultDEKLength = 32
+
+	// GoEnvelopeDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	//
+	// This is not Java's Ciphers.PLAIN_BLOCK_SIZE (1 MiB, a compile-time
+	// constant there); see the [GoEnvelopeEncryptionManager] doc comment.
+	GoEnvelopeDefaultBlockSize = 64 * 1024
+
+	// GoEnvelopeMaxBlockSize is the largest plaintext block size accepted
+	// from the AES GCM Stream header on read, and the largest that
+	// [WithBlockSize] will configure for writing. The header's block-length
+	// field is unauthenticated, untrusted data (the Iceberg AES GCM Stream
+	// spec's "File length" note applies equally here); without a ceiling, a
+	// crafted header claiming e.g. 1<<40 bytes would force a huge
+	// allocation (see readBlock) before any authentication check can run.
+	GoEnvelopeMaxBlockSize = 128 * 1024 * 1024
+)
+
+// Sentinel errors returned by [GoEnvelopeEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile] when keyID is
+	// empty. GoEnvelopeEncryptionManager always encrypts, so it requires a
+	// KEK to wrap the generated DEK; use [PlaintextEncryptionManager] for
+	// unencrypted tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when keyMetadata
+	// is empty. GoEnvelopeEncryptionManager always decrypts, so it requires
+	// the per-file key metadata produced by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured block size is not
+	// positive or exceeds [GoEnvelopeMaxBlockSize].
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive and at most GoEnvelopeMaxBlockSize")
+
+	// ErrInvalidStreamHeader is returned when the AES GCM Stream header
+	// (the "AGS1" magic and little-endian block-length fields at the start
+	// of an encrypted file, per the Iceberg AES GCM Stream spec) is
+	// missing, truncated, or specifies a block length outside the
+	// supported range.
+	ErrInvalidStreamHeader = errors.New("encryption: invalid AES GCM Stream header")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a missing AAD prefix). Key metadata is untrusted input on a crypto
+	// read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+
+	// ErrOutputFileClosed is returned by [goEnvelopeOutputFile.Write] when
+	// called after Close, or after a previous flush has poisoned the writer.
+	// It wraps [fs.ErrClosed] so callers can test with errors.Is(err, fs.ErrClosed).
+	ErrOutputFileClosed = fmt.Errorf("encryption: write to closed GoEnvelopeEncryptionManager output file: %w", fs.ErrClosed)
+
+	// ErrBlockTruncated is returned by [goEnvelopeInputFile.ReadAt] when the
+	// underlying storage returns fewer ciphertext bytes for a block than its
+	// recorded length requires, indicating the file was truncated at rest.
+	// This is distinct from [ErrCiphertextTooShort], which [KeyManagementClient]
+	// implementations use for a too-short wrapped key or KMS-encrypted
+	// payload; keeping them separate lets a caller tell a malformed KMS blob
+	// apart from a short block read.
+	ErrBlockTruncated = errors.New("encryption: block truncated: read fewer ciphertext bytes than expected")
+)
+
+// Constants describing the Iceberg AES GCM Stream ("AGS1") wire format used
+// for the ciphertext produced by [GoEnvelopeEncryptionManager]. See
+// https://iceberg.apache.org/gcm-stream-spec/ for the full specification.
+const (
+	// gcmStreamMagic identifies an AES GCM Stream version 1 file.
+	gcmStreamMagic = "AGS1"
+
+	// gcmStreamHeaderLength is the length, in bytes, of the magic plus the
+	// little-endian block-length field written at the start of every file.
+	gcmStreamHeaderLength = len(gcmStreamMagic) + 4
+
+	// gcmStreamNonceLength is the length, in bytes, of the random AES-GCM
+	// nonce stored at the start of every cipher block.
+	gcmStreamNonceLength = 12
+
+	// gcmStreamTagLength is the length, in bytes, of the AES-GCM
+	// authentication tag appended to every cipher block's ciphertext.
+	gcmStreamTagLength = 16
+
+	// gcmStreamBlockOverhead is the number of ciphertext bytes added to
+	// each block beyond its plaintext length (nonce + tag).
+	gcmStreamBlockOverhead = gcmStreamNonceLength + gcmStreamTagLength
+
+	// gcmStreamAADPrefixLength is the length, in bytes, of the random
+	// per-file AAD prefix generated for new output files.
+	gcmStreamAADPrefixLength = 16
+)
+
+// goEnvelopeKeyMetadataVersion is the current encoding version written by
+// [GoEnvelopeEncryptionManager]. It is bumped whenever the on-disk layout of
+// goEnvelopeKeyMetadata changes incompatibly.
+const goEnvelopeKeyMetadataVersion = 1
+
+// goEnvelopeKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [GoEnvelopeEncryptionManager].
+//
+// This encoding is Go-specific, not Java's Avro-encoded StandardKeyMetadata;
+// see the [GoEnvelopeEncryptionManager] doc comment. Per the table spec,
+// DataFile/ManifestFile key_metadata is explicitly "implementation-specific";
+// what must be Iceberg AES GCM Stream compliant - and is - is the wire
+// format of the encrypted byte stream itself (magic, block framing, nonce
+// placement, and AAD; see the constants above).
+type goEnvelopeKeyMetadata struct {
+	Version    int    `json:"v"`
+	KeyID      string `json:"key-id"`
+	WrappedKey []byte `json:"wrapped-key"`
+
+	// BlockSize is the trusted plaintext block size the file was written
+	// with. It is validated bounded before any file I/O, and is what's
+	// actually used to size reads; the stream header's block-length field
+	// is untrusted (unauthenticated, attacker-influenced storage bytes) and
+	// is only compared against this value, never used directly to size an
+	// allocation.
+	BlockSize int64 `json:"block-size"`
+
+	// AADPrefix is combined with each block's little-endian index to form
+	// the AES GCM Stream additional authenticated data, binding every
+	// ciphertext block to this file and to its position so that blocks
+	// cannot be silently reordered, replayed from another file, or spliced
+	// in from elsewhere in the same file. It is not secret.
+	AADPrefix []byte `json:"aad-prefix"`
+
+	// PlaintextLength is the trusted total plaintext size used to compute
+	// the block count on read. Per the AES GCM Stream spec's "File length"
+	// note, a reader must use a length from a trusted source rather than
+	// the underlying storage's reported size, since storage size alone
+	// cannot distinguish a genuinely short file from one truncated by an
+	// attacker who does not also control this metadata.
+	PlaintextLength int64 `json:"plaintext-length"`
+}
+
+// GoEnvelopeEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks and written using the
+// Iceberg AES GCM Stream ("AGS1") format: a magic/block-length header
+// followed by independently authenticated blocks, each carrying its own
+// random nonce and authenticated with an AAD that binds it to the file and
+// to its position. This bounds memory usage and supports random access
+// (Seek/ReadAt) on the decrypted file without buffering or decrypting more
+// than the requested blocks.
+//
+// GoEnvelopeEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+//
+// Not interoperable with Java's StandardEncryptionManager: the AGS1 byte
+// stream framing (magic, block layout, nonce placement, AAD) matches the
+// spec, but the two implementations are not cross-readable. Java's reader
+// hard-requires a 1 MiB header block size (a compile-time constant there),
+// while [GoEnvelopeDefaultBlockSize] is 64 KiB, and Java decodes key
+// metadata as a 1-byte version plus Avro-encoded StandardKeyMetadata, while
+// this type encodes key metadata as JSON (goEnvelopeKeyMetadata). Files
+// written by one are not readable by the other.
+type GoEnvelopeEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*GoEnvelopeEncryptionManager)(nil)
+
+// GoEnvelopeManagerOption configures a [GoEnvelopeEncryptionManager] created
+// by [NewGoEnvelopeEncryptionManager].
+type GoEnvelopeManagerOption func(*GoEnvelopeEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) GoEnvelopeManagerOption {
+	return func(m *GoEnvelopeEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication. size must be
+// positive and at most [GoEnvelopeMaxBlockSize].
+func WithBlockSize(size int) GoEnvelopeManagerOption {
+	return func(m *GoEnvelopeEncryptionManager) { m.blockSize = size }
+}
+
+// NewGoEnvelopeEncryptionManager creates a [GoEnvelopeEncryptionManager]
+// backed by kms. kms must not be nil; NewGoEnvelopeEncryptionManager panics
+// if it is.
+func NewGoEnvelopeEncryptionManager(kms KeyManagementClient, opts ...GoEnvelopeManagerOption) *GoEnvelopeEncryptionManager {
+	if kms == nil {
+		panic("encryption: NewGoEnvelopeEncryptionManager: kms must not be nil")
+	}
+
+	m := &GoEnvelopeEncryptionManager{
+		kms:       kms,
+		dekLength: GoEnvelopeDefaultDEKLength,
+		blockSize: GoEnvelopeDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *GoEnvelopeEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 || m.blockSize > GoEnvelopeMaxBlockSize {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+	switch m.dekLength {
+	case 16, 24, 32:
+	default:
+		return nil, fmt.Errorf("%w: DEK length must be 16, 24, or 32 bytes; got %d", ErrInvalidKeyLength, m.dekLength)
+	}
+
+	// The (key, nonce) uniqueness this block format relies on requires a
+	// freshly generated DEK for every file: never cache or reuse
+	// plainDEK/wrappedDEK across calls to NewEncryptedOutputFile.
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = io.ReadFull(rand.Reader, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newGoEnvelopeAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	aadPrefix := make([]byte, gcmStreamAADPrefixLength)
+	if _, err := io.ReadFull(rand.Reader, aadPrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate AAD prefix: %w", err)
+	}
+
+	// Write the AES GCM Stream header (magic + little-endian block length)
+	// up front, before any ciphertext blocks, per the format spec.
+	header := make([]byte, gcmStreamHeaderLength)
+	copy(header, gcmStreamMagic)
+	binary.LittleEndian.PutUint32(header[len(gcmStreamMagic):], uint32(m.blockSize)) //nolint:gosec // bounded by ErrInvalidBlockSize above
+	if _, err := writer.Write(header); err != nil {
+		return nil, fmt.Errorf("encryption: failed to write stream header: %w", err)
+	}
+
+	return &goEnvelopeOutputFile{
+		FileWriter: writer,
+		aead:       aead,
+		aadPrefix:  aadPrefix,
+		blockSize:  m.blockSize,
+		keyID:      keyID,
+		wrappedKey: wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *GoEnvelopeEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta goEnvelopeKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != goEnvelopeKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 || meta.BlockSize > GoEnvelopeMaxBlockSize {
+		return nil, fmt.Errorf("%w: block-size must be positive and at most %d, got %d", ErrInvalidKeyMetadata, GoEnvelopeMaxBlockSize, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}
+	if len(meta.AADPrefix) == 0 {
+		return nil, fmt.Errorf("%w: aad-prefix must not be empty", ErrInvalidKeyMetadata)
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newGoEnvelopeAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	// headerBlockSize is untrusted (unauthenticated bytes read from
+	// storage): it is only ever compared against the trusted, already
+	// bounded meta.BlockSize below, never used to size a read or allocation.
+	headerBlockSize, err := readGCMStreamHeader(file)
+	if err != nil {
+		return nil, err
+	}
+	if headerBlockSize != meta.BlockSize {
+		return nil, fmt.Errorf("%w: stream header block length %d does not match key metadata block-size %d", ErrInvalidStreamHeader, headerBlockSize, meta.BlockSize)
+	}
+
+	return &goEnvelopeInputFile{
+		underlying:      file,
+		aead:            aead,
+		aadPrefix:       meta.AADPrefix,
+		blockSize:       meta.BlockSize,
+		plaintextLength: meta.PlaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newGoEnvelopeAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %w", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// readGCMStreamHeader reads and validates the AES GCM Stream magic and
+// block-length header at the start of file, returning the plaintext block
+// length. The header is untrusted, unauthenticated data, so the returned
+// length is bounded to [GoEnvelopeMaxBlockSize] before any allocation sized
+// by it takes place.
+func readGCMStreamHeader(file icebergio.File) (int64, error) {
+	header := make([]byte, gcmStreamHeaderLength)
+	n, err := file.ReadAt(header, 0)
+	if err != nil && !errors.Is(err, io.EOF) {
+		return 0, fmt.Errorf("encryption: failed to read stream header: %w", err)
+	}
+	if n != gcmStreamHeaderLength {
+		return 0, fmt.Errorf("%w: expected %d header bytes, got %d", ErrInvalidStreamHeader, gcmStreamHeaderLength, n)
+	}
+	if string(header[:len(gcmStreamMagic)]) != gcmStreamMagic {
+		return 0, fmt.Errorf("%w: missing %q magic", ErrInvalidStreamHeader, gcmStreamMagic)
+	}
+
+	blockSize := int64(binary.LittleEndian.Uint32(header[len(gcmStreamMagic):]))
+	if blockSize <= 0 || blockSize > GoEnvelopeMaxBlockSize {
+		return 0, fmt.Errorf("%w: block length %d out of supported range (0, %d]", ErrInvalidStreamHeader, blockSize, GoEnvelopeMaxBlockSize)
+	}
+
+	return blockSize, nil
+}
+
+// gcmStreamBlockAAD derives the AES-GCM additional authenticated data for
+// blockIndex: the per-file AAD prefix followed by the 4-byte little-endian
+// block index, per the Iceberg AES GCM Stream spec. This binds every
+// ciphertext block to this file and to its position, which matters because
+// blocks carry independent random nonces (rather than a nonce derived from
+// the block index): without the index in the AAD, an attacker able to
+// tamper with ciphertext at rest could silently reorder or splice blocks.
+func gcmStreamBlockAAD(prefix []byte, blockIndex uint32) []byte {
+	aad := make([]byte, len(prefix)+4)
+	copy(aad, prefix)
+	binary.LittleEndian.PutUint32(aad[len(prefix):], blockIndex)
+
+	return aad
+}
+
+// checkedMulInt64 returns a*b and true, or (0, false) if the multiplication
+// overflows int64.
+func checkedMulInt64(a, b int64) (int64, bool) {
+	if a == 0 || b == 0 {
+		return 0, true
+	}
+	result := a * b
+	if result/b != a {
+		return 0, false
+	}
+
+	return result, true
+}
+
+// checkedAddInt64 returns a+b and true, or (0, false) if the addition
+// overflows int64.
+func checkedAddInt64(a, b int64) (int64, bool) {
+	result := a + b
+	if (b > 0 && result < a) || (b < 0 && result > a) {
+		return 0, false
+	}
+
+	return result, true
+}
+
+// goEnvelopeOutputFile is an [EncryptedOutputFile] that seals fixed-size
+// plaintext blocks with AES-GCM as they are written, using the Iceberg AES
+// GCM Stream ("AGS1") wire format.
+type goEnvelopeOutputFile struct {
+	icebergio.FileWriter
+
+	aead       cipher.AEAD
+	aadPrefix  []byte
+	blockSize  int
+	keyID      string
+	wrappedKey []byte
+
+	buf        []byte
+	blockIndex uint32
+	written    int64
+	closed     bool
+	err        error
+
+	// underlyingClosed tracks whether FileWriter.Close has already been
+	// attempted, so a poisoned writer is closed exactly once regardless of
+	// whether the failure is first observed in Write or in Close.
+	underlyingClosed bool
+
+	keyMetadata EncryptionKeyMetadata
+}
+
+var _ EncryptedOutputFile = (*goEnvelopeOutputFile)(nil)
+
+// closeUnderlyingIgnoringError closes the underlying writer at most once.
+// The error is ignored: the caller is already reporting a more specific
+// failure (a flush or encode error), and this is best-effort cleanup so a
+// poisoned writer never leaks its underlying file descriptor or connection.
+//
+// defensive: today every call site sets f.err before calling this, and
+// Write/Close both bail out early once f.err is set, so the
+// underlyingClosed guard never actually stops a second Close in practice.
+// It stays as a hard invariant in case a future call site is added that
+// doesn't follow that pattern.
+func (f *goEnvelopeOutputFile) closeUnderlyingIgnoringError() {
+	if f.underlyingClosed {
+		return
+	}
+	f.underlyingClosed = true
+	_ = f.FileWriter.Close()
+}
+
+func (f *goEnvelopeOutputFile) Write(p []byte) (int, error) {
+	if f.err != nil {
+		return 0, f.err
+	}
+	if f.closed {
+		return 0, ErrOutputFileClosed
+	}
+
+	total := len(p)
+	consumed := 0 // bytes of p appended into f.buf so far in this call
+	accepted := 0 // bytes of p known to be durably flushed; reported on failure
+	for len(p) > 0 {
+		space := f.blockSize - len(f.buf)
+		n := min(space, len(p))
+		f.buf = append(f.buf, p[:n]...)
+		p = p[n:]
+		consumed += n
+		if len(f.buf) == f.blockSize {
+			if err := f.flushBlock(); err != nil {
+				f.err = err
+				f.closeUnderlyingIgnoringError()
+
+				return accepted, err
+			}
+			accepted = consumed
+		}
+	}
+
+	return total, nil
+}
+
+// flushBlock seals and writes the currently buffered plaintext block using a
+// fresh random nonce, per the Iceberg AES GCM Stream format. f.written is
+// only advanced once the ciphertext has actually reached the underlying
+// writer, so a failed flush never overcounts PlaintextLength.
+func (f *goEnvelopeOutputFile) flushBlock() error {
+	if f.blockIndex == math.MaxUint32 {
+		return errors.New("encryption: cannot write block: exceeded maximum block count")
+	}
+
+	nonce := make([]byte, gcmStreamNonceLength)
+	if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
+		return fmt.Errorf("encryption: failed to generate block nonce: %w", err)

Review Comment:
   i have added `TestGoEnvelopeEncryptionManager_BlockNoncesAreUnique` added, mutation-verified against a constant-nonce regression



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat(encryption): add GoEnvelopeEncryptionManager for generic file envelope encryption [iceberg-go]

Posted by "zeroshade (via GitHub)" <gi...@apache.org>.
zeroshade commented on code in PR #1620:
URL: https://github.com/apache/iceberg-go/pull/1620#discussion_r4158511963


##########
encryption/go_envelope_manager.go:
##########
@@ -0,0 +1,889 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+	"math"
+	"sync"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [GoEnvelopeEncryptionManager].
+const (
+	// GoEnvelopeDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	GoEnvelopeDefaultDEKLength = 32
+
+	// GoEnvelopeDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	//
+	// This is not Java's Ciphers.PLAIN_BLOCK_SIZE (1 MiB, a compile-time
+	// constant there); see the [GoEnvelopeEncryptionManager] doc comment.
+	GoEnvelopeDefaultBlockSize = 64 * 1024

Review Comment:
   Make the block size a fixed 1 MiB, matching Java's `Ciphers.PLAIN_BLOCK_SIZE` and iceberg-rust's `PLAIN_BLOCK_SIZE`. Java's `AesGcmInputStream.validateHeader` rejects any other header value, so a 64 KiB stream can't be read there regardless of key metadata.
   
   My call on the knob:
   - Drop `WithBlockSize`, `GoEnvelopeMaxBlockSize` and `ErrInvalidBlockSize`.
   - The writer always emits 1 MiB; the reader requires the header to say 1 MiB and returns `ErrInvalidStreamHeader` otherwise.
   
   That also removes the attacker-sized-allocation surface we went back and forth on. The tests built on `WithBlockSize(16)` (:69, :81, :91, ...) can use ~2.5 MiB payloads, as iceberg-rust's suite does.
   
   @tanmayrauth this supersedes the block-size validation from your 07-31 thread: the knob goes away instead.
   



##########
encryption/go_envelope_manager.go:
##########
@@ -0,0 +1,889 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+	"math"
+	"sync"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [GoEnvelopeEncryptionManager].
+const (
+	// GoEnvelopeDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	GoEnvelopeDefaultDEKLength = 32
+
+	// GoEnvelopeDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	//
+	// This is not Java's Ciphers.PLAIN_BLOCK_SIZE (1 MiB, a compile-time
+	// constant there); see the [GoEnvelopeEncryptionManager] doc comment.
+	GoEnvelopeDefaultBlockSize = 64 * 1024
+
+	// GoEnvelopeMaxBlockSize is the largest plaintext block size accepted
+	// from the AES GCM Stream header on read, and the largest that
+	// [WithBlockSize] will configure for writing. The header's block-length
+	// field is unauthenticated, untrusted data (the Iceberg AES GCM Stream
+	// spec's "File length" note applies equally here); without a ceiling, a
+	// crafted header claiming e.g. 1<<40 bytes would force a huge
+	// allocation (see readBlock) before any authentication check can run.
+	GoEnvelopeMaxBlockSize = 128 * 1024 * 1024
+)
+
+// Sentinel errors returned by [GoEnvelopeEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile] when keyID is
+	// empty. GoEnvelopeEncryptionManager always encrypts, so it requires a
+	// KEK to wrap the generated DEK; use [PlaintextEncryptionManager] for
+	// unencrypted tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when keyMetadata
+	// is empty. GoEnvelopeEncryptionManager always decrypts, so it requires
+	// the per-file key metadata produced by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured block size is not
+	// positive or exceeds [GoEnvelopeMaxBlockSize].
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive and at most GoEnvelopeMaxBlockSize")
+
+	// ErrInvalidStreamHeader is returned when the AES GCM Stream header
+	// (the "AGS1" magic and little-endian block-length fields at the start
+	// of an encrypted file, per the Iceberg AES GCM Stream spec) is
+	// missing, truncated, or specifies a block length outside the
+	// supported range.
+	ErrInvalidStreamHeader = errors.New("encryption: invalid AES GCM Stream header")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a missing AAD prefix). Key metadata is untrusted input on a crypto
+	// read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+
+	// ErrOutputFileClosed is returned by [goEnvelopeOutputFile.Write] when
+	// called after Close, or after a previous flush has poisoned the writer.
+	// It wraps [fs.ErrClosed] so callers can test with errors.Is(err, fs.ErrClosed).
+	ErrOutputFileClosed = fmt.Errorf("encryption: write to closed GoEnvelopeEncryptionManager output file: %w", fs.ErrClosed)
+
+	// ErrBlockTruncated is returned by [goEnvelopeInputFile.ReadAt] when the
+	// underlying storage returns fewer ciphertext bytes for a block than its
+	// recorded length requires, indicating the file was truncated at rest.
+	// This is distinct from [ErrCiphertextTooShort], which [KeyManagementClient]
+	// implementations use for a too-short wrapped key or KMS-encrypted
+	// payload; keeping them separate lets a caller tell a malformed KMS blob
+	// apart from a short block read.
+	ErrBlockTruncated = errors.New("encryption: block truncated: read fewer ciphertext bytes than expected")
+)
+
+// Constants describing the Iceberg AES GCM Stream ("AGS1") wire format used
+// for the ciphertext produced by [GoEnvelopeEncryptionManager]. See
+// https://iceberg.apache.org/gcm-stream-spec/ for the full specification.
+const (
+	// gcmStreamMagic identifies an AES GCM Stream version 1 file.
+	gcmStreamMagic = "AGS1"
+
+	// gcmStreamHeaderLength is the length, in bytes, of the magic plus the
+	// little-endian block-length field written at the start of every file.
+	gcmStreamHeaderLength = len(gcmStreamMagic) + 4
+
+	// gcmStreamNonceLength is the length, in bytes, of the random AES-GCM
+	// nonce stored at the start of every cipher block.
+	gcmStreamNonceLength = 12
+
+	// gcmStreamTagLength is the length, in bytes, of the AES-GCM
+	// authentication tag appended to every cipher block's ciphertext.
+	gcmStreamTagLength = 16
+
+	// gcmStreamBlockOverhead is the number of ciphertext bytes added to
+	// each block beyond its plaintext length (nonce + tag).
+	gcmStreamBlockOverhead = gcmStreamNonceLength + gcmStreamTagLength
+
+	// gcmStreamAADPrefixLength is the length, in bytes, of the random
+	// per-file AAD prefix generated for new output files.
+	gcmStreamAADPrefixLength = 16
+)
+
+// goEnvelopeKeyMetadataVersion is the current encoding version written by
+// [GoEnvelopeEncryptionManager]. It is bumped whenever the on-disk layout of
+// goEnvelopeKeyMetadata changes incompatibly.
+const goEnvelopeKeyMetadataVersion = 1
+
+// goEnvelopeKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [GoEnvelopeEncryptionManager].
+//
+// This encoding is Go-specific, not Java's Avro-encoded StandardKeyMetadata;
+// see the [GoEnvelopeEncryptionManager] doc comment. Per the table spec,
+// DataFile/ManifestFile key_metadata is explicitly "implementation-specific";
+// what must be Iceberg AES GCM Stream compliant - and is - is the wire
+// format of the encrypted byte stream itself (magic, block framing, nonce
+// placement, and AAD; see the constants above).
+type goEnvelopeKeyMetadata struct {

Review Comment:
   Replace the JSON blob with Java's `StandardKeyMetadata` encoding: a version byte `0x01` followed by an Avro binary record `{encryption_key: bytes, aad_prefix: bytes, file_length: long}`.
   
   - In Java's schema `aad_prefix` and `file_length` are optional `["null", T]` unions, so a present value is written as union branch 1 followed by the value. `github.com/twmb/avro` is already a dependency, or you can hand-encode the three fields.
   - `encryption_key` is the raw DEK. No KMS-wrapped key and no key-id go in the per-file metadata; see the comment on :280.
   - `file_length` is the encrypted length. `Close` knows it, so always write it. On read, derive the plaintext length from it the way Java's `AesGcmInputStream.calculatePlaintextLength` does, instead of storing `plaintext-length`. Java treats the field as optional; when it's absent, the trusted length has to come from the caller (the manifest entry). Don't fall back to `Stat().Size()`, per the AGS1 "File length" rule.
   
   Those bytes then match pyiceberg's and iceberg-rust's `StandardKeyMetadata`. Bytes produced by Java's `StandardKeyMetadata.buffer()` make the regression fixture.
   



##########
encryption/go_envelope_manager.go:
##########
@@ -0,0 +1,889 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+	"math"
+	"sync"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [GoEnvelopeEncryptionManager].
+const (
+	// GoEnvelopeDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	GoEnvelopeDefaultDEKLength = 32
+
+	// GoEnvelopeDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	//
+	// This is not Java's Ciphers.PLAIN_BLOCK_SIZE (1 MiB, a compile-time
+	// constant there); see the [GoEnvelopeEncryptionManager] doc comment.
+	GoEnvelopeDefaultBlockSize = 64 * 1024
+
+	// GoEnvelopeMaxBlockSize is the largest plaintext block size accepted
+	// from the AES GCM Stream header on read, and the largest that
+	// [WithBlockSize] will configure for writing. The header's block-length
+	// field is unauthenticated, untrusted data (the Iceberg AES GCM Stream
+	// spec's "File length" note applies equally here); without a ceiling, a
+	// crafted header claiming e.g. 1<<40 bytes would force a huge
+	// allocation (see readBlock) before any authentication check can run.
+	GoEnvelopeMaxBlockSize = 128 * 1024 * 1024
+)
+
+// Sentinel errors returned by [GoEnvelopeEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile] when keyID is
+	// empty. GoEnvelopeEncryptionManager always encrypts, so it requires a
+	// KEK to wrap the generated DEK; use [PlaintextEncryptionManager] for
+	// unencrypted tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when keyMetadata
+	// is empty. GoEnvelopeEncryptionManager always decrypts, so it requires
+	// the per-file key metadata produced by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured block size is not
+	// positive or exceeds [GoEnvelopeMaxBlockSize].
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive and at most GoEnvelopeMaxBlockSize")
+
+	// ErrInvalidStreamHeader is returned when the AES GCM Stream header
+	// (the "AGS1" magic and little-endian block-length fields at the start
+	// of an encrypted file, per the Iceberg AES GCM Stream spec) is
+	// missing, truncated, or specifies a block length outside the
+	// supported range.
+	ErrInvalidStreamHeader = errors.New("encryption: invalid AES GCM Stream header")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a missing AAD prefix). Key metadata is untrusted input on a crypto
+	// read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+
+	// ErrOutputFileClosed is returned by [goEnvelopeOutputFile.Write] when
+	// called after Close, or after a previous flush has poisoned the writer.
+	// It wraps [fs.ErrClosed] so callers can test with errors.Is(err, fs.ErrClosed).
+	ErrOutputFileClosed = fmt.Errorf("encryption: write to closed GoEnvelopeEncryptionManager output file: %w", fs.ErrClosed)

Review Comment:
   The doc says this error is returned "after a previous flush has poisoned the writer", but `Write` returns the sticky `f.err` before it ever checks `closed` (:513-515). After a failed flush, `errors.Is(err, ErrOutputFileClosed)` and `errors.Is(err, fs.ErrClosed)` are both false. Drop that clause.
   



##########
encryption/go_envelope_manager.go:
##########
@@ -0,0 +1,889 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+	"math"
+	"sync"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [GoEnvelopeEncryptionManager].
+const (
+	// GoEnvelopeDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	GoEnvelopeDefaultDEKLength = 32
+
+	// GoEnvelopeDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	//
+	// This is not Java's Ciphers.PLAIN_BLOCK_SIZE (1 MiB, a compile-time
+	// constant there); see the [GoEnvelopeEncryptionManager] doc comment.
+	GoEnvelopeDefaultBlockSize = 64 * 1024
+
+	// GoEnvelopeMaxBlockSize is the largest plaintext block size accepted
+	// from the AES GCM Stream header on read, and the largest that
+	// [WithBlockSize] will configure for writing. The header's block-length
+	// field is unauthenticated, untrusted data (the Iceberg AES GCM Stream
+	// spec's "File length" note applies equally here); without a ceiling, a
+	// crafted header claiming e.g. 1<<40 bytes would force a huge
+	// allocation (see readBlock) before any authentication check can run.
+	GoEnvelopeMaxBlockSize = 128 * 1024 * 1024
+)
+
+// Sentinel errors returned by [GoEnvelopeEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile] when keyID is
+	// empty. GoEnvelopeEncryptionManager always encrypts, so it requires a
+	// KEK to wrap the generated DEK; use [PlaintextEncryptionManager] for
+	// unencrypted tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when keyMetadata
+	// is empty. GoEnvelopeEncryptionManager always decrypts, so it requires
+	// the per-file key metadata produced by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured block size is not
+	// positive or exceeds [GoEnvelopeMaxBlockSize].
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive and at most GoEnvelopeMaxBlockSize")
+
+	// ErrInvalidStreamHeader is returned when the AES GCM Stream header
+	// (the "AGS1" magic and little-endian block-length fields at the start
+	// of an encrypted file, per the Iceberg AES GCM Stream spec) is
+	// missing, truncated, or specifies a block length outside the
+	// supported range.
+	ErrInvalidStreamHeader = errors.New("encryption: invalid AES GCM Stream header")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a missing AAD prefix). Key metadata is untrusted input on a crypto
+	// read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+
+	// ErrOutputFileClosed is returned by [goEnvelopeOutputFile.Write] when
+	// called after Close, or after a previous flush has poisoned the writer.
+	// It wraps [fs.ErrClosed] so callers can test with errors.Is(err, fs.ErrClosed).
+	ErrOutputFileClosed = fmt.Errorf("encryption: write to closed GoEnvelopeEncryptionManager output file: %w", fs.ErrClosed)
+
+	// ErrBlockTruncated is returned by [goEnvelopeInputFile.ReadAt] when the
+	// underlying storage returns fewer ciphertext bytes for a block than its
+	// recorded length requires, indicating the file was truncated at rest.
+	// This is distinct from [ErrCiphertextTooShort], which [KeyManagementClient]
+	// implementations use for a too-short wrapped key or KMS-encrypted
+	// payload; keeping them separate lets a caller tell a malformed KMS blob
+	// apart from a short block read.
+	ErrBlockTruncated = errors.New("encryption: block truncated: read fewer ciphertext bytes than expected")
+)
+
+// Constants describing the Iceberg AES GCM Stream ("AGS1") wire format used
+// for the ciphertext produced by [GoEnvelopeEncryptionManager]. See
+// https://iceberg.apache.org/gcm-stream-spec/ for the full specification.
+const (
+	// gcmStreamMagic identifies an AES GCM Stream version 1 file.
+	gcmStreamMagic = "AGS1"
+
+	// gcmStreamHeaderLength is the length, in bytes, of the magic plus the
+	// little-endian block-length field written at the start of every file.
+	gcmStreamHeaderLength = len(gcmStreamMagic) + 4
+
+	// gcmStreamNonceLength is the length, in bytes, of the random AES-GCM
+	// nonce stored at the start of every cipher block.
+	gcmStreamNonceLength = 12
+
+	// gcmStreamTagLength is the length, in bytes, of the AES-GCM
+	// authentication tag appended to every cipher block's ciphertext.
+	gcmStreamTagLength = 16
+
+	// gcmStreamBlockOverhead is the number of ciphertext bytes added to
+	// each block beyond its plaintext length (nonce + tag).
+	gcmStreamBlockOverhead = gcmStreamNonceLength + gcmStreamTagLength
+
+	// gcmStreamAADPrefixLength is the length, in bytes, of the random
+	// per-file AAD prefix generated for new output files.
+	gcmStreamAADPrefixLength = 16
+)
+
+// goEnvelopeKeyMetadataVersion is the current encoding version written by
+// [GoEnvelopeEncryptionManager]. It is bumped whenever the on-disk layout of
+// goEnvelopeKeyMetadata changes incompatibly.
+const goEnvelopeKeyMetadataVersion = 1
+
+// goEnvelopeKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [GoEnvelopeEncryptionManager].
+//
+// This encoding is Go-specific, not Java's Avro-encoded StandardKeyMetadata;
+// see the [GoEnvelopeEncryptionManager] doc comment. Per the table spec,
+// DataFile/ManifestFile key_metadata is explicitly "implementation-specific";
+// what must be Iceberg AES GCM Stream compliant - and is - is the wire
+// format of the encrypted byte stream itself (magic, block framing, nonce
+// placement, and AAD; see the constants above).
+type goEnvelopeKeyMetadata struct {
+	Version    int    `json:"v"`
+	KeyID      string `json:"key-id"`
+	WrappedKey []byte `json:"wrapped-key"`
+
+	// BlockSize is the trusted plaintext block size the file was written
+	// with. It is validated bounded before any file I/O, and is what's
+	// actually used to size reads; the stream header's block-length field
+	// is untrusted (unauthenticated, attacker-influenced storage bytes) and
+	// is only compared against this value, never used directly to size an
+	// allocation.
+	BlockSize int64 `json:"block-size"`
+
+	// AADPrefix is combined with each block's little-endian index to form
+	// the AES GCM Stream additional authenticated data, binding every
+	// ciphertext block to this file and to its position so that blocks
+	// cannot be silently reordered, replayed from another file, or spliced
+	// in from elsewhere in the same file. It is not secret.
+	AADPrefix []byte `json:"aad-prefix"`
+
+	// PlaintextLength is the trusted total plaintext size used to compute
+	// the block count on read. Per the AES GCM Stream spec's "File length"
+	// note, a reader must use a length from a trusted source rather than
+	// the underlying storage's reported size, since storage size alone
+	// cannot distinguish a genuinely short file from one truncated by an
+	// attacker who does not also control this metadata.
+	PlaintextLength int64 `json:"plaintext-length"`
+}
+
+// GoEnvelopeEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks and written using the
+// Iceberg AES GCM Stream ("AGS1") format: a magic/block-length header
+// followed by independently authenticated blocks, each carrying its own
+// random nonce and authenticated with an AAD that binds it to the file and
+// to its position. This bounds memory usage and supports random access
+// (Seek/ReadAt) on the decrypted file without buffering or decrypting more
+// than the requested blocks.
+//
+// GoEnvelopeEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+//
+// Not interoperable with Java's StandardEncryptionManager: the AGS1 byte
+// stream framing (magic, block layout, nonce placement, AAD) matches the
+// spec, but the two implementations are not cross-readable. Java's reader
+// hard-requires a 1 MiB header block size (a compile-time constant there),
+// while [GoEnvelopeDefaultBlockSize] is 64 KiB, and Java decodes key
+// metadata as a 1-byte version plus Avro-encoded StandardKeyMetadata, while
+// this type encodes key metadata as JSON (goEnvelopeKeyMetadata). Files
+// written by one are not readable by the other.
+type GoEnvelopeEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*GoEnvelopeEncryptionManager)(nil)
+
+// GoEnvelopeManagerOption configures a [GoEnvelopeEncryptionManager] created
+// by [NewGoEnvelopeEncryptionManager].
+type GoEnvelopeManagerOption func(*GoEnvelopeEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) GoEnvelopeManagerOption {
+	return func(m *GoEnvelopeEncryptionManager) { m.dekLength = length }
+}

Review Comment:
   `WithDEKLength` takes a generic name in package `encryption` but only configures this type. Once this is the Java-compatible manager, and the KEK layer adds more options, name it for what it maps to, the `encryption.data-key-length` table property. Either share one option type across the package's managers or use a type-specific name. Renaming after a release breaks callers.
   
   Two related points:
   - Java's default for that property is 16 bytes (`ENCRYPTION_DEK_LENGTH_DEFAULT`), and iceberg-rust also defaults to 128-bit. Match it unless there's a reason not to.
   - Once the format matches, the `StandardEncryptionManager` name is accurate again, so renaming back is fine.
   



##########
encryption/go_envelope_manager.go:
##########
@@ -0,0 +1,889 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+	"math"
+	"sync"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [GoEnvelopeEncryptionManager].
+const (
+	// GoEnvelopeDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	GoEnvelopeDefaultDEKLength = 32
+
+	// GoEnvelopeDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	//
+	// This is not Java's Ciphers.PLAIN_BLOCK_SIZE (1 MiB, a compile-time
+	// constant there); see the [GoEnvelopeEncryptionManager] doc comment.
+	GoEnvelopeDefaultBlockSize = 64 * 1024
+
+	// GoEnvelopeMaxBlockSize is the largest plaintext block size accepted
+	// from the AES GCM Stream header on read, and the largest that
+	// [WithBlockSize] will configure for writing. The header's block-length
+	// field is unauthenticated, untrusted data (the Iceberg AES GCM Stream
+	// spec's "File length" note applies equally here); without a ceiling, a
+	// crafted header claiming e.g. 1<<40 bytes would force a huge
+	// allocation (see readBlock) before any authentication check can run.
+	GoEnvelopeMaxBlockSize = 128 * 1024 * 1024
+)
+
+// Sentinel errors returned by [GoEnvelopeEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile] when keyID is
+	// empty. GoEnvelopeEncryptionManager always encrypts, so it requires a
+	// KEK to wrap the generated DEK; use [PlaintextEncryptionManager] for
+	// unencrypted tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when keyMetadata
+	// is empty. GoEnvelopeEncryptionManager always decrypts, so it requires
+	// the per-file key metadata produced by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured block size is not
+	// positive or exceeds [GoEnvelopeMaxBlockSize].
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive and at most GoEnvelopeMaxBlockSize")
+
+	// ErrInvalidStreamHeader is returned when the AES GCM Stream header
+	// (the "AGS1" magic and little-endian block-length fields at the start
+	// of an encrypted file, per the Iceberg AES GCM Stream spec) is
+	// missing, truncated, or specifies a block length outside the
+	// supported range.
+	ErrInvalidStreamHeader = errors.New("encryption: invalid AES GCM Stream header")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a missing AAD prefix). Key metadata is untrusted input on a crypto
+	// read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+
+	// ErrOutputFileClosed is returned by [goEnvelopeOutputFile.Write] when
+	// called after Close, or after a previous flush has poisoned the writer.
+	// It wraps [fs.ErrClosed] so callers can test with errors.Is(err, fs.ErrClosed).
+	ErrOutputFileClosed = fmt.Errorf("encryption: write to closed GoEnvelopeEncryptionManager output file: %w", fs.ErrClosed)
+
+	// ErrBlockTruncated is returned by [goEnvelopeInputFile.ReadAt] when the
+	// underlying storage returns fewer ciphertext bytes for a block than its
+	// recorded length requires, indicating the file was truncated at rest.
+	// This is distinct from [ErrCiphertextTooShort], which [KeyManagementClient]
+	// implementations use for a too-short wrapped key or KMS-encrypted
+	// payload; keeping them separate lets a caller tell a malformed KMS blob
+	// apart from a short block read.
+	ErrBlockTruncated = errors.New("encryption: block truncated: read fewer ciphertext bytes than expected")
+)
+
+// Constants describing the Iceberg AES GCM Stream ("AGS1") wire format used
+// for the ciphertext produced by [GoEnvelopeEncryptionManager]. See
+// https://iceberg.apache.org/gcm-stream-spec/ for the full specification.
+const (
+	// gcmStreamMagic identifies an AES GCM Stream version 1 file.
+	gcmStreamMagic = "AGS1"
+
+	// gcmStreamHeaderLength is the length, in bytes, of the magic plus the
+	// little-endian block-length field written at the start of every file.
+	gcmStreamHeaderLength = len(gcmStreamMagic) + 4
+
+	// gcmStreamNonceLength is the length, in bytes, of the random AES-GCM
+	// nonce stored at the start of every cipher block.
+	gcmStreamNonceLength = 12
+
+	// gcmStreamTagLength is the length, in bytes, of the AES-GCM
+	// authentication tag appended to every cipher block's ciphertext.
+	gcmStreamTagLength = 16
+
+	// gcmStreamBlockOverhead is the number of ciphertext bytes added to
+	// each block beyond its plaintext length (nonce + tag).
+	gcmStreamBlockOverhead = gcmStreamNonceLength + gcmStreamTagLength
+
+	// gcmStreamAADPrefixLength is the length, in bytes, of the random
+	// per-file AAD prefix generated for new output files.
+	gcmStreamAADPrefixLength = 16
+)
+
+// goEnvelopeKeyMetadataVersion is the current encoding version written by
+// [GoEnvelopeEncryptionManager]. It is bumped whenever the on-disk layout of
+// goEnvelopeKeyMetadata changes incompatibly.
+const goEnvelopeKeyMetadataVersion = 1
+
+// goEnvelopeKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [GoEnvelopeEncryptionManager].
+//
+// This encoding is Go-specific, not Java's Avro-encoded StandardKeyMetadata;
+// see the [GoEnvelopeEncryptionManager] doc comment. Per the table spec,
+// DataFile/ManifestFile key_metadata is explicitly "implementation-specific";
+// what must be Iceberg AES GCM Stream compliant - and is - is the wire
+// format of the encrypted byte stream itself (magic, block framing, nonce
+// placement, and AAD; see the constants above).
+type goEnvelopeKeyMetadata struct {
+	Version    int    `json:"v"`
+	KeyID      string `json:"key-id"`
+	WrappedKey []byte `json:"wrapped-key"`
+
+	// BlockSize is the trusted plaintext block size the file was written
+	// with. It is validated bounded before any file I/O, and is what's
+	// actually used to size reads; the stream header's block-length field
+	// is untrusted (unauthenticated, attacker-influenced storage bytes) and
+	// is only compared against this value, never used directly to size an
+	// allocation.
+	BlockSize int64 `json:"block-size"`
+
+	// AADPrefix is combined with each block's little-endian index to form
+	// the AES GCM Stream additional authenticated data, binding every
+	// ciphertext block to this file and to its position so that blocks
+	// cannot be silently reordered, replayed from another file, or spliced
+	// in from elsewhere in the same file. It is not secret.
+	AADPrefix []byte `json:"aad-prefix"`
+
+	// PlaintextLength is the trusted total plaintext size used to compute
+	// the block count on read. Per the AES GCM Stream spec's "File length"
+	// note, a reader must use a length from a trusted source rather than
+	// the underlying storage's reported size, since storage size alone
+	// cannot distinguish a genuinely short file from one truncated by an
+	// attacker who does not also control this metadata.
+	PlaintextLength int64 `json:"plaintext-length"`
+}
+
+// GoEnvelopeEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks and written using the
+// Iceberg AES GCM Stream ("AGS1") format: a magic/block-length header
+// followed by independently authenticated blocks, each carrying its own
+// random nonce and authenticated with an AAD that binds it to the file and
+// to its position. This bounds memory usage and supports random access
+// (Seek/ReadAt) on the decrypted file without buffering or decrypting more
+// than the requested blocks.
+//
+// GoEnvelopeEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+//
+// Not interoperable with Java's StandardEncryptionManager: the AGS1 byte
+// stream framing (magic, block layout, nonce placement, AAD) matches the
+// spec, but the two implementations are not cross-readable. Java's reader
+// hard-requires a 1 MiB header block size (a compile-time constant there),
+// while [GoEnvelopeDefaultBlockSize] is 64 KiB, and Java decodes key
+// metadata as a 1-byte version plus Avro-encoded StandardKeyMetadata, while
+// this type encodes key metadata as JSON (goEnvelopeKeyMetadata). Files
+// written by one are not readable by the other.
+type GoEnvelopeEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*GoEnvelopeEncryptionManager)(nil)
+
+// GoEnvelopeManagerOption configures a [GoEnvelopeEncryptionManager] created
+// by [NewGoEnvelopeEncryptionManager].
+type GoEnvelopeManagerOption func(*GoEnvelopeEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) GoEnvelopeManagerOption {
+	return func(m *GoEnvelopeEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication. size must be
+// positive and at most [GoEnvelopeMaxBlockSize].
+func WithBlockSize(size int) GoEnvelopeManagerOption {
+	return func(m *GoEnvelopeEncryptionManager) { m.blockSize = size }
+}
+
+// NewGoEnvelopeEncryptionManager creates a [GoEnvelopeEncryptionManager]
+// backed by kms. kms must not be nil; NewGoEnvelopeEncryptionManager panics
+// if it is.
+func NewGoEnvelopeEncryptionManager(kms KeyManagementClient, opts ...GoEnvelopeManagerOption) *GoEnvelopeEncryptionManager {
+	if kms == nil {
+		panic("encryption: NewGoEnvelopeEncryptionManager: kms must not be nil")
+	}
+
+	m := &GoEnvelopeEncryptionManager{
+		kms:       kms,
+		dekLength: GoEnvelopeDefaultDEKLength,
+		blockSize: GoEnvelopeDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *GoEnvelopeEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 || m.blockSize > GoEnvelopeMaxBlockSize {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+	switch m.dekLength {
+	case 16, 24, 32:
+	default:
+		return nil, fmt.Errorf("%w: DEK length must be 16, 24, or 32 bytes; got %d", ErrInvalidKeyLength, m.dekLength)
+	}
+
+	// The (key, nonce) uniqueness this block format relies on requires a
+	// freshly generated DEK for every file: never cache or reuse
+	// plainDEK/wrappedDEK across calls to NewEncryptedOutputFile.
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = io.ReadFull(rand.Reader, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newGoEnvelopeAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	aadPrefix := make([]byte, gcmStreamAADPrefixLength)
+	if _, err := io.ReadFull(rand.Reader, aadPrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate AAD prefix: %w", err)
+	}
+
+	// Write the AES GCM Stream header (magic + little-endian block length)
+	// up front, before any ciphertext blocks, per the format spec.
+	header := make([]byte, gcmStreamHeaderLength)
+	copy(header, gcmStreamMagic)
+	binary.LittleEndian.PutUint32(header[len(gcmStreamMagic):], uint32(m.blockSize)) //nolint:gosec // bounded by ErrInvalidBlockSize above
+	if _, err := writer.Write(header); err != nil {
+		return nil, fmt.Errorf("encryption: failed to write stream header: %w", err)
+	}
+
+	return &goEnvelopeOutputFile{
+		FileWriter: writer,
+		aead:       aead,
+		aadPrefix:  aadPrefix,
+		blockSize:  m.blockSize,
+		keyID:      keyID,
+		wrappedKey: wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *GoEnvelopeEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta goEnvelopeKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != goEnvelopeKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 || meta.BlockSize > GoEnvelopeMaxBlockSize {
+		return nil, fmt.Errorf("%w: block-size must be positive and at most %d, got %d", ErrInvalidKeyMetadata, GoEnvelopeMaxBlockSize, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}
+	// AADPrefix is bounded to exactly the length this implementation's own
+	// writer emits (gcmStreamAADPrefixLength): key metadata is Go-specific
+	// (not cross-implementation compatible; see the type doc comment), so
+	// there is no other length a valid file could carry. Without this
+	// ceiling, an oversized prefix would be re-allocated on every
+	// gcmStreamBlockAAD call in readBlock.
+	if len(meta.AADPrefix) != gcmStreamAADPrefixLength {
+		return nil, fmt.Errorf("%w: aad-prefix must be exactly %d bytes, got %d", ErrInvalidKeyMetadata, gcmStreamAADPrefixLength, len(meta.AADPrefix))
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newGoEnvelopeAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	// headerBlockSize is untrusted (unauthenticated bytes read from
+	// storage): it is only ever compared against the trusted, already
+	// bounded meta.BlockSize below, never used to size a read or allocation.
+	headerBlockSize, err := readGCMStreamHeader(file)
+	if err != nil {
+		return nil, err
+	}
+	if headerBlockSize != meta.BlockSize {
+		return nil, fmt.Errorf("%w: stream header block length %d does not match key metadata block-size %d", ErrInvalidStreamHeader, headerBlockSize, meta.BlockSize)
+	}
+
+	return &goEnvelopeInputFile{
+		underlying:      file,
+		aead:            aead,
+		aadPrefix:       meta.AADPrefix,
+		blockSize:       meta.BlockSize,
+		plaintextLength: meta.PlaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newGoEnvelopeAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %w", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// readGCMStreamHeader reads and validates the AES GCM Stream magic and
+// block-length header at the start of file, returning the plaintext block
+// length. The header is untrusted, unauthenticated data, so the returned
+// length is bounded to [GoEnvelopeMaxBlockSize] before any allocation sized
+// by it takes place.
+func readGCMStreamHeader(file icebergio.File) (int64, error) {
+	header := make([]byte, gcmStreamHeaderLength)
+	n, err := file.ReadAt(header, 0)
+	if err != nil && !errors.Is(err, io.EOF) {
+		return 0, fmt.Errorf("encryption: failed to read stream header: %w", err)
+	}
+	if n != gcmStreamHeaderLength {
+		return 0, fmt.Errorf("%w: expected %d header bytes, got %d", ErrInvalidStreamHeader, gcmStreamHeaderLength, n)
+	}
+	if string(header[:len(gcmStreamMagic)]) != gcmStreamMagic {
+		return 0, fmt.Errorf("%w: missing %q magic", ErrInvalidStreamHeader, gcmStreamMagic)
+	}
+
+	blockSize := int64(binary.LittleEndian.Uint32(header[len(gcmStreamMagic):]))
+	if blockSize <= 0 || blockSize > GoEnvelopeMaxBlockSize {
+		return 0, fmt.Errorf("%w: block length %d out of supported range (0, %d]", ErrInvalidStreamHeader, blockSize, GoEnvelopeMaxBlockSize)
+	}
+
+	return blockSize, nil
+}
+
+// gcmStreamBlockAAD derives the AES-GCM additional authenticated data for
+// blockIndex: the per-file AAD prefix followed by the 4-byte little-endian
+// block index, per the Iceberg AES GCM Stream spec. This binds every
+// ciphertext block to this file and to its position, which matters because
+// blocks carry independent random nonces (rather than a nonce derived from
+// the block index): without the index in the AAD, an attacker able to
+// tamper with ciphertext at rest could silently reorder or splice blocks.
+func gcmStreamBlockAAD(prefix []byte, blockIndex uint32) []byte {
+	aad := make([]byte, len(prefix)+4)
+	copy(aad, prefix)
+	binary.LittleEndian.PutUint32(aad[len(prefix):], blockIndex)

Review Comment:
   Nothing in the suite checks this against the spec. If I change this line to `binary.BigEndian` (the spec requires 4-byte little-endian), every test still passes, because the writer and reader share this helper.
   
   Add a test that decodes the output with only `crypto/aes` and `crypto/cipher`:
   - parse the `AGS1` header
   - split each block into `nonce‖ciphertext‖tag`
   - build the AAD by hand as `aadPrefix‖LE32(i)` and call `Open`
   
   A decoder like that fails at block 1 under the BigEndian change. If you can produce one, also check in a Java-written fixture (encrypted file plus `StandardKeyMetadata` bytes) and decrypt it in a test. That's the actual interop check.
   



##########
encryption/go_envelope_manager.go:
##########
@@ -0,0 +1,889 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+	"math"
+	"sync"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [GoEnvelopeEncryptionManager].
+const (
+	// GoEnvelopeDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	GoEnvelopeDefaultDEKLength = 32
+
+	// GoEnvelopeDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	//
+	// This is not Java's Ciphers.PLAIN_BLOCK_SIZE (1 MiB, a compile-time
+	// constant there); see the [GoEnvelopeEncryptionManager] doc comment.
+	GoEnvelopeDefaultBlockSize = 64 * 1024
+
+	// GoEnvelopeMaxBlockSize is the largest plaintext block size accepted
+	// from the AES GCM Stream header on read, and the largest that
+	// [WithBlockSize] will configure for writing. The header's block-length
+	// field is unauthenticated, untrusted data (the Iceberg AES GCM Stream
+	// spec's "File length" note applies equally here); without a ceiling, a
+	// crafted header claiming e.g. 1<<40 bytes would force a huge
+	// allocation (see readBlock) before any authentication check can run.
+	GoEnvelopeMaxBlockSize = 128 * 1024 * 1024
+)
+
+// Sentinel errors returned by [GoEnvelopeEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile] when keyID is
+	// empty. GoEnvelopeEncryptionManager always encrypts, so it requires a
+	// KEK to wrap the generated DEK; use [PlaintextEncryptionManager] for
+	// unencrypted tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when keyMetadata
+	// is empty. GoEnvelopeEncryptionManager always decrypts, so it requires
+	// the per-file key metadata produced by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured block size is not
+	// positive or exceeds [GoEnvelopeMaxBlockSize].
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive and at most GoEnvelopeMaxBlockSize")
+
+	// ErrInvalidStreamHeader is returned when the AES GCM Stream header
+	// (the "AGS1" magic and little-endian block-length fields at the start
+	// of an encrypted file, per the Iceberg AES GCM Stream spec) is
+	// missing, truncated, or specifies a block length outside the
+	// supported range.
+	ErrInvalidStreamHeader = errors.New("encryption: invalid AES GCM Stream header")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a missing AAD prefix). Key metadata is untrusted input on a crypto
+	// read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+
+	// ErrOutputFileClosed is returned by [goEnvelopeOutputFile.Write] when
+	// called after Close, or after a previous flush has poisoned the writer.
+	// It wraps [fs.ErrClosed] so callers can test with errors.Is(err, fs.ErrClosed).
+	ErrOutputFileClosed = fmt.Errorf("encryption: write to closed GoEnvelopeEncryptionManager output file: %w", fs.ErrClosed)
+
+	// ErrBlockTruncated is returned by [goEnvelopeInputFile.ReadAt] when the
+	// underlying storage returns fewer ciphertext bytes for a block than its
+	// recorded length requires, indicating the file was truncated at rest.
+	// This is distinct from [ErrCiphertextTooShort], which [KeyManagementClient]
+	// implementations use for a too-short wrapped key or KMS-encrypted
+	// payload; keeping them separate lets a caller tell a malformed KMS blob
+	// apart from a short block read.
+	ErrBlockTruncated = errors.New("encryption: block truncated: read fewer ciphertext bytes than expected")
+)
+
+// Constants describing the Iceberg AES GCM Stream ("AGS1") wire format used
+// for the ciphertext produced by [GoEnvelopeEncryptionManager]. See
+// https://iceberg.apache.org/gcm-stream-spec/ for the full specification.
+const (
+	// gcmStreamMagic identifies an AES GCM Stream version 1 file.
+	gcmStreamMagic = "AGS1"
+
+	// gcmStreamHeaderLength is the length, in bytes, of the magic plus the
+	// little-endian block-length field written at the start of every file.
+	gcmStreamHeaderLength = len(gcmStreamMagic) + 4
+
+	// gcmStreamNonceLength is the length, in bytes, of the random AES-GCM
+	// nonce stored at the start of every cipher block.
+	gcmStreamNonceLength = 12
+
+	// gcmStreamTagLength is the length, in bytes, of the AES-GCM
+	// authentication tag appended to every cipher block's ciphertext.
+	gcmStreamTagLength = 16
+
+	// gcmStreamBlockOverhead is the number of ciphertext bytes added to
+	// each block beyond its plaintext length (nonce + tag).
+	gcmStreamBlockOverhead = gcmStreamNonceLength + gcmStreamTagLength
+
+	// gcmStreamAADPrefixLength is the length, in bytes, of the random
+	// per-file AAD prefix generated for new output files.
+	gcmStreamAADPrefixLength = 16
+)
+
+// goEnvelopeKeyMetadataVersion is the current encoding version written by
+// [GoEnvelopeEncryptionManager]. It is bumped whenever the on-disk layout of
+// goEnvelopeKeyMetadata changes incompatibly.
+const goEnvelopeKeyMetadataVersion = 1
+
+// goEnvelopeKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [GoEnvelopeEncryptionManager].
+//
+// This encoding is Go-specific, not Java's Avro-encoded StandardKeyMetadata;
+// see the [GoEnvelopeEncryptionManager] doc comment. Per the table spec,
+// DataFile/ManifestFile key_metadata is explicitly "implementation-specific";
+// what must be Iceberg AES GCM Stream compliant - and is - is the wire
+// format of the encrypted byte stream itself (magic, block framing, nonce
+// placement, and AAD; see the constants above).
+type goEnvelopeKeyMetadata struct {
+	Version    int    `json:"v"`
+	KeyID      string `json:"key-id"`
+	WrappedKey []byte `json:"wrapped-key"`
+
+	// BlockSize is the trusted plaintext block size the file was written
+	// with. It is validated bounded before any file I/O, and is what's
+	// actually used to size reads; the stream header's block-length field
+	// is untrusted (unauthenticated, attacker-influenced storage bytes) and
+	// is only compared against this value, never used directly to size an
+	// allocation.
+	BlockSize int64 `json:"block-size"`
+
+	// AADPrefix is combined with each block's little-endian index to form
+	// the AES GCM Stream additional authenticated data, binding every
+	// ciphertext block to this file and to its position so that blocks
+	// cannot be silently reordered, replayed from another file, or spliced
+	// in from elsewhere in the same file. It is not secret.
+	AADPrefix []byte `json:"aad-prefix"`
+
+	// PlaintextLength is the trusted total plaintext size used to compute
+	// the block count on read. Per the AES GCM Stream spec's "File length"
+	// note, a reader must use a length from a trusted source rather than
+	// the underlying storage's reported size, since storage size alone
+	// cannot distinguish a genuinely short file from one truncated by an
+	// attacker who does not also control this metadata.
+	PlaintextLength int64 `json:"plaintext-length"`
+}
+
+// GoEnvelopeEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks and written using the
+// Iceberg AES GCM Stream ("AGS1") format: a magic/block-length header
+// followed by independently authenticated blocks, each carrying its own
+// random nonce and authenticated with an AAD that binds it to the file and
+// to its position. This bounds memory usage and supports random access
+// (Seek/ReadAt) on the decrypted file without buffering or decrypting more
+// than the requested blocks.
+//
+// GoEnvelopeEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+//
+// Not interoperable with Java's StandardEncryptionManager: the AGS1 byte
+// stream framing (magic, block layout, nonce placement, AAD) matches the
+// spec, but the two implementations are not cross-readable. Java's reader
+// hard-requires a 1 MiB header block size (a compile-time constant there),
+// while [GoEnvelopeDefaultBlockSize] is 64 KiB, and Java decodes key
+// metadata as a 1-byte version plus Avro-encoded StandardKeyMetadata, while
+// this type encodes key metadata as JSON (goEnvelopeKeyMetadata). Files
+// written by one are not readable by the other.
+type GoEnvelopeEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*GoEnvelopeEncryptionManager)(nil)
+
+// GoEnvelopeManagerOption configures a [GoEnvelopeEncryptionManager] created
+// by [NewGoEnvelopeEncryptionManager].
+type GoEnvelopeManagerOption func(*GoEnvelopeEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) GoEnvelopeManagerOption {
+	return func(m *GoEnvelopeEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication. size must be
+// positive and at most [GoEnvelopeMaxBlockSize].
+func WithBlockSize(size int) GoEnvelopeManagerOption {
+	return func(m *GoEnvelopeEncryptionManager) { m.blockSize = size }
+}
+
+// NewGoEnvelopeEncryptionManager creates a [GoEnvelopeEncryptionManager]
+// backed by kms. kms must not be nil; NewGoEnvelopeEncryptionManager panics
+// if it is.
+func NewGoEnvelopeEncryptionManager(kms KeyManagementClient, opts ...GoEnvelopeManagerOption) *GoEnvelopeEncryptionManager {
+	if kms == nil {
+		panic("encryption: NewGoEnvelopeEncryptionManager: kms must not be nil")
+	}
+
+	m := &GoEnvelopeEncryptionManager{
+		kms:       kms,
+		dekLength: GoEnvelopeDefaultDEKLength,
+		blockSize: GoEnvelopeDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *GoEnvelopeEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 || m.blockSize > GoEnvelopeMaxBlockSize {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+	switch m.dekLength {
+	case 16, 24, 32:
+	default:
+		return nil, fmt.Errorf("%w: DEK length must be 16, 24, or 32 bytes; got %d", ErrInvalidKeyLength, m.dekLength)
+	}
+
+	// The (key, nonce) uniqueness this block format relies on requires a
+	// freshly generated DEK for every file: never cache or reuse
+	// plainDEK/wrappedDEK across calls to NewEncryptedOutputFile.
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = io.ReadFull(rand.Reader, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newGoEnvelopeAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	aadPrefix := make([]byte, gcmStreamAADPrefixLength)
+	if _, err := io.ReadFull(rand.Reader, aadPrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate AAD prefix: %w", err)
+	}
+
+	// Write the AES GCM Stream header (magic + little-endian block length)
+	// up front, before any ciphertext blocks, per the format spec.
+	header := make([]byte, gcmStreamHeaderLength)
+	copy(header, gcmStreamMagic)
+	binary.LittleEndian.PutUint32(header[len(gcmStreamMagic):], uint32(m.blockSize)) //nolint:gosec // bounded by ErrInvalidBlockSize above
+	if _, err := writer.Write(header); err != nil {
+		return nil, fmt.Errorf("encryption: failed to write stream header: %w", err)
+	}
+
+	return &goEnvelopeOutputFile{
+		FileWriter: writer,
+		aead:       aead,
+		aadPrefix:  aadPrefix,
+		blockSize:  m.blockSize,
+		keyID:      keyID,
+		wrappedKey: wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *GoEnvelopeEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta goEnvelopeKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != goEnvelopeKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 || meta.BlockSize > GoEnvelopeMaxBlockSize {
+		return nil, fmt.Errorf("%w: block-size must be positive and at most %d, got %d", ErrInvalidKeyMetadata, GoEnvelopeMaxBlockSize, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}
+	// AADPrefix is bounded to exactly the length this implementation's own
+	// writer emits (gcmStreamAADPrefixLength): key metadata is Go-specific
+	// (not cross-implementation compatible; see the type doc comment), so
+	// there is no other length a valid file could carry. Without this
+	// ceiling, an oversized prefix would be re-allocated on every
+	// gcmStreamBlockAAD call in readBlock.
+	if len(meta.AADPrefix) != gcmStreamAADPrefixLength {
+		return nil, fmt.Errorf("%w: aad-prefix must be exactly %d bytes, got %d", ErrInvalidKeyMetadata, gcmStreamAADPrefixLength, len(meta.AADPrefix))
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newGoEnvelopeAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	// headerBlockSize is untrusted (unauthenticated bytes read from
+	// storage): it is only ever compared against the trusted, already
+	// bounded meta.BlockSize below, never used to size a read or allocation.
+	headerBlockSize, err := readGCMStreamHeader(file)
+	if err != nil {
+		return nil, err
+	}
+	if headerBlockSize != meta.BlockSize {
+		return nil, fmt.Errorf("%w: stream header block length %d does not match key metadata block-size %d", ErrInvalidStreamHeader, headerBlockSize, meta.BlockSize)
+	}
+
+	return &goEnvelopeInputFile{
+		underlying:      file,
+		aead:            aead,
+		aadPrefix:       meta.AADPrefix,
+		blockSize:       meta.BlockSize,
+		plaintextLength: meta.PlaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newGoEnvelopeAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %w", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// readGCMStreamHeader reads and validates the AES GCM Stream magic and
+// block-length header at the start of file, returning the plaintext block
+// length. The header is untrusted, unauthenticated data, so the returned
+// length is bounded to [GoEnvelopeMaxBlockSize] before any allocation sized
+// by it takes place.

Review Comment:
   These comments still describe the old design, where the header's block length sized allocations. Now:
   - the header value is only compared against trusted metadata (:373);
   - it's a `uint32`, so the `1<<40` example at :57 can't happen;
   - `numBlocks` (:692-696) takes `blockSize` from key metadata, not "the untrusted stream header".
   
   With a fixed 1 MiB block most of this goes away. Whatever remains should describe the header as validated only.
   



##########
encryption/go_envelope_manager.go:
##########
@@ -0,0 +1,889 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+	"math"
+	"sync"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [GoEnvelopeEncryptionManager].
+const (
+	// GoEnvelopeDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	GoEnvelopeDefaultDEKLength = 32
+
+	// GoEnvelopeDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	//
+	// This is not Java's Ciphers.PLAIN_BLOCK_SIZE (1 MiB, a compile-time
+	// constant there); see the [GoEnvelopeEncryptionManager] doc comment.
+	GoEnvelopeDefaultBlockSize = 64 * 1024
+
+	// GoEnvelopeMaxBlockSize is the largest plaintext block size accepted
+	// from the AES GCM Stream header on read, and the largest that
+	// [WithBlockSize] will configure for writing. The header's block-length
+	// field is unauthenticated, untrusted data (the Iceberg AES GCM Stream
+	// spec's "File length" note applies equally here); without a ceiling, a
+	// crafted header claiming e.g. 1<<40 bytes would force a huge
+	// allocation (see readBlock) before any authentication check can run.
+	GoEnvelopeMaxBlockSize = 128 * 1024 * 1024
+)
+
+// Sentinel errors returned by [GoEnvelopeEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile] when keyID is
+	// empty. GoEnvelopeEncryptionManager always encrypts, so it requires a
+	// KEK to wrap the generated DEK; use [PlaintextEncryptionManager] for
+	// unencrypted tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when keyMetadata
+	// is empty. GoEnvelopeEncryptionManager always decrypts, so it requires
+	// the per-file key metadata produced by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured block size is not
+	// positive or exceeds [GoEnvelopeMaxBlockSize].
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive and at most GoEnvelopeMaxBlockSize")
+
+	// ErrInvalidStreamHeader is returned when the AES GCM Stream header
+	// (the "AGS1" magic and little-endian block-length fields at the start
+	// of an encrypted file, per the Iceberg AES GCM Stream spec) is
+	// missing, truncated, or specifies a block length outside the
+	// supported range.
+	ErrInvalidStreamHeader = errors.New("encryption: invalid AES GCM Stream header")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a missing AAD prefix). Key metadata is untrusted input on a crypto
+	// read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+
+	// ErrOutputFileClosed is returned by [goEnvelopeOutputFile.Write] when
+	// called after Close, or after a previous flush has poisoned the writer.
+	// It wraps [fs.ErrClosed] so callers can test with errors.Is(err, fs.ErrClosed).
+	ErrOutputFileClosed = fmt.Errorf("encryption: write to closed GoEnvelopeEncryptionManager output file: %w", fs.ErrClosed)
+
+	// ErrBlockTruncated is returned by [goEnvelopeInputFile.ReadAt] when the
+	// underlying storage returns fewer ciphertext bytes for a block than its
+	// recorded length requires, indicating the file was truncated at rest.
+	// This is distinct from [ErrCiphertextTooShort], which [KeyManagementClient]
+	// implementations use for a too-short wrapped key or KMS-encrypted
+	// payload; keeping them separate lets a caller tell a malformed KMS blob
+	// apart from a short block read.
+	ErrBlockTruncated = errors.New("encryption: block truncated: read fewer ciphertext bytes than expected")
+)
+
+// Constants describing the Iceberg AES GCM Stream ("AGS1") wire format used
+// for the ciphertext produced by [GoEnvelopeEncryptionManager]. See
+// https://iceberg.apache.org/gcm-stream-spec/ for the full specification.
+const (
+	// gcmStreamMagic identifies an AES GCM Stream version 1 file.
+	gcmStreamMagic = "AGS1"
+
+	// gcmStreamHeaderLength is the length, in bytes, of the magic plus the
+	// little-endian block-length field written at the start of every file.
+	gcmStreamHeaderLength = len(gcmStreamMagic) + 4
+
+	// gcmStreamNonceLength is the length, in bytes, of the random AES-GCM
+	// nonce stored at the start of every cipher block.
+	gcmStreamNonceLength = 12
+
+	// gcmStreamTagLength is the length, in bytes, of the AES-GCM
+	// authentication tag appended to every cipher block's ciphertext.
+	gcmStreamTagLength = 16
+
+	// gcmStreamBlockOverhead is the number of ciphertext bytes added to
+	// each block beyond its plaintext length (nonce + tag).
+	gcmStreamBlockOverhead = gcmStreamNonceLength + gcmStreamTagLength
+
+	// gcmStreamAADPrefixLength is the length, in bytes, of the random
+	// per-file AAD prefix generated for new output files.
+	gcmStreamAADPrefixLength = 16
+)
+
+// goEnvelopeKeyMetadataVersion is the current encoding version written by
+// [GoEnvelopeEncryptionManager]. It is bumped whenever the on-disk layout of
+// goEnvelopeKeyMetadata changes incompatibly.
+const goEnvelopeKeyMetadataVersion = 1
+
+// goEnvelopeKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [GoEnvelopeEncryptionManager].
+//
+// This encoding is Go-specific, not Java's Avro-encoded StandardKeyMetadata;
+// see the [GoEnvelopeEncryptionManager] doc comment. Per the table spec,
+// DataFile/ManifestFile key_metadata is explicitly "implementation-specific";
+// what must be Iceberg AES GCM Stream compliant - and is - is the wire
+// format of the encrypted byte stream itself (magic, block framing, nonce
+// placement, and AAD; see the constants above).
+type goEnvelopeKeyMetadata struct {
+	Version    int    `json:"v"`
+	KeyID      string `json:"key-id"`
+	WrappedKey []byte `json:"wrapped-key"`
+
+	// BlockSize is the trusted plaintext block size the file was written
+	// with. It is validated bounded before any file I/O, and is what's
+	// actually used to size reads; the stream header's block-length field
+	// is untrusted (unauthenticated, attacker-influenced storage bytes) and
+	// is only compared against this value, never used directly to size an
+	// allocation.
+	BlockSize int64 `json:"block-size"`
+
+	// AADPrefix is combined with each block's little-endian index to form
+	// the AES GCM Stream additional authenticated data, binding every
+	// ciphertext block to this file and to its position so that blocks
+	// cannot be silently reordered, replayed from another file, or spliced
+	// in from elsewhere in the same file. It is not secret.
+	AADPrefix []byte `json:"aad-prefix"`
+
+	// PlaintextLength is the trusted total plaintext size used to compute
+	// the block count on read. Per the AES GCM Stream spec's "File length"
+	// note, a reader must use a length from a trusted source rather than
+	// the underlying storage's reported size, since storage size alone
+	// cannot distinguish a genuinely short file from one truncated by an
+	// attacker who does not also control this metadata.
+	PlaintextLength int64 `json:"plaintext-length"`
+}
+
+// GoEnvelopeEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks and written using the
+// Iceberg AES GCM Stream ("AGS1") format: a magic/block-length header
+// followed by independently authenticated blocks, each carrying its own
+// random nonce and authenticated with an AAD that binds it to the file and
+// to its position. This bounds memory usage and supports random access
+// (Seek/ReadAt) on the decrypted file without buffering or decrypting more
+// than the requested blocks.
+//
+// GoEnvelopeEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+//
+// Not interoperable with Java's StandardEncryptionManager: the AGS1 byte
+// stream framing (magic, block layout, nonce placement, AAD) matches the
+// spec, but the two implementations are not cross-readable. Java's reader
+// hard-requires a 1 MiB header block size (a compile-time constant there),
+// while [GoEnvelopeDefaultBlockSize] is 64 KiB, and Java decodes key
+// metadata as a 1-byte version plus Avro-encoded StandardKeyMetadata, while
+// this type encodes key metadata as JSON (goEnvelopeKeyMetadata). Files
+// written by one are not readable by the other.
+type GoEnvelopeEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*GoEnvelopeEncryptionManager)(nil)
+
+// GoEnvelopeManagerOption configures a [GoEnvelopeEncryptionManager] created
+// by [NewGoEnvelopeEncryptionManager].
+type GoEnvelopeManagerOption func(*GoEnvelopeEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) GoEnvelopeManagerOption {
+	return func(m *GoEnvelopeEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication. size must be
+// positive and at most [GoEnvelopeMaxBlockSize].
+func WithBlockSize(size int) GoEnvelopeManagerOption {
+	return func(m *GoEnvelopeEncryptionManager) { m.blockSize = size }
+}
+
+// NewGoEnvelopeEncryptionManager creates a [GoEnvelopeEncryptionManager]
+// backed by kms. kms must not be nil; NewGoEnvelopeEncryptionManager panics
+// if it is.
+func NewGoEnvelopeEncryptionManager(kms KeyManagementClient, opts ...GoEnvelopeManagerOption) *GoEnvelopeEncryptionManager {
+	if kms == nil {
+		panic("encryption: NewGoEnvelopeEncryptionManager: kms must not be nil")
+	}
+
+	m := &GoEnvelopeEncryptionManager{
+		kms:       kms,
+		dekLength: GoEnvelopeDefaultDEKLength,
+		blockSize: GoEnvelopeDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *GoEnvelopeEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 || m.blockSize > GoEnvelopeMaxBlockSize {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+	switch m.dekLength {
+	case 16, 24, 32:
+	default:
+		return nil, fmt.Errorf("%w: DEK length must be 16, 24, or 32 bytes; got %d", ErrInvalidKeyLength, m.dekLength)
+	}
+
+	// The (key, nonce) uniqueness this block format relies on requires a
+	// freshly generated DEK for every file: never cache or reuse
+	// plainDEK/wrappedDEK across calls to NewEncryptedOutputFile.
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = io.ReadFull(rand.Reader, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newGoEnvelopeAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	aadPrefix := make([]byte, gcmStreamAADPrefixLength)
+	if _, err := io.ReadFull(rand.Reader, aadPrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate AAD prefix: %w", err)
+	}
+
+	// Write the AES GCM Stream header (magic + little-endian block length)
+	// up front, before any ciphertext blocks, per the format spec.
+	header := make([]byte, gcmStreamHeaderLength)
+	copy(header, gcmStreamMagic)
+	binary.LittleEndian.PutUint32(header[len(gcmStreamMagic):], uint32(m.blockSize)) //nolint:gosec // bounded by ErrInvalidBlockSize above
+	if _, err := writer.Write(header); err != nil {
+		return nil, fmt.Errorf("encryption: failed to write stream header: %w", err)
+	}
+
+	return &goEnvelopeOutputFile{
+		FileWriter: writer,
+		aead:       aead,
+		aadPrefix:  aadPrefix,
+		blockSize:  m.blockSize,
+		keyID:      keyID,
+		wrappedKey: wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *GoEnvelopeEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta goEnvelopeKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != goEnvelopeKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+	if meta.BlockSize <= 0 || meta.BlockSize > GoEnvelopeMaxBlockSize {
+		return nil, fmt.Errorf("%w: block-size must be positive and at most %d, got %d", ErrInvalidKeyMetadata, GoEnvelopeMaxBlockSize, meta.BlockSize)
+	}
+	if meta.PlaintextLength < 0 {
+		return nil, fmt.Errorf("%w: plaintext-length must be non-negative, got %d", ErrInvalidKeyMetadata, meta.PlaintextLength)
+	}
+	// AADPrefix is bounded to exactly the length this implementation's own
+	// writer emits (gcmStreamAADPrefixLength): key metadata is Go-specific
+	// (not cross-implementation compatible; see the type doc comment), so
+	// there is no other length a valid file could carry. Without this
+	// ceiling, an oversized prefix would be re-allocated on every
+	// gcmStreamBlockAAD call in readBlock.
+	if len(meta.AADPrefix) != gcmStreamAADPrefixLength {
+		return nil, fmt.Errorf("%w: aad-prefix must be exactly %d bytes, got %d", ErrInvalidKeyMetadata, gcmStreamAADPrefixLength, len(meta.AADPrefix))
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newGoEnvelopeAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	// headerBlockSize is untrusted (unauthenticated bytes read from
+	// storage): it is only ever compared against the trusted, already
+	// bounded meta.BlockSize below, never used to size a read or allocation.
+	headerBlockSize, err := readGCMStreamHeader(file)
+	if err != nil {
+		return nil, err
+	}
+	if headerBlockSize != meta.BlockSize {
+		return nil, fmt.Errorf("%w: stream header block length %d does not match key metadata block-size %d", ErrInvalidStreamHeader, headerBlockSize, meta.BlockSize)
+	}
+
+	return &goEnvelopeInputFile{
+		underlying:      file,
+		aead:            aead,
+		aadPrefix:       meta.AADPrefix,
+		blockSize:       meta.BlockSize,
+		plaintextLength: meta.PlaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newGoEnvelopeAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %w", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// readGCMStreamHeader reads and validates the AES GCM Stream magic and
+// block-length header at the start of file, returning the plaintext block
+// length. The header is untrusted, unauthenticated data, so the returned
+// length is bounded to [GoEnvelopeMaxBlockSize] before any allocation sized
+// by it takes place.
+func readGCMStreamHeader(file icebergio.File) (int64, error) {
+	header := make([]byte, gcmStreamHeaderLength)
+	n, err := file.ReadAt(header, 0)
+	if err != nil && !errors.Is(err, io.EOF) {
+		return 0, fmt.Errorf("encryption: failed to read stream header: %w", err)
+	}
+	if n != gcmStreamHeaderLength {
+		return 0, fmt.Errorf("%w: expected %d header bytes, got %d", ErrInvalidStreamHeader, gcmStreamHeaderLength, n)
+	}
+	if string(header[:len(gcmStreamMagic)]) != gcmStreamMagic {
+		return 0, fmt.Errorf("%w: missing %q magic", ErrInvalidStreamHeader, gcmStreamMagic)
+	}
+
+	blockSize := int64(binary.LittleEndian.Uint32(header[len(gcmStreamMagic):]))
+	if blockSize <= 0 || blockSize > GoEnvelopeMaxBlockSize {
+		return 0, fmt.Errorf("%w: block length %d out of supported range (0, %d]", ErrInvalidStreamHeader, blockSize, GoEnvelopeMaxBlockSize)
+	}
+
+	return blockSize, nil
+}
+
+// gcmStreamBlockAAD derives the AES-GCM additional authenticated data for
+// blockIndex: the per-file AAD prefix followed by the 4-byte little-endian
+// block index, per the Iceberg AES GCM Stream spec. This binds every
+// ciphertext block to this file and to its position, which matters because
+// blocks carry independent random nonces (rather than a nonce derived from
+// the block index): without the index in the AAD, an attacker able to
+// tamper with ciphertext at rest could silently reorder or splice blocks.
+func gcmStreamBlockAAD(prefix []byte, blockIndex uint32) []byte {
+	aad := make([]byte, len(prefix)+4)
+	copy(aad, prefix)
+	binary.LittleEndian.PutUint32(aad[len(prefix):], blockIndex)
+
+	return aad
+}
+
+// checkedMulInt64 returns a*b and true, or (0, false) if the multiplication
+// overflows int64.
+func checkedMulInt64(a, b int64) (int64, bool) {
+	if a == 0 || b == 0 {
+		return 0, true
+	}
+	result := a * b
+	if result/b != a {
+		return 0, false
+	}
+
+	return result, true
+}
+
+// checkedAddInt64 returns a+b and true, or (0, false) if the addition
+// overflows int64.
+func checkedAddInt64(a, b int64) (int64, bool) {
+	result := a + b
+	if (b > 0 && result < a) || (b < 0 && result > a) {
+		return 0, false
+	}
+
+	return result, true
+}
+
+// goEnvelopeOutputFile is an [EncryptedOutputFile] that seals fixed-size
+// plaintext blocks with AES-GCM as they are written, using the Iceberg AES
+// GCM Stream ("AGS1") wire format.
+type goEnvelopeOutputFile struct {
+	icebergio.FileWriter
+
+	aead       cipher.AEAD
+	aadPrefix  []byte
+	blockSize  int
+	keyID      string
+	wrappedKey []byte
+
+	buf        []byte
+	blockIndex uint32
+	written    int64
+	closed     bool
+	err        error
+
+	// underlyingClosed tracks whether FileWriter.Close has already been
+	// attempted, so a poisoned writer is closed exactly once regardless of
+	// whether the failure is first observed in Write or in Close.
+	underlyingClosed bool
+
+	keyMetadata EncryptionKeyMetadata
+}
+
+var _ EncryptedOutputFile = (*goEnvelopeOutputFile)(nil)
+
+// closeUnderlyingIgnoringError closes the underlying writer at most once.
+// The error is ignored: the caller is already reporting a more specific
+// failure (a flush or encode error), and this is best-effort cleanup so a
+// poisoned writer never leaks its underlying file descriptor or connection.
+//
+// defensive: today every call site sets f.err before calling this, and
+// Write/Close both bail out early once f.err is set, so the
+// underlyingClosed guard never actually stops a second Close in practice.
+// It stays as a hard invariant in case a future call site is added that
+// doesn't follow that pattern.
+func (f *goEnvelopeOutputFile) closeUnderlyingIgnoringError() {
+	if f.underlyingClosed {
+		return
+	}
+	f.underlyingClosed = true
+	_ = f.FileWriter.Close()
+}
+
+func (f *goEnvelopeOutputFile) Write(p []byte) (int, error) {
+	if f.err != nil {
+		return 0, f.err
+	}
+	if f.closed {
+		return 0, ErrOutputFileClosed
+	}
+
+	total := len(p)
+	consumed := 0 // bytes of p appended into f.buf so far in this call
+	accepted := 0 // bytes of p known to be durably flushed; reported on failure
+	for len(p) > 0 {
+		space := f.blockSize - len(f.buf)
+		n := min(space, len(p))
+		f.buf = append(f.buf, p[:n]...)
+		p = p[n:]
+		consumed += n
+		if len(f.buf) == f.blockSize {
+			if err := f.flushBlock(); err != nil {
+				f.err = err
+				f.closeUnderlyingIgnoringError()
+
+				return accepted, err
+			}
+			accepted = consumed
+		}
+	}
+
+	return total, nil
+}
+
+// flushBlock seals and writes the currently buffered plaintext block using a
+// fresh random nonce, per the Iceberg AES GCM Stream format. f.written is
+// only advanced once the ciphertext has actually reached the underlying
+// writer, so a failed flush never overcounts PlaintextLength.
+func (f *goEnvelopeOutputFile) flushBlock() error {
+	if f.blockIndex == math.MaxUint32 {
+		return errors.New("encryption: cannot write block: exceeded maximum block count")
+	}
+
+	nonce := make([]byte, gcmStreamNonceLength)
+	if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
+		return fmt.Errorf("encryption: failed to generate block nonce: %w", err)
+	}
+
+	aad := gcmStreamBlockAAD(f.aadPrefix, f.blockIndex)
+	sealed := f.aead.Seal(nonce, nonce, f.buf, aad)
+	if _, err := f.FileWriter.Write(sealed); err != nil {
+		return fmt.Errorf("encryption: failed to write encrypted block: %w", err)
+	}
+	f.written += int64(len(f.buf))
+	f.blockIndex++
+	f.buf = f.buf[:0]
+
+	return nil
+}
+
+// ReadFrom copies from r, encrypting as data is written, satisfying
+// io.ReaderFrom (required by [icebergio.FileWriter]).
+func (f *goEnvelopeOutputFile) ReadFrom(r io.Reader) (int64, error) {
+	buf := make([]byte, max(32*1024, f.blockSize))
+	var total int64
+	for {
+		n, err := r.Read(buf)
+		if n > 0 {
+			wn, werr := f.Write(buf[:n])
+			total += int64(wn)
+			if werr != nil {
+				return total, werr
+			}
+		}
+		if err == io.EOF {
+			break
+		}
+		if err != nil {
+			return total, err
+		}
+	}
+
+	return total, nil
+}
+
+// Close flushes any buffered partial block and finalizes the key metadata.
+// closed is only set, and keyMetadata only published, once everything -
+// including the underlying Close - has succeeded; a failed Close poisons the
+// writer (via f.err) so a retry reliably reports the same error instead of
+// masking the failure as success or exposing metadata for an output that
+// never finished.
+func (f *goEnvelopeOutputFile) Close() error {
+	if f.err != nil {
+		return f.err
+	}
+	if f.closed {
+		return nil
+	}
+
+	if len(f.buf) > 0 {

Review Comment:
   Java writes block 0 even when the plaintext is empty. `close()` always calls `encryptAndWriteBlock()`, which only skips an empty block when `currentBlockIndex != 0`. An empty Java file is therefore 8 + 28 = 36 bytes, and iceberg-rust rejects anything shorter (`MIN_STREAM_LENGTH`). This code writes an 8-byte header-only file.
   
   The spec text says the last block is non-empty, but every shipping implementation writes the empty block 0, so match them:
   - flush when `len(f.buf) > 0 || f.blockIndex == 0`
   - on read, accept the 36-byte empty form (encrypted length 36 → plaintext length 0)
   



##########
encryption/go_envelope_manager_test.go:
##########
@@ -0,0 +1,654 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption_test
+
+import (
+	"bytes"
+	"encoding/base64"
+	"encoding/binary"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+	"math"
+	"testing"
+	"time"
+
+	"github.com/apache/iceberg-go/encryption"
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+	"golang.org/x/sync/errgroup"
+)
+
+func newTestGoEnvelopeManager(t *testing.T, opts ...encryption.GoEnvelopeManagerOption) (*encryption.GoEnvelopeEncryptionManager, *encryption.InMemoryKeyManagementClient) {
+	t.Helper()
+	kms := encryption.NewInMemoryKeyManagementClient()
+	require.NoError(t, kms.AddKey("kek-1", bytes.Repeat([]byte{0x42}, 32)))
+
+	return encryption.NewGoEnvelopeEncryptionManager(kms, opts...), kms
+}
+
+func encryptAll(t *testing.T, mgr *encryption.GoEnvelopeEncryptionManager, keyID string, plaintext []byte) (ciphertext []byte, keyMetadata encryption.EncryptionKeyMetadata) {
+	t.Helper()
+	fw := &memFileWriter{}
+	out, err := mgr.NewEncryptedOutputFile(t.Context(), fw, keyID)
+	require.NoError(t, err)
+	_, err = out.Write(plaintext)
+	require.NoError(t, err)
+	require.NoError(t, out.Close())
+
+	return fw.Bytes(), out.KeyMetadata()
+}
+
+func decryptAll(t *testing.T, mgr *encryption.GoEnvelopeEncryptionManager, ciphertext []byte, keyMetadata encryption.EncryptionKeyMetadata) []byte {
+	t.Helper()
+	in, err := mgr.NewDecryptedInputFile(t.Context(), newMemFile(ciphertext), keyMetadata)
+	require.NoError(t, err)
+	data, err := io.ReadAll(in)
+	require.NoError(t, err)
+
+	return data
+}
+
+func TestGoEnvelopeEncryptionManager_RoundTrip_SmallerThanBlock(t *testing.T) {
+	mgr, _ := newTestGoEnvelopeManager(t, encryption.WithBlockSize(16))
+	plaintext := []byte("hello iceberg")
+
+	ciphertext, keyMetadata := encryptAll(t, mgr, "kek-1", plaintext)
+	assert.NotEmpty(t, keyMetadata)
+	assert.NotEqual(t, plaintext, ciphertext, "ciphertext must differ from plaintext")
+
+	got := decryptAll(t, mgr, ciphertext, keyMetadata)
+	assert.Equal(t, plaintext, got)
+}
+
+func TestGoEnvelopeEncryptionManager_RoundTrip_MultiBlock(t *testing.T) {
+	mgr, _ := newTestGoEnvelopeManager(t, encryption.WithBlockSize(16))
+	plaintext := bytes.Repeat([]byte("0123456789abcdef"), 10)
+	plaintext = append(plaintext, []byte("partial-tail")...)
+
+	ciphertext, keyMetadata := encryptAll(t, mgr, "kek-1", plaintext)
+	got := decryptAll(t, mgr, ciphertext, keyMetadata)
+	assert.Equal(t, plaintext, got)
+}
+
+func TestGoEnvelopeEncryptionManager_RoundTrip_ExactBlockMultiple(t *testing.T) {
+	mgr, _ := newTestGoEnvelopeManager(t, encryption.WithBlockSize(16))
+	plaintext := bytes.Repeat([]byte("0123456789abcdef"), 4)
+
+	ciphertext, keyMetadata := encryptAll(t, mgr, "kek-1", plaintext)
+	got := decryptAll(t, mgr, ciphertext, keyMetadata)
+	assert.Equal(t, plaintext, got)
+}
+
+func TestGoEnvelopeEncryptionManager_RoundTrip_Empty(t *testing.T) {
+	mgr, _ := newTestGoEnvelopeManager(t, encryption.WithBlockSize(16))
+
+	ciphertext, keyMetadata := encryptAll(t, mgr, "kek-1", nil)
+	got := decryptAll(t, mgr, ciphertext, keyMetadata)
+	assert.Empty(t, got)
+}
+
+func TestGoEnvelopeEncryptionManager_RandomAccess(t *testing.T) {
+	mgr, _ := newTestGoEnvelopeManager(t, encryption.WithBlockSize(16))
+	plaintext := bytes.Repeat([]byte("0123456789abcdef"), 10)
+	plaintext = append(plaintext, []byte("tail-bytes")...)
+
+	ciphertext, keyMetadata := encryptAll(t, mgr, "kek-1", plaintext)
+	in, err := mgr.NewDecryptedInputFile(t.Context(), newMemFile(ciphertext), keyMetadata)
+	require.NoError(t, err)
+
+	// Read a slice spanning a block boundary.
+	buf := make([]byte, 20)
+	n, err := in.ReadAt(buf, 10)
+	require.NoError(t, err)
+	assert.Equal(t, plaintext[10:30], buf[:n])
+
+	// Seek + Read.
+	pos, err := in.Seek(5, io.SeekStart)
+	require.NoError(t, err)
+	assert.Equal(t, int64(5), pos)
+
+	rest, err := io.ReadAll(in)
+	require.NoError(t, err)
+	assert.Equal(t, plaintext[5:], rest)
+}
+
+func TestGoEnvelopeEncryptionManager_TamperedBlockFailsAuthentication(t *testing.T) {
+	mgr, _ := newTestGoEnvelopeManager(t, encryption.WithBlockSize(16))
+	plaintext := bytes.Repeat([]byte("0123456789abcdef"), 4)
+
+	ciphertext, keyMetadata := encryptAll(t, mgr, "kek-1", plaintext)
+	// Flip a bit inside the first block's ciphertext, past the 8-byte AES
+	// GCM Stream header and 12-byte nonce; flipping the header instead
+	// would fail earlier, at stream-header validation.
+	ciphertext[8+12] ^= 0xFF
+
+	in, err := mgr.NewDecryptedInputFile(t.Context(), newMemFile(ciphertext), keyMetadata)
+	require.NoError(t, err)
+
+	_, err = io.ReadAll(in)
+	require.Error(t, err)
+	assert.True(t, errors.Is(err, encryption.ErrAuthenticationFailed))
+}
+
+func TestGoEnvelopeEncryptionManager_ReorderedBlocksFailAuthentication(t *testing.T) {
+	mgr, _ := newTestGoEnvelopeManager(t, encryption.WithBlockSize(16))
+	plaintext := bytes.Repeat([]byte("0123456789abcdef"), 2) // exactly two full 16-byte blocks
+
+	ciphertext, keyMetadata := encryptAll(t, mgr, "kek-1", plaintext)
+
+	// The AES GCM Stream header (magic + block length) is 8 bytes; each
+	// cipher block here is 16 (block size) + 12 (nonce) + 16 (tag) = 44
+	// bytes. Swap the two blocks: with a random nonce per block, only the
+	// AAD (which binds a block to its position) can catch this.
+	const headerLen, blockPhysicalLen = 8, 44
+	block1 := append([]byte(nil), ciphertext[headerLen:headerLen+blockPhysicalLen]...)
+	block2 := append([]byte(nil), ciphertext[headerLen+blockPhysicalLen:headerLen+2*blockPhysicalLen]...)
+	copy(ciphertext[headerLen:headerLen+blockPhysicalLen], block2)
+	copy(ciphertext[headerLen+blockPhysicalLen:headerLen+2*blockPhysicalLen], block1)
+
+	in, err := mgr.NewDecryptedInputFile(t.Context(), newMemFile(ciphertext), keyMetadata)
+	require.NoError(t, err)
+
+	_, err = io.ReadAll(in)
+	require.Error(t, err)
+	assert.True(t, errors.Is(err, encryption.ErrAuthenticationFailed), "swapping blocks must be detected: the AAD binds each block to its position")
+}
+
+func TestGoEnvelopeEncryptionManager_StreamHeaderMagicMismatchRejected(t *testing.T) {
+	mgr, _ := newTestGoEnvelopeManager(t, encryption.WithBlockSize(16))
+	ciphertext, keyMetadata := encryptAll(t, mgr, "kek-1", []byte("hello iceberg"))
+	copy(ciphertext[:4], "XXXX")
+
+	_, err := mgr.NewDecryptedInputFile(t.Context(), newMemFile(ciphertext), keyMetadata)
+	require.Error(t, err)
+	assert.True(t, errors.Is(err, encryption.ErrInvalidStreamHeader))
+}
+
+func TestGoEnvelopeEncryptionManager_StreamHeaderZeroBlockLengthRejected(t *testing.T) {
+	mgr, _ := newTestGoEnvelopeManager(t, encryption.WithBlockSize(16))
+	ciphertext, keyMetadata := encryptAll(t, mgr, "kek-1", []byte("hello iceberg"))
+	binary.LittleEndian.PutUint32(ciphertext[4:8], 0)
+
+	_, err := mgr.NewDecryptedInputFile(t.Context(), newMemFile(ciphertext), keyMetadata)
+	require.Error(t, err)
+	assert.True(t, errors.Is(err, encryption.ErrInvalidStreamHeader))
+}
+
+func TestGoEnvelopeEncryptionManager_StreamHeaderBlockLengthExceedsMaxRejected(t *testing.T) {
+	mgr, _ := newTestGoEnvelopeManager(t, encryption.WithBlockSize(16))
+	ciphertext, keyMetadata := encryptAll(t, mgr, "kek-1", []byte("hello iceberg"))
+	binary.LittleEndian.PutUint32(ciphertext[4:8], math.MaxUint32)
+
+	_, err := mgr.NewDecryptedInputFile(t.Context(), newMemFile(ciphertext), keyMetadata)
+	require.Error(t, err)
+	assert.True(t, errors.Is(err, encryption.ErrInvalidStreamHeader))
+}
+
+func TestGoEnvelopeEncryptionManager_OutputFile_EmptyKeyIDRejected(t *testing.T) {
+	mgr, _ := newTestGoEnvelopeManager(t)
+	_, err := mgr.NewEncryptedOutputFile(t.Context(), &memFileWriter{}, "")
+	require.Error(t, err)
+	assert.True(t, errors.Is(err, encryption.ErrKeyIDRequired))
+}
+
+func TestGoEnvelopeEncryptionManager_InputFile_EmptyKeyMetadataRejected(t *testing.T) {
+	mgr, _ := newTestGoEnvelopeManager(t)
+	_, err := mgr.NewDecryptedInputFile(t.Context(), newMemFile(nil), nil)
+	require.Error(t, err)
+	assert.True(t, errors.Is(err, encryption.ErrKeyMetadataRequired))
+}
+
+func TestGoEnvelopeEncryptionManager_UnknownKeyIDPropagatesFromKMS(t *testing.T) {
+	mgr, _ := newTestGoEnvelopeManager(t)
+	_, err := mgr.NewEncryptedOutputFile(t.Context(), &memFileWriter{}, "does-not-exist")
+	require.Error(t, err)
+	assert.True(t, errors.Is(err, encryption.ErrUnknownKeyID))
+}
+
+func TestGoEnvelopeEncryptionManager_MalformedKeyMetadataRejected(t *testing.T) {
+	mgr, _ := newTestGoEnvelopeManager(t)
+	_, err := mgr.NewDecryptedInputFile(t.Context(), newMemFile(nil), encryption.EncryptionKeyMetadata("not json"))
+	require.Error(t, err)
+}
+
+func TestGoEnvelopeEncryptionManager_ZeroBlockSizeRejectedOnWrite(t *testing.T) {
+	mgr, _ := newTestGoEnvelopeManager(t, encryption.WithBlockSize(0))
+	_, err := mgr.NewEncryptedOutputFile(t.Context(), &memFileWriter{}, "kek-1")
+	require.Error(t, err)
+	assert.True(t, errors.Is(err, encryption.ErrInvalidBlockSize))
+}
+
+func TestGoEnvelopeEncryptionManager_NegativeBlockSizeRejectedOnWrite(t *testing.T) {
+	mgr, _ := newTestGoEnvelopeManager(t, encryption.WithBlockSize(-1))
+	_, err := mgr.NewEncryptedOutputFile(t.Context(), &memFileWriter{}, "kek-1")
+	require.Error(t, err)
+	assert.True(t, errors.Is(err, encryption.ErrInvalidBlockSize))
+}
+
+func TestGoEnvelopeEncryptionManager_BlockSizeExceedingMaxRejectedOnWrite(t *testing.T) {
+	mgr, _ := newTestGoEnvelopeManager(t, encryption.WithBlockSize(encryption.GoEnvelopeMaxBlockSize+1))
+	_, err := mgr.NewEncryptedOutputFile(t.Context(), &memFileWriter{}, "kek-1")
+	require.Error(t, err)
+	assert.True(t, errors.Is(err, encryption.ErrInvalidBlockSize))
+}
+
+func TestGoEnvelopeEncryptionManager_NegativePlaintextLengthMetadataRejectedOnRead(t *testing.T) {
+	mgr, _ := newTestGoEnvelopeManager(t)
+	meta := []byte(`{"v":1,"key-id":"kek-1","wrapped-key":"AA==","block-size":16,"aad-prefix":"MTIzNDU2Nzg5MDEyMzQ1Ng==","plaintext-length":-1}`)
+	_, err := mgr.NewDecryptedInputFile(t.Context(), newMemFile(nil), meta)
+	require.Error(t, err)
+	assert.True(t, errors.Is(err, encryption.ErrInvalidKeyMetadata))
+	assert.ErrorContains(t, err, "plaintext-length must be non-negative")
+}
+
+func TestGoEnvelopeEncryptionManager_EmptyAADPrefixMetadataRejectedOnRead(t *testing.T) {
+	mgr, _ := newTestGoEnvelopeManager(t)
+	meta := []byte(`{"v":1,"key-id":"kek-1","wrapped-key":"AA==","block-size":16,"aad-prefix":"","plaintext-length":10}`)
+	_, err := mgr.NewDecryptedInputFile(t.Context(), newMemFile(nil), meta)
+	require.Error(t, err)
+	assert.True(t, errors.Is(err, encryption.ErrInvalidKeyMetadata))
+	assert.ErrorContains(t, err, "aad-prefix must be exactly 16 bytes")
+}
+
+func TestGoEnvelopeEncryptionManager_OversizedAADPrefixMetadataRejectedOnRead(t *testing.T) {
+	mgr, _ := newTestGoEnvelopeManager(t)
+	// 17 zero bytes, base64-encoded: one byte longer than gcmStreamAADPrefixLength.
+	oversized := base64.StdEncoding.EncodeToString(make([]byte, 17))
+	meta := fmt.Appendf(nil, `{"v":1,"key-id":"kek-1","wrapped-key":"AA==","block-size":16,"aad-prefix":"%s","plaintext-length":10}`, oversized)
+	_, err := mgr.NewDecryptedInputFile(t.Context(), newMemFile(nil), meta)
+	require.Error(t, err)
+	assert.True(t, errors.Is(err, encryption.ErrInvalidKeyMetadata))
+	assert.ErrorContains(t, err, "aad-prefix must be exactly 16 bytes")
+}
+
+func TestGoEnvelopeEncryptionManager_ZeroBlockSizeMetadataRejectedOnRead(t *testing.T) {
+	mgr, _ := newTestGoEnvelopeManager(t)
+	meta := []byte(`{"v":1,"key-id":"kek-1","wrapped-key":"AA==","block-size":0,"aad-prefix":"MTIzNDU2Nzg5MDEyMzQ1Ng==","plaintext-length":10}`)
+	_, err := mgr.NewDecryptedInputFile(t.Context(), newMemFile(nil), meta)
+	require.Error(t, err)
+	assert.True(t, errors.Is(err, encryption.ErrInvalidKeyMetadata))
+	assert.ErrorContains(t, err, "block-size must be positive")
+}
+
+func TestGoEnvelopeEncryptionManager_BlockSizeExceedingMaxMetadataRejectedOnRead(t *testing.T) {
+	mgr, _ := newTestGoEnvelopeManager(t)
+	meta := fmt.Appendf(nil, `{"v":1,"key-id":"kek-1","wrapped-key":"AA==","block-size":%d,"aad-prefix":"MTIzNDU2Nzg5MDEyMzQ1Ng==","plaintext-length":10}`, encryption.GoEnvelopeMaxBlockSize+1)
+	_, err := mgr.NewDecryptedInputFile(t.Context(), newMemFile(nil), meta)
+	require.Error(t, err)
+	assert.True(t, errors.Is(err, encryption.ErrInvalidKeyMetadata))
+	assert.ErrorContains(t, err, "block-size must be positive")
+}
+
+func TestGoEnvelopeEncryptionManager_InvalidDEKLengthRejected(t *testing.T) {
+	mgr, _ := newTestGoEnvelopeManager(t, encryption.WithDEKLength(15))
+	_, err := mgr.NewEncryptedOutputFile(t.Context(), &memFileWriter{}, "kek-1")
+	require.Error(t, err)
+	assert.True(t, errors.Is(err, encryption.ErrInvalidKeyLength))
+}
+
+// shortReadFile is an icebergio.File stub whose ReadAt returns fewer bytes
+// than requested along with io.EOF once truncateAt is reached, mimicking a
+// real backend (S3, local fs) reading a genuinely truncated file. A plain
+// bytes.Reader always fills the requested slice, which is why the round-trip
+// tests never exercise this path.
+type shortReadFile struct {
+	*memFile
+	truncateAt int64
+}
+
+func (f *shortReadFile) ReadAt(p []byte, off int64) (int, error) {
+	if off >= f.truncateAt {
+		return 0, io.EOF
+	}
+	if off+int64(len(p)) > f.truncateAt {
+		p = p[:f.truncateAt-off]
+	}
+	n, err := f.memFile.ReadAt(p, off)
+	if err == nil && int64(n) < int64(len(p)) {
+		err = io.EOF
+	}
+
+	return n, err
+}
+
+func TestGoEnvelopeEncryptionManager_TruncatedBackendReadReportsBlockTruncated(t *testing.T) {
+	mgr, _ := newTestGoEnvelopeManager(t, encryption.WithBlockSize(16))
+	plaintext := bytes.Repeat([]byte("0123456789abcdef"), 4)
+
+	ciphertext, keyMetadata := encryptAll(t, mgr, "kek-1", plaintext)
+	truncated := &shortReadFile{memFile: newMemFile(ciphertext), truncateAt: int64(len(ciphertext) - 5)}
+
+	in, err := mgr.NewDecryptedInputFile(t.Context(), truncated, keyMetadata)
+	require.NoError(t, err)
+
+	_, err = io.ReadAll(in)
+	require.Error(t, err)
+	assert.True(t, errors.Is(err, encryption.ErrBlockTruncated))
+	assert.False(t, errors.Is(err, encryption.ErrCiphertextTooShort), "a truncated block read is distinct from a too-short KMS-wrapped key/payload")
+	assert.False(t, errors.Is(err, encryption.ErrAuthenticationFailed), "a truncated read must not be misreported as tampering")
+}
+
+func TestGoEnvelopeEncryptionManager_EmptyFile_ZeroLengthReadAt(t *testing.T) {
+	mgr, _ := newTestGoEnvelopeManager(t, encryption.WithBlockSize(16))
+	ciphertext, keyMetadata := encryptAll(t, mgr, "kek-1", nil)
+
+	in, err := mgr.NewDecryptedInputFile(t.Context(), newMemFile(ciphertext), keyMetadata)
+	require.NoError(t, err)
+
+	n, err := in.ReadAt(nil, 0)
+	assert.NoError(t, err, "a zero-length ReadAt on an empty file should behave like bytes.Reader, not report io.EOF")

Review Comment:
   Returning `(0, nil)` here is fine, but the reason in the message is wrong. `bytes.Reader.ReadAt` returns `(0, io.EOF)` whenever `off >= len`, whatever `len(p)` is:
   
   ```go
   if off >= int64(len(r.s)) {
   	return 0, io.EOF
   }
   ```
   
   The behavior here matches `os.File.ReadAt` instead. Reword the message, e.g. "zero-length ReadAt must return (0, nil), like os.File". (@laskoviymishka: same correction to the premise of the 08-05 zero-length-read thread.)
   



##########
encryption/go_envelope_manager.go:
##########
@@ -0,0 +1,889 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+	"math"
+	"sync"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [GoEnvelopeEncryptionManager].
+const (
+	// GoEnvelopeDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	GoEnvelopeDefaultDEKLength = 32
+
+	// GoEnvelopeDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	//
+	// This is not Java's Ciphers.PLAIN_BLOCK_SIZE (1 MiB, a compile-time
+	// constant there); see the [GoEnvelopeEncryptionManager] doc comment.
+	GoEnvelopeDefaultBlockSize = 64 * 1024
+
+	// GoEnvelopeMaxBlockSize is the largest plaintext block size accepted
+	// from the AES GCM Stream header on read, and the largest that
+	// [WithBlockSize] will configure for writing. The header's block-length
+	// field is unauthenticated, untrusted data (the Iceberg AES GCM Stream
+	// spec's "File length" note applies equally here); without a ceiling, a
+	// crafted header claiming e.g. 1<<40 bytes would force a huge
+	// allocation (see readBlock) before any authentication check can run.
+	GoEnvelopeMaxBlockSize = 128 * 1024 * 1024
+)
+
+// Sentinel errors returned by [GoEnvelopeEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile] when keyID is
+	// empty. GoEnvelopeEncryptionManager always encrypts, so it requires a
+	// KEK to wrap the generated DEK; use [PlaintextEncryptionManager] for
+	// unencrypted tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when keyMetadata
+	// is empty. GoEnvelopeEncryptionManager always decrypts, so it requires
+	// the per-file key metadata produced by
+	// [GoEnvelopeEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: GoEnvelopeEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+
+	// ErrInvalidBlockSize is returned when a configured block size is not
+	// positive or exceeds [GoEnvelopeMaxBlockSize].
+	ErrInvalidBlockSize = errors.New("encryption: block size must be positive and at most GoEnvelopeMaxBlockSize")
+
+	// ErrInvalidStreamHeader is returned when the AES GCM Stream header
+	// (the "AGS1" magic and little-endian block-length fields at the start
+	// of an encrypted file, per the Iceberg AES GCM Stream spec) is
+	// missing, truncated, or specifies a block length outside the
+	// supported range.
+	ErrInvalidStreamHeader = errors.New("encryption: invalid AES GCM Stream header")
+
+	// ErrInvalidKeyMetadata is returned by
+	// [GoEnvelopeEncryptionManager.NewDecryptedInputFile] when decoded key
+	// metadata fails basic sanity checks (e.g. a negative plaintext length
+	// or a missing AAD prefix). Key metadata is untrusted input on a crypto
+	// read path, so it is validated rather than trusted blindly.
+	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")
+
+	// ErrOutputFileClosed is returned by [goEnvelopeOutputFile.Write] when
+	// called after Close, or after a previous flush has poisoned the writer.
+	// It wraps [fs.ErrClosed] so callers can test with errors.Is(err, fs.ErrClosed).
+	ErrOutputFileClosed = fmt.Errorf("encryption: write to closed GoEnvelopeEncryptionManager output file: %w", fs.ErrClosed)
+
+	// ErrBlockTruncated is returned by [goEnvelopeInputFile.ReadAt] when the
+	// underlying storage returns fewer ciphertext bytes for a block than its
+	// recorded length requires, indicating the file was truncated at rest.
+	// This is distinct from [ErrCiphertextTooShort], which [KeyManagementClient]
+	// implementations use for a too-short wrapped key or KMS-encrypted
+	// payload; keeping them separate lets a caller tell a malformed KMS blob
+	// apart from a short block read.
+	ErrBlockTruncated = errors.New("encryption: block truncated: read fewer ciphertext bytes than expected")
+)
+
+// Constants describing the Iceberg AES GCM Stream ("AGS1") wire format used
+// for the ciphertext produced by [GoEnvelopeEncryptionManager]. See
+// https://iceberg.apache.org/gcm-stream-spec/ for the full specification.
+const (
+	// gcmStreamMagic identifies an AES GCM Stream version 1 file.
+	gcmStreamMagic = "AGS1"
+
+	// gcmStreamHeaderLength is the length, in bytes, of the magic plus the
+	// little-endian block-length field written at the start of every file.
+	gcmStreamHeaderLength = len(gcmStreamMagic) + 4
+
+	// gcmStreamNonceLength is the length, in bytes, of the random AES-GCM
+	// nonce stored at the start of every cipher block.
+	gcmStreamNonceLength = 12
+
+	// gcmStreamTagLength is the length, in bytes, of the AES-GCM
+	// authentication tag appended to every cipher block's ciphertext.
+	gcmStreamTagLength = 16
+
+	// gcmStreamBlockOverhead is the number of ciphertext bytes added to
+	// each block beyond its plaintext length (nonce + tag).
+	gcmStreamBlockOverhead = gcmStreamNonceLength + gcmStreamTagLength
+
+	// gcmStreamAADPrefixLength is the length, in bytes, of the random
+	// per-file AAD prefix generated for new output files.
+	gcmStreamAADPrefixLength = 16
+)
+
+// goEnvelopeKeyMetadataVersion is the current encoding version written by
+// [GoEnvelopeEncryptionManager]. It is bumped whenever the on-disk layout of
+// goEnvelopeKeyMetadata changes incompatibly.
+const goEnvelopeKeyMetadataVersion = 1
+
+// goEnvelopeKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [GoEnvelopeEncryptionManager].
+//
+// This encoding is Go-specific, not Java's Avro-encoded StandardKeyMetadata;
+// see the [GoEnvelopeEncryptionManager] doc comment. Per the table spec,
+// DataFile/ManifestFile key_metadata is explicitly "implementation-specific";
+// what must be Iceberg AES GCM Stream compliant - and is - is the wire
+// format of the encrypted byte stream itself (magic, block framing, nonce
+// placement, and AAD; see the constants above).
+type goEnvelopeKeyMetadata struct {
+	Version    int    `json:"v"`
+	KeyID      string `json:"key-id"`
+	WrappedKey []byte `json:"wrapped-key"`
+
+	// BlockSize is the trusted plaintext block size the file was written
+	// with. It is validated bounded before any file I/O, and is what's
+	// actually used to size reads; the stream header's block-length field
+	// is untrusted (unauthenticated, attacker-influenced storage bytes) and
+	// is only compared against this value, never used directly to size an
+	// allocation.
+	BlockSize int64 `json:"block-size"`
+
+	// AADPrefix is combined with each block's little-endian index to form
+	// the AES GCM Stream additional authenticated data, binding every
+	// ciphertext block to this file and to its position so that blocks
+	// cannot be silently reordered, replayed from another file, or spliced
+	// in from elsewhere in the same file. It is not secret.
+	AADPrefix []byte `json:"aad-prefix"`
+
+	// PlaintextLength is the trusted total plaintext size used to compute
+	// the block count on read. Per the AES GCM Stream spec's "File length"
+	// note, a reader must use a length from a trusted source rather than
+	// the underlying storage's reported size, since storage size alone
+	// cannot distinguish a genuinely short file from one truncated by an
+	// attacker who does not also control this metadata.
+	PlaintextLength int64 `json:"plaintext-length"`
+}
+
+// GoEnvelopeEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks and written using the
+// Iceberg AES GCM Stream ("AGS1") format: a magic/block-length header
+// followed by independently authenticated blocks, each carrying its own
+// random nonce and authenticated with an AAD that binds it to the file and
+// to its position. This bounds memory usage and supports random access
+// (Seek/ReadAt) on the decrypted file without buffering or decrypting more
+// than the requested blocks.
+//
+// GoEnvelopeEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+//
+// Not interoperable with Java's StandardEncryptionManager: the AGS1 byte
+// stream framing (magic, block layout, nonce placement, AAD) matches the
+// spec, but the two implementations are not cross-readable. Java's reader
+// hard-requires a 1 MiB header block size (a compile-time constant there),
+// while [GoEnvelopeDefaultBlockSize] is 64 KiB, and Java decodes key
+// metadata as a 1-byte version plus Avro-encoded StandardKeyMetadata, while
+// this type encodes key metadata as JSON (goEnvelopeKeyMetadata). Files
+// written by one are not readable by the other.
+type GoEnvelopeEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*GoEnvelopeEncryptionManager)(nil)
+
+// GoEnvelopeManagerOption configures a [GoEnvelopeEncryptionManager] created
+// by [NewGoEnvelopeEncryptionManager].
+type GoEnvelopeManagerOption func(*GoEnvelopeEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) GoEnvelopeManagerOption {
+	return func(m *GoEnvelopeEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication. size must be
+// positive and at most [GoEnvelopeMaxBlockSize].
+func WithBlockSize(size int) GoEnvelopeManagerOption {
+	return func(m *GoEnvelopeEncryptionManager) { m.blockSize = size }
+}
+
+// NewGoEnvelopeEncryptionManager creates a [GoEnvelopeEncryptionManager]
+// backed by kms. kms must not be nil; NewGoEnvelopeEncryptionManager panics
+// if it is.
+func NewGoEnvelopeEncryptionManager(kms KeyManagementClient, opts ...GoEnvelopeManagerOption) *GoEnvelopeEncryptionManager {
+	if kms == nil {
+		panic("encryption: NewGoEnvelopeEncryptionManager: kms must not be nil")
+	}
+
+	m := &GoEnvelopeEncryptionManager{
+		kms:       kms,
+		dekLength: GoEnvelopeDefaultDEKLength,
+		blockSize: GoEnvelopeDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *GoEnvelopeEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+	if m.blockSize <= 0 || m.blockSize > GoEnvelopeMaxBlockSize {
+		return nil, fmt.Errorf("%w: got %d", ErrInvalidBlockSize, m.blockSize)
+	}
+	switch m.dekLength {
+	case 16, 24, 32:
+	default:
+		return nil, fmt.Errorf("%w: DEK length must be 16, 24, or 32 bytes; got %d", ErrInvalidKeyLength, m.dekLength)
+	}
+
+	// The (key, nonce) uniqueness this block format relies on requires a
+	// freshly generated DEK for every file: never cache or reuse
+	// plainDEK/wrappedDEK across calls to NewEncryptedOutputFile.
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = io.ReadFull(rand.Reader, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}

Review Comment:
   With the raw DEK in `StandardKeyMetadata`, this block and the `UnwrapKey` at :356 go away. Generate the DEK locally with `crypto/rand`, the way Java's `StandardEncryptedOutputFile.keyMetadata()` does.
   
   Wrapping each file's DEK costs a KMS round trip for every file opened, and no cache can help across files. Java and Rust call the KMS once per KEK and cache it for an hour. In that model the DEK is protected by encrypting the thing that holds the key metadata (manifest, manifest list), with the KEK layer stored in the table's `encryption-keys`. That layer and the unwrap cache are the follow-up PR, and it has to land before EncryptingFileIO writes anything. Nothing calls this manager yet, so a raw DEK in this slice is acceptable.
   
   @laskoviymishka this replaces the per-file wrapping you reviewed on 08-05 and approved on 08-27 and 09-08 with the Java/Rust key hierarchy.
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat(encryption): add StandardEncryptionManager [iceberg-go]

Posted by "tanmayrauth (via GitHub)" <gi...@apache.org>.
tanmayrauth commented on code in PR #1620:
URL: https://github.com/apache/iceberg-go/pull/1620#discussion_r3693021679


##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,488 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	return &standardInputFile{
+		underlying:      file,
+		aead:            aead,
+		noncePrefix:     meta.NoncePrefix,
+		blockSize:       meta.BlockSize,
+		plaintextLength: meta.PlaintextLength,
+		keyMetadata:     keyMetadata,
+	}, nil
+}
+
+func newStandardAEAD(key []byte) (cipher.AEAD, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return nil, fmt.Errorf("%w: %v", ErrInvalidKeyLength, err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to create GCM: %w", err)
+	}
+
+	return gcm, nil
+}
+
+// standardBlockNonce derives the AES-GCM nonce for blockIndex: the 4-byte
+// per-file random prefix followed by the 8-byte big-endian block index. The
+// (key, nonce) pair is unique per block since the DEK is fresh per file and
+// no two blocks in the same file share an index.
+func standardBlockNonce(prefix []byte, blockIndex uint64) []byte {
+	nonce := make([]byte, 12)
+	copy(nonce, prefix)
+	binary.BigEndian.PutUint64(nonce[4:], blockIndex)
+
+	return nonce
+}
+
+// standardOutputFile is an [EncryptedOutputFile] that seals fixed-size
+// plaintext blocks with AES-GCM as they are written.
+type standardOutputFile struct {
+	icebergio.FileWriter
+
+	aead        cipher.AEAD
+	noncePrefix []byte
+	blockSize   int
+	keyID       string
+	wrappedKey  []byte
+
+	buf        []byte
+	blockIndex uint64
+	written    int64
+	closed     bool
+
+	keyMetadata EncryptionKeyMetadata
+}
+
+var _ EncryptedOutputFile = (*standardOutputFile)(nil)
+
+func (f *standardOutputFile) Write(p []byte) (int, error) {
+	total := len(p)
+	for len(p) > 0 {
+		space := f.blockSize - len(f.buf)

Review Comment:
   Nit: `NewStandardEncryptionManager` doesn't validate `blockSize`, so a bad `WithBlockSize` only surfaces at write time — `WithBlockSize(-1)` panics `slice bounds out of range [:-1]` on the first `Write`, and `WithBlockSize(0)` spins forever here (`len(f.buf) == f.blockSize` is `0 == 0` every iteration, so `p` is never consumed). A `blockSize > 0` guard in `NewEncryptedOutputFile` (which already returns an error) rejects it early.
   



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,488 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {
+	kms       KeyManagementClient
+	dekLength int
+	blockSize int
+}
+
+var _ EncryptionManager = (*StandardEncryptionManager)(nil)
+
+// StandardManagerOption configures a [StandardEncryptionManager] created by
+// [NewStandardEncryptionManager].
+type StandardManagerOption func(*StandardEncryptionManager)
+
+// WithDEKLength overrides the default data encryption key length (in bytes).
+// Valid AES key lengths are 16, 24, or 32 bytes.
+func WithDEKLength(length int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.dekLength = length }
+}
+
+// WithBlockSize overrides the default plaintext block size (in bytes) used
+// to split files for independent block-level authentication.
+func WithBlockSize(size int) StandardManagerOption {
+	return func(m *StandardEncryptionManager) { m.blockSize = size }
+}
+
+// NewStandardEncryptionManager creates a [StandardEncryptionManager] backed
+// by kms. kms must not be nil.
+func NewStandardEncryptionManager(kms KeyManagementClient, opts ...StandardManagerOption) *StandardEncryptionManager {
+	m := &StandardEncryptionManager{
+		kms:       kms,
+		dekLength: StandardDefaultDEKLength,
+		blockSize: StandardDefaultBlockSize,
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+
+	return m
+}
+
+// NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file.
+// keyID identifies the KEK used to wrap the freshly generated per-file DEK,
+// and must be non-empty; otherwise [ErrKeyIDRequired] is returned.
+func (m *StandardEncryptionManager) NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error) {
+	if keyID == "" {
+		return nil, ErrKeyIDRequired
+	}
+
+	var (
+		plainDEK, wrappedDEK []byte
+		err                  error
+	)
+	if m.kms.SupportsKeyGeneration() {
+		plainDEK, wrappedDEK, err = m.kms.GenerateKey(ctx, keyID, m.dekLength)
+		if err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+	} else {
+		plainDEK = make([]byte, m.dekLength)
+		if _, err = rand.Read(plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to generate DEK: %w", err)
+		}
+		if wrappedDEK, err = m.kms.WrapKey(ctx, keyID, plainDEK); err != nil {
+			return nil, fmt.Errorf("encryption: failed to wrap DEK: %w", err)
+		}
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	noncePrefix := make([]byte, 4)
+	if _, err := rand.Read(noncePrefix); err != nil {
+		return nil, fmt.Errorf("encryption: failed to generate nonce prefix: %w", err)
+	}
+
+	return &standardOutputFile{
+		FileWriter:  writer,
+		aead:        aead,
+		noncePrefix: noncePrefix,
+		blockSize:   m.blockSize,
+		keyID:       keyID,
+		wrappedKey:  wrappedDEK,
+	}, nil
+}
+
+// NewDecryptedInputFile wraps file for transparent block-level AES-GCM
+// decryption. keyMetadata must be the non-empty blob produced by
+// [StandardEncryptionManager.NewEncryptedOutputFile]; otherwise
+// [ErrKeyMetadataRequired] is returned.
+func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error) {
+	if len(keyMetadata) == 0 {
+		return nil, ErrKeyMetadataRequired
+	}
+
+	var meta standardKeyMetadata
+	if err := json.Unmarshal(keyMetadata, &meta); err != nil {
+		return nil, fmt.Errorf("encryption: failed to decode key metadata: %w", err)
+	}
+	if meta.Version != standardKeyMetadataVersion {
+		return nil, fmt.Errorf("%w: %d", ErrUnsupportedKeyMetadataVersion, meta.Version)
+	}
+
+	plainDEK, err := m.kms.UnwrapKey(ctx, meta.KeyID, meta.WrappedKey)
+	if err != nil {
+		return nil, fmt.Errorf("encryption: failed to unwrap DEK: %w", err)
+	}
+
+	aead, err := newStandardAEAD(plainDEK)
+	if err != nil {
+		return nil, err
+	}
+
+	return &standardInputFile{
+		underlying:      file,
+		aead:            aead,
+		noncePrefix:     meta.NoncePrefix,
+		blockSize:       meta.BlockSize,

Review Comment:
     Minor robustness nit: `NewDecryptedInputFile` checks the version but doesn't validate the rest of the decoded metadata. A well-formed-JSON `key_metadata` with `"block-size":0` and a non-zero `plaintext-length` builds fine here, then the first `Read`/`ReadAt` panics with `integer divide by zero` (via `numBlocks` at :379 and `curOff / int64(f.blockSize)` at :423). Not reachable from this manager's own output, but once #1289 feeds `key_metadata` from real manifests it's untrusted input on a crypto read path, and a panic is worse than a clean error. Validate `meta.BlockSize > 0`, `meta.PlaintextLength >= 0`, and `len(meta.NoncePrefix) == 4` right after the version check (:198) and  return a wrapped error. Worth a matching test — the existing "malformed key metadata" case only covers invalid JSON.
   



##########
encryption/standard_manager.go:
##########
@@ -0,0 +1,488 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package encryption
+
+import (
+	"context"
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/binary"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"io/fs"
+
+	icebergio "github.com/apache/iceberg-go/io"
+)
+
+// Defaults for [StandardEncryptionManager].
+const (
+	// StandardDefaultDEKLength is the default length, in bytes, of the
+	// per-file data encryption key (DEK) generated for AES-256-GCM.
+	StandardDefaultDEKLength = 32
+
+	// StandardDefaultBlockSize is the default plaintext block size, in
+	// bytes, used to split a file into independently authenticated AES-GCM
+	// blocks. Blocks allow random access (Seek/ReadAt) without buffering or
+	// decrypting the whole file.
+	StandardDefaultBlockSize = 64 * 1024
+)
+
+// Sentinel errors returned by [StandardEncryptionManager].
+var (
+	// ErrKeyIDRequired is returned by
+	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
+	// StandardEncryptionManager always encrypts, so it requires a KEK to wrap
+	// the generated DEK; use [PlaintextEncryptionManager] for unencrypted
+	// tables instead of passing an empty keyID here.
+	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")
+
+	// ErrKeyMetadataRequired is returned by
+	// [StandardEncryptionManager.NewDecryptedInputFile] when keyMetadata is
+	// empty. StandardEncryptionManager always decrypts, so it requires the
+	// per-file key metadata produced by [StandardEncryptionManager.NewEncryptedOutputFile].
+	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")
+
+	// ErrUnsupportedKeyMetadataVersion is returned when key metadata was
+	// produced by a newer, incompatible encoding version.
+	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")
+)
+
+// standardKeyMetadataVersion is the current encoding version written by
+// [StandardEncryptionManager]. It is bumped whenever the on-disk layout of
+// standardKeyMetadata or the block ciphertext format changes incompatibly.
+const standardKeyMetadataVersion = 1
+
+// standardKeyMetadata is the JSON-encoded structure stored as the opaque
+// [EncryptionKeyMetadata] for files produced by [StandardEncryptionManager].
+type standardKeyMetadata struct {
+	Version         int    `json:"v"`
+	KeyID           string `json:"key-id"`
+	WrappedKey      []byte `json:"wrapped-key"`
+	NoncePrefix     []byte `json:"nonce-prefix"`
+	BlockSize       int    `json:"block-size"`
+	PlaintextLength int64  `json:"plaintext-length"`
+}
+
+// StandardEncryptionManager is a generic, format-agnostic [EncryptionManager]
+// that provides envelope encryption for arbitrary files (e.g. manifests,
+// manifest lists, Puffin statistics) using a [KeyManagementClient] to wrap
+// and unwrap a fresh AES-256-GCM data encryption key (DEK) per file.
+//
+// Each file is split into fixed-size plaintext blocks, and each block is
+// sealed independently with AES-GCM using a unique nonce (a per-file random
+// prefix combined with the block index). This bounds memory usage and
+// supports random access (Seek/ReadAt) on the decrypted file without
+// buffering or decrypting more than the requested blocks.
+//
+// StandardEncryptionManager always encrypts and always decrypts: it fails
+// closed, returning [ErrKeyIDRequired] or [ErrKeyMetadataRequired] rather
+// than silently falling back to plaintext. Use [PlaintextEncryptionManager]
+// for tables or files that are not encrypted.
+type StandardEncryptionManager struct {

Review Comment:
    Heads-up on the format, not a blocker — a call worth making before this gets wired in, since the format becomes a breaking change once reads/writes depend on it.
     
     Java's StandardEncryptionManager (same name) produces the AGS1 stream via AesGcmOutputStream: "AGS1" header + block size, 1 MiB blocks, an inline random 12-byte nonce per block, AAD = fileAadPrefix ‖ block ordinal, and Avro StandardKeyMetadata {encryption_key, aad_prefix, file_length}. This produces a different format — no header, 64 KB blocks, derived nonce, nil AAD, JSON key_metadata — so a Java reader can't read a file written here and vice versa.
     
     Is cross-engine interop of encrypted metadata a goal? For a table encrypted by one engine and read by another it has to be, but if the intent is an iceberg-go-only format for now, this is fine as-is. One thing to note either way: there's no fileAadPrefix hook here, which is what Java uses to bind an AAD (e.g. the manifest-list case); adding that later is easier before the format is locked in. Flagging for the design discussion in #1289, not asking for changes in this PR.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org