keyset

package
v2.6.0 Latest Latest
Warning

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

Go to latest
Published: Dec 10, 2025 License: Apache-2.0 Imports: 22 Imported by: 63

Documentation

Overview

Package keyset provides methods to generate, read, write or validate keysets.

Example (EncryptedKeyset)
package main

// [START encrypted-keyset-example]

import (
	"bytes"
	"fmt"
	"log"

	"github.com/tink-crypto/tink-go/v2/aead"
	"github.com/tink-crypto/tink-go/v2/keyset"
	"github.com/tink-crypto/tink-go/v2/testing/fakekms"
)

// The fake KMS should only be used in tests. It is not secure.
const keyURI = "fake-kms://CM2b3_MDElQKSAowdHlwZS5nb29nbGVhcGlzLmNvbS9nb29nbGUuY3J5cHRvLnRpbmsuQWVzR2NtS2V5EhIaEIK75t5L-adlUwVhWvRuWUwYARABGM2b3_MDIAE"

func main() {
	// Get a KEK (key encryption key) AEAD. This is usually a remote AEAD to a KMS. In this example,
	// we use a fake KMS to avoid making RPCs.
	client, err := fakekms.NewClient(keyURI)
	if err != nil {
		log.Fatal(err)
	}
	kekAEAD, err := client.GetAEAD(keyURI)
	if err != nil {
		log.Fatal(err)
	}

	// Generate a new keyset handle for the primitive we want to use.
	newHandle, err := keyset.NewHandle(aead.AES256GCMKeyTemplate())
	if err != nil {
		log.Fatal(err)
	}

	// Choose some associated data. This is the context in which the keyset will be used.
	keysetAssociatedData := []byte("keyset encryption example")

	// Encrypt the keyset with the KEK AEAD and the associated data.
	buf := new(bytes.Buffer)
	writer := keyset.NewBinaryWriter(buf)
	err = newHandle.WriteWithAssociatedData(writer, kekAEAD, keysetAssociatedData)
	if err != nil {
		log.Fatal(err)
	}
	encryptedKeyset := buf.Bytes()

	// The encrypted keyset can now be stored.

	// To use the primitive, we first need to decrypt the keyset. We use the same
	// KEK AEAD and the same associated data that we used to encrypt it.
	reader := keyset.NewBinaryReader(bytes.NewReader(encryptedKeyset))
	handle, err := keyset.ReadWithAssociatedData(reader, kekAEAD, keysetAssociatedData)
	if err != nil {
		log.Fatal(err)
	}

	// Get the primitive.
	primitive, err := aead.New(handle)
	if err != nil {
		log.Fatal(err)
	}

	// Use the primitive.
	plaintext := []byte("message")
	associatedData := []byte("example encryption")
	ciphertext, err := primitive.Encrypt(plaintext, associatedData)
	if err != nil {
		log.Fatal(err)
	}
	decrypted, err := primitive.Decrypt(ciphertext, associatedData)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(decrypted))
}

// [END encrypted-keyset-example]
Output:
message

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Primitives added in v2.4.0

func Primitives[T any](h *Handle, config Config, _ internalapi.Token) (*primitiveset.PrimitiveSet[T], error)

Primitives creates a primitiveset.PrimitiveSet with primitives of type T from keys in h.

Only ENABLED keys are considered. This function uses either the given Config or a global registry to create the primitives.

Example usage:

ps, err := keyset.Primitives[tink.AEAD](h, internalapi.Token{}, keyset.WithConfig(config.V0()))

The returned primitiveset.PrimitiveSet is intended to be used by primitive factories.

NOTE: This is an internal API.

func Validate

func Validate(keyset *tinkpb.Keyset) error

Validate validates the given key set. Returns nil if it is valid; an error otherwise.

func ValidateKeyVersion

func ValidateKeyVersion(version, maxExpected uint32) error

ValidateKeyVersion checks whether the given version is valid. The version is valid only if it is the range [0..maxExpected]

Types

type BinaryReader

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

BinaryReader deserializes a keyset from binary proto format.

func NewBinaryReader

func NewBinaryReader(r io.Reader) *BinaryReader

NewBinaryReader returns new BinaryReader that will read from r.

func (*BinaryReader) Read

func (bkr *BinaryReader) Read() (*tinkpb.Keyset, error)

Read parses a (cleartext) keyset from the underlying io.Reader.

func (*BinaryReader) ReadEncrypted

func (bkr *BinaryReader) ReadEncrypted() (*tinkpb.EncryptedKeyset, error)

ReadEncrypted parses an EncryptedKeyset from the underlying io.Reader.

type BinaryWriter

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

BinaryWriter serializes a keyset into binary proto format.

func NewBinaryWriter

func NewBinaryWriter(w io.Writer) *BinaryWriter

NewBinaryWriter returns a new BinaryWriter that will write to w.

func (*BinaryWriter) Write

func (bkw *BinaryWriter) Write(keyset *tinkpb.Keyset) error

Write writes the keyset to the underlying io.Writer.

func (*BinaryWriter) WriteEncrypted

func (bkw *BinaryWriter) WriteEncrypted(keyset *tinkpb.EncryptedKeyset) error

WriteEncrypted writes the encrypted keyset to the underlying io.Writer.

type Config added in v2.2.0

type Config interface {
	// PrimitiveFromKey creates a primitive from a [key.Key].
	PrimitiveFromKey(key key.Key, _ internalapi.Token) (any, error)
}

Config provides methods to create primitives from [key.Key]s.

type Entry added in v2.3.0

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

Entry represents an entry in a keyset.

func (*Entry) IsPrimary added in v2.3.0

func (e *Entry) IsPrimary() bool

IsPrimary returns true if the key is the primary key.

func (*Entry) Key added in v2.3.0

func (e *Entry) Key() key.Key

Key returns the key.

func (*Entry) KeyID added in v2.3.0

func (e *Entry) KeyID() uint32

KeyID returns the key ID.

func (*Entry) KeyStatus added in v2.3.0

func (e *Entry) KeyStatus() KeyStatus

KeyStatus returns the key status.

type Handle

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

Handle provides access to a keyset to limit the exposure of the internal keyset representation, which may hold sensitive key material.

func NewHandle

func NewHandle(kt *tinkpb.KeyTemplate) (*Handle, error)

NewHandle creates a keyset handle that contains a single fresh key generated according to the given KeyTemplate.

func NewHandleWithNoSecrets

func NewHandleWithNoSecrets(ks *tinkpb.Keyset) (*Handle, error)

NewHandleWithNoSecrets creates a new instance of KeysetHandle from the the given keyset which does not contain any secret key material.

func Read

func Read(reader Reader, masterKey tink.AEAD) (*Handle, error)

Read tries to create a Handle from an encrypted keyset obtained via reader.

func ReadWithAssociatedData

func ReadWithAssociatedData(reader Reader, masterKey tink.AEAD, associatedData []byte) (*Handle, error)

ReadWithAssociatedData tries to create a Handle from an encrypted keyset obtained via reader using the provided associated data.

func ReadWithContext added in v2.3.0

func ReadWithContext(ctx context.Context, reader Reader, keyEncryptionAEAD tink.AEADWithContext, associatedData []byte) (*Handle, error)

ReadWithContext creates a keyset.Handle from an encrypted keyset obtained via reader using the provided AEADWithContext.

func ReadWithNoSecrets

func ReadWithNoSecrets(reader Reader) (*Handle, error)

ReadWithNoSecrets tries to create a keyset.Handle from a keyset obtained via reader.

func (*Handle) Entry added in v2.3.0

func (h *Handle) Entry(i int) (*Entry, error)

Entry returns the key at index i from the keyset. i must be within the range [0, Handle.Len()).

func (*Handle) KeysetInfo

func (h *Handle) KeysetInfo() *tinkpb.KeysetInfo

KeysetInfo returns *tinkpb.KeysetInfo representation of the managed keyset.

The result does not contain any sensitive key material.

func (*Handle) Len added in v2.3.0

func (h *Handle) Len() int

Len returns the number of keys in the keyset.

func (*Handle) Primary added in v2.3.0

func (h *Handle) Primary() (*Entry, error)

Primary returns the primary key of the keyset.

func (*Handle) Public

func (h *Handle) Public() (*Handle, error)

Public returns a Handle of the public keys if the managed keyset contains private keys.

func (*Handle) String

func (h *Handle) String() string

String returns a string representation of the managed keyset. The result does not contain any sensitive key material.

func (*Handle) Write

func (h *Handle) Write(writer Writer, masterKey tink.AEAD) error

Write encrypts and writes the enclosing keyset.

func (*Handle) WriteWithAssociatedData

func (h *Handle) WriteWithAssociatedData(writer Writer, masterKey tink.AEAD, associatedData []byte) error

WriteWithAssociatedData encrypts and writes the enclosing keyset using the provided associated data.

func (*Handle) WriteWithContext added in v2.3.0

func (h *Handle) WriteWithContext(ctx context.Context, writer Writer, keyEncryptionAEAD tink.AEADWithContext, associatedData []byte) error

WriteWithContext encrypts and writes the keyset using the provided AEADWithContext.

func (*Handle) WriteWithNoSecrets

func (h *Handle) WriteWithNoSecrets(w Writer) error

WriteWithNoSecrets exports the keyset in h to the given Writer w returning an error if the keyset contains secret key material.

type JSONReader

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

JSONReader deserializes a keyset from json format.

func NewJSONReader

func NewJSONReader(r io.Reader) *JSONReader

NewJSONReader returns new JSONReader that will read from r.

func (*JSONReader) Read

func (bkr *JSONReader) Read() (*tinkpb.Keyset, error)

Read parses a (cleartext) keyset from the underlying io.Reader.

func (*JSONReader) ReadEncrypted

func (bkr *JSONReader) ReadEncrypted() (*tinkpb.EncryptedKeyset, error)

ReadEncrypted parses an EncryptedKeyset from the underlying io.Reader.

type JSONWriter

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

JSONWriter serializes a keyset into json format.

func NewJSONWriter

func NewJSONWriter(w io.Writer) *JSONWriter

NewJSONWriter returns a new JSONWriter that will write to w.

func (*JSONWriter) Write

func (bkw *JSONWriter) Write(keyset *tinkpb.Keyset) error

Write writes the keyset to the underlying io.Writer.

func (*JSONWriter) WriteEncrypted

func (bkw *JSONWriter) WriteEncrypted(keyset *tinkpb.EncryptedKeyset) error

WriteEncrypted writes the encrypted keyset to the underlying io.Writer.

type KeyOpts added in v2.5.0

type KeyOpts interface {
	// contains filtered or unexported methods
}

KeyOpts is an interface for options that can be applied to a key.

func AsPrimary added in v2.5.0

func AsPrimary() KeyOpts

AsPrimary sets the key as primary.

func WithFixedID added in v2.5.0

func WithFixedID(id uint32) KeyOpts

WithFixedID sets the ID of the key.

NOTE: It is preferable to add keys with ID requirements or fixed IDs before adding keys without ID requirements to reduce the risk of ID collisions.

func WithStatus added in v2.5.0

func WithStatus(status KeyStatus) KeyOpts

WithStatus sets the status of the key.

type KeyStatus added in v2.3.0

type KeyStatus int

KeyStatus is the key status.

const (
	// Unknown is the default invalid value.
	Unknown KeyStatus = iota
	// Enabled means the key is enabled.
	Enabled
	// Disabled means the key is disabled.
	Disabled
	// Destroyed means the key is marked for destruction.
	Destroyed
)

func (KeyStatus) String added in v2.3.0

func (ks KeyStatus) String() string

String implements fmt.Stringer.

type Manager

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

Manager manages a Keyset-proto, with convenience methods that rotate, disable, enable or destroy keys. Note: It is not thread-safe.

func NewManager

func NewManager() *Manager

NewManager creates a new instance with an empty Keyset.

func NewManagerFromHandle

func NewManagerFromHandle(kh *Handle) *Manager

NewManagerFromHandle creates a new instance from the given Handle.

func (*Manager) Add

func (km *Manager) Add(kt *tinkpb.KeyTemplate) (uint32, error)

Add generates and adds a fresh key using the given key template. the key is enabled on creation, but not set to primary. It returns the ID of the new key

func (*Manager) AddKey added in v2.3.0

func (km *Manager) AddKey(key key.Key) (uint32, error)

AddKey adds key to the keyset and returns the key ID. The added key is enabled by default.

func (*Manager) AddKeyWithOpts added in v2.5.0

func (km *Manager) AddKeyWithOpts(key key.Key, _ internalapi.Token, opts ...KeyOpts) (uint32, error)

AddKeyWithOpts adds a key to the keyset with the given options.

Default options are: - The key is enabled. - The key ID is random if the key does not require an ID.

This is an internal API.

func (*Manager) AddNewKeyFromParameters added in v2.3.0

func (km *Manager) AddNewKeyFromParameters(parameters key.Parameters) (uint32, error)

AddNewKeyFromParameters generates a new key from parameters, adds the key to the keyset, and returns the key ID.

func (*Manager) Delete

func (km *Manager) Delete(keyID uint32) error

Delete will delete the key with given keyID, removing the key from the keyset entirely. Returns an error if the key is not found or it is the primary key.

func (*Manager) Disable

func (km *Manager) Disable(keyID uint32) error

Disable will disable the key with given keyID. Returns an error if the key is not found or it is the primary key.

func (*Manager) Enable

func (km *Manager) Enable(keyID uint32) error

Enable will enable the key with given keyID. Returns an error if the key is not found or is not enabled or disabled already.

func (*Manager) Handle

func (km *Manager) Handle() (*Handle, error)

Handle creates a new Handle for the managed keyset.

func (*Manager) SetAnnotations added in v2.5.0

func (km *Manager) SetAnnotations(annotations map[string]string) error

SetAnnotations sets the annotations for the keyset.

This method makes a copy of the annotations map to prevent the caller from modifying the annotations.

func (*Manager) SetPrimary

func (km *Manager) SetPrimary(keyID uint32) error

SetPrimary sets the key with given keyID as primary. Returns an error if the key is not found or not enabled.

type MemReaderWriter deprecated

type MemReaderWriter struct {
	Keyset          *tinkpb.Keyset
	EncryptedKeyset *tinkpb.EncryptedKeyset
}

MemReaderWriter implements keyset.Reader and keyset.Writer for *tinkpb.Keyset and *tinkpb.EncryptedKeyset.

Deprecated: Use keyset.NewBinaryReader or keyset.NewBinaryWriter instead. See tests in mem_io_test.go for examples on how to use them instead.

func (*MemReaderWriter) Read

func (m *MemReaderWriter) Read() (*tinkpb.Keyset, error)

Read returns *tinkpb.Keyset from memory.

func (*MemReaderWriter) ReadEncrypted

func (m *MemReaderWriter) ReadEncrypted() (*tinkpb.EncryptedKeyset, error)

ReadEncrypted returns *tinkpb.EncryptedKeyset from memory.

func (*MemReaderWriter) Write

func (m *MemReaderWriter) Write(keyset *tinkpb.Keyset) error

Write keyset to memory.

func (*MemReaderWriter) WriteEncrypted

func (m *MemReaderWriter) WriteEncrypted(keyset *tinkpb.EncryptedKeyset) error

WriteEncrypted keyset to memory.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option is used to pass options for a keyset handle.

func WithAnnotations

func WithAnnotations(annotations map[string]string) Option

WithAnnotations adds monitoring annotations to a keyset handle.

type Reader

type Reader interface {
	// Read returns a (cleartext) Keyset object from the underlying source.
	Read() (*tinkpb.Keyset, error)

	// ReadEncrypted returns an EncryptedKeyset object from the underlying source.
	ReadEncrypted() (*tinkpb.EncryptedKeyset, error)
}

Reader knows how to read a Keyset or an EncryptedKeyset from some source. In order to turn a Reader into a KeysetHandle for use, callers must use insecure.KeysetHandle or by keyset.Read (with encryption).

type Writer

type Writer interface {
	// Write keyset to some storage system.
	Write(Keyset *tinkpb.Keyset) error

	// Write EncryptedKeyset to some storage system.
	WriteEncrypted(keyset *tinkpb.EncryptedKeyset) error
}

Writer knows how to write a Keyset or an EncryptedKeyset to some source.

Jump to

Keyboard shortcuts

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