secrets

package module
v1.1.4 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 24 Imported by: ? modules, 0 packages

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

README

secrets

A Go library for handling sensitive values (passwords, tokens, API keys, …) safely. Secrets are never exposed through String(), %#v, JSON marshaling, parse errors, or flag help text — only through an explicit .Secret() call.

Types

PlainSecret[T]

Stores the value in plaintext memory. Suitable when you simply want masking in logs and CLI output.

s := secrets.NewSecret("my-api-key")
s.String()   // "*****"      — masked (fixed width, does not reveal length)
s.Secret()   // "my-api-key" — explicit retrieval
GuardedSecret[T]

Stores the serialized plaintext directly in a memguard Enclave: mlock'd, guard-paged, excluded from swap and core dumps, and encrypted at rest with a per-process in-memory key managed entirely by memguard. No user-supplied key is required.

s := secrets.NewGuardedSecret("my-api-key")
s.String()   // "*****"      — masked
s.Secret()   // "my-api-key" — decrypts from protected memory on demand
s.Destroy()  // drop the sealed value; the secret reads as empty afterwards

When to choose GuardedSecret over EncryptedSecret: use GuardedSecret for the strongest in-process memory protection when you don't need to persist or share the encrypted form. Use EncryptedSecret when you need a user-supplied or KMS-derived key.

GuardedSecret is safe for concurrent use. PlainSecret, EncryptedSecret and StringSecret are safe for concurrent reads, but must not be mutated (Set, UnmarshalText, UnmarshalJSON, Destroy) concurrently with other access — Destroy wipes the stored bytes in place, so a concurrent read can fail or panic.

⚠️ Calling memguard.Purge() rotates memguard's session key, after which every existing GuardedSecret is permanently undecryptable and Secret() panics. Each read also briefly mlocks a memory page; in hot paths, read the value once and reuse it rather than calling Secret() per request.

EncryptedSecret[T]

Encrypts the value with AES-256-GCM using a per-process random key (or a key you supply). The value is stored encrypted and only decrypted on demand.

To reduce exposure to memory dumps:

  • The AES key is sealed in an memguard enclave — mlocked, guard-paged, excluded from swap and core dumps — and only opened for the moment the cipher is created.
  • Transient plaintext buffers in Set/Secret/ID are wiped immediately after use.

Limits: the value returned by Secret() lives in regular memory under the caller's control, string values are immutable and cannot be wiped, and Go's GC may copy memory. This reduces how much plaintext is resident and for how long — it does not make a memory dump safe.

NewEncryptedSecret panics for string types (including named string types), because the immutable string handed to it can never be wiped. Use []byte so buffers can actually be wiped, or StringSecret for string-valued secrets. (An EncryptedSecret[string] zero value can still be filled through Set or JSON.)

Custom T types must follow the standard UnmarshalText/UnmarshalJSON contract and copy the input if they retain it — the library wipes the decrypted buffer after unmarshaling.

es := secrets.NewEncryptedSecret([]byte("my-api-key"))
es.String()   // "*****"                — masked
es.Secret()   // []byte("my-api-key")   — decrypts on demand
StringSecret

A non-generic, []byte-backed type for string-valued secrets (e.g. CLI flags). The slice itself holds the AES-256-GCM ciphertext, encrypted with the same package key (and SetKey) as EncryptedSecret, so no wrapper struct is needed. It satisfies Secret[[]byte]: Secret() returns the plaintext as a caller-owned []byte that can be wiped after use.

s := secrets.NewStringSecret("my-api-key") // Secret[[]byte] (a *StringSecret)
s.String()          // "*****"
string(s.Secret())  // "my-api-key"

// or from an existing *string (nil or empty yields an empty secret):
val := "my-api-key"
s2 := secrets.NewStringFlag(&val)

The same key-management and memory-exposure caveats as EncryptedSecret apply.

The Secret[T] interface

All four types satisfy the Secret[T] interface (StringSecret as Secret[[]byte], via its pointer):

type Secret[T any] interface {
    encoding.TextMarshaler    // always returns masked text
    encoding.TextUnmarshaler  // parses the real value
    json.Marshaler            // always marshals as masked text
    json.Unmarshaler          // unmarshals the real value
    pflag.Value               // String / Set / Type — for CLI flags

    Secret() T                        // returns the plaintext value
    Empty() bool
    Hash() ([32]byte, error)          // unsalted SHA-256 hash of the plaintext bytes
    ID() (string, error)              // short, stable identifier derived from the value
    MarshalSecret() ([]byte, error)   // returns the plaintext bytes
    Destroy()                         // wipes the value; the secret reads as empty afterwards
    Equal(other Secret[T]) bool       // constant-time comparison of the hashes; empty secrets are never equal
}

Behavior shared by all types:

  • Set("") / UnmarshalText(nil) clears the secret.
  • Parse errors never quote the input: they wrap secrets.ErrInvalidValue and only name the target type (secrets: invalid value for secret of type int).
  • Writing to a nil secret pointer returns secrets.ErrNilSecret instead of silently dropping the value. Read methods on a nil pointer behave like an empty secret.
  • Hash(), ID() and Equal are unsalted; see the ID section below for the dictionary-attack caveat.

Supported value types

T can be anything that can be (un)marshaled:

Type Marshaling used
string direct
[]byte direct
encoding.TextMarshaler / encoding.TextUnmarshaler text
json.Marshaler / json.Unmarshaler JSON
Private keys: crypto.Signer (*rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey, …), or a broad interface holding one (crypto.Signer, crypto.PrivateKey, any) PKCS8 (x509.MarshalPKCS8PrivateKey)
Public keys: *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey, …, or a broad interface holding one (crypto.PublicKey, any) PKIX (x509.MarshalPKIXPublicKey), prefixed with a 1-byte tag
*jwt.Token (golang-jwt/jwt/v5) the token's compact string (Token.Raw)
any other struct / value encoding/json fallback

Usage

Basic string secret
import "github.com/zauberhaus/secrets"

var s secrets.StringSecret
fmt.Println(s)          // ""  (empty → no asterisks)

s2 := secrets.NewStringSecret("hunter2")
fmt.Println(s2)                  // "*****"

plain := s2.Secret()             // []byte("hunter2"), owned by the caller
defer secrets.Wipe(plain)
Byte-slice secret
b := secrets.NewSecret([]byte("raw-token"))
b.Secret() // []byte("raw-token")
Secret from an environment variable

NewEncryptedSecretFromEnv reads a variable into an EncryptedSecret[[]byte] and then unsets it, so child processes and later os.Getenv calls no longer see it. A missing variable yields an empty secret. The original value may still remain in the process's initial environment block (e.g. /proc/self/environ on Linux), which cannot be wiped from Go.

token := secrets.NewEncryptedSecretFromEnv("API_TOKEN")
if token.Empty() {
    log.Fatal("API_TOKEN not set")
}
Wiping plaintext buffers

Wipe zeroes a byte slice (via memguard.WipeBytes). Use it on []byte values returned by Secret() or MarshalSecret() once you're done with them.

data, _ := es.MarshalSecret()
defer secrets.Wipe(data)
Custom type
type Credentials struct {
    User string `json:"user"`
    Pass string `json:"pass"`
}

creds := secrets.NewSecret(Credentials{User: "alice", Pass: "s3cr3t"})
creds.String()  // "*****"
creds.Secret()  // Credentials{User:"alice", Pass:"s3cr3t"}
Private/public key secret

*rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey, and any value assignable to crypto.Signer are encoded as PKCS8 instead of JSON. Their public-key counterparts (*rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey, …) are encoded as PKIX, prefixed with a 1-byte tag.

The tag exists because a public key type has no marker interface to check T against the way crypto.Signer lets private keys skip straight to the right parser: without it, decoding a public key stored under a broad interface (any, crypto.PublicKey) would need to try a PKCS8 parse, watch it fail, and only then try PKIX. The tag lets that case go straight to PKIX in one parse. It only appears on public-key output — every other type's MarshalSecret() bytes are unprefixed, exactly as before. Untagged public key DER (loaded from a file, or written before this existed) still decodes correctly by falling back to the old try-both-parsers path.

key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)

es := secrets.NewEncryptedSecret(key)
es.Secret() // *ecdsa.PrivateKey, equal to key

// Also works when T is a broad interface:
signer := secrets.NewEncryptedSecret[crypto.Signer](key)
signer.Secret() // crypto.Signer wrapping the *ecdsa.PrivateKey

pub := secrets.NewEncryptedSecret(key.Public())
pub.Secret() // crypto.PublicKey wrapping the *ecdsa.PublicKey

Comparing decoded keys with == or reflect.DeepEqual is unreliable — RSA keys in particular cache an internal, lazily-computed FIPS-mode shadow copy that isn't guaranteed byte-identical between two otherwise-equal keys. Use the key's own Equal(x crypto.PrivateKey/PublicKey) bool method instead.

JWT secret

*jwt.Token is stored as its compact string form (Token.Raw), so only an already-parsed or already-signed token round-trips — one built with jwt.New/jwt.NewWithClaims and never turned into a string has an empty Raw.

Reading it back parses the string without verifying its signature (jwt.NewParser().ParseUnverified): this library's AES-GCM encryption already gives the stored bytes confidentiality and integrity, so re-checking the JWT's own signature on every read isn't needed for at-rest storage. If you hand the decoded token to something that trusts its claims for authorization, verify it against the appropriate key first.

signed, _ := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{"sub": "user123"}).
    SignedString([]byte("signing-key"))
tok, _, _ := jwt.NewParser().ParseUnverified(signed, jwt.MapClaims{})

es := secrets.NewEncryptedSecret(tok)
es.Secret().Raw // == signed
JSON round-trip (value is always masked)
s := secrets.NewStringSecret("tok_live_abc123")

data, _ := json.Marshal(s)
fmt.Println(string(data)) // "*****"

var s2 secrets.StringSecret
json.Unmarshal([]byte(`"tok_live_abc123"`), &s2)
string(s2.Secret()) // "tok_live_abc123"
Cobra / pflag CLI flag

All types implement pflag.Value, so they register directly as cobra flags. The value is masked in --help output; only the command handler sees the real value.

var apiKey = secrets.NewStringSecret("")

func init() {
    rootCmd.Flags().Var(apiKey, "api-key", "API key (masked in logs)")
}

func run(cmd *cobra.Command, args []string) {
    key := apiKey.Secret() // []byte copy owned by the caller
    defer secrets.Wipe(key)

    client := newClient(key) // plaintext only here
}
$ myapp --help
Flags:
  --api-key string   API key (masked in logs) (default *****)

$ myapp --api-key tok_live_abc123
# string(apiKey.Secret()) == "tok_live_abc123" inside run()

pflag quotes the raw argument in its invalid-value errors (invalid argument "…" for "--pin" flag). Install SanitizeFlagError so a mistyped secret is not echoed to the terminal or logs; it only rewrites errors for flags that hold a secret:

rootCmd.SetFlagErrorFunc(func(_ *cobra.Command, err error) error {
    return secrets.SanitizeFlagError(err)
})

A plain pflag.FlagSet with ExitOnError (the default for pflag.CommandLine) prints the unsanitized error itself before exiting; use ContinueOnError and pass the returned error through SanitizeFlagError.

Identifying a secret without exposing it

ID() returns a short, stable Base58-encoded identifier derived from the SHA-256 hash of the secret's plaintext bytes (first 8 bytes of the hash). It lets you correlate log entries or cache keys against a specific secret value without ever logging the value itself.

s := secrets.NewSecret("tok_live_abc123")
id, err := s.ID()
fmt.Println(id) // e.g. "4i7vEoxMskW" — same every time for the same value

The same value always produces the same ID; different values produce different IDs (with high probability).

⚠️ The ID is an unsalted hash of the plaintext. For low-entropy secrets (human-chosen passwords), an attacker who sees the ID can confirm guesses offline via a dictionary attack. Only expose IDs of high-entropy secrets (random tokens, generated keys).

Custom encryption key

By default a random 256-bit key is generated at process start. To use a deterministic key (e.g. from a KMS), call SetKey before any EncryptedSecret is created:

func main() {
    key := fetchKeyFromKMS() // must be exactly 32 bytes
    secrets.SetKey(key)

    // now create encrypted secrets as normal
}

SetKey panics if a key has already been initialized or if the key is not exactly 32 bytes. The key is moved into a locked memory enclave and the caller's slice is wiped in the process (also when SetKey panics). Cipher texts are bound to their type through GCM associated data, so an EncryptedSecret[[]byte] ciphertext cannot be decrypted as, say, an EncryptedSecret[int] or a StringSecret.

Installation

go get github.com/zauberhaus/secrets

License

Licensed under the Apache License, Version 2.0. See LICENSE.

Documentation

Index

Constants

View Source
const MaxBase58DecodeLen = 1 << 16

MaxBase58DecodeLen bounds the input accepted by Base58Decode. Decoding is quadratic in the input length, so unbounded untrusted input could be used for denial of service.

Variables

View Source
var (
	// ErrInvalidValue is returned (wrapped) when input cannot be parsed into
	// a secret. The underlying parser error is deliberately dropped because
	// it may quote parts of the secret.
	ErrInvalidValue = errors.New("secrets: invalid value")

	// ErrNilSecret is returned when a value is written to a nil secret
	// pointer, so the write cannot be silently lost.
	ErrNilSecret = errors.New("secrets: write to nil secret")
)

Functions

func Base58Decode

func Base58Decode(input string) ([]byte, error)

func Base58Encode

func Base58Encode(input []byte) string

func CalculateEntropy

func CalculateEntropy(data []byte) float64

func Equal

func Equal[X any, Y any](s1 Secret[X], s2 Secret[Y]) bool

Equal reports whether both secrets hold the same plaintext bytes, comparing their hashes in constant time. Empty secrets are never equal.

func SanitizeFlagError

func SanitizeFlagError(err error) error

SanitizeFlagError removes the raw argument from a pflag pflag.InvalidValueError when the flag holds a secret, so the value does not end up on stderr or in logs. Other errors are returned unchanged.

With cobra, install it once on the root command:

cmd.SetFlagErrorFunc(func(_ *cobra.Command, err error) error {
	return secrets.SanitizeFlagError(err)
})

A pflag.FlagSet using pflag.ExitOnError (the default for pflag.CommandLine) prints the unsanitized error itself before exiting; use pflag.ContinueOnError and sanitize the returned error instead.

func SetKey

func SetKey(key []byte)

SetKey sets the AES-256 key used by all EncryptedSecret values. It must be called before any EncryptedSecret is created and panics if the key is already initialized or is not exactly 32 bytes. The key is moved into a locked enclave and the caller's slice is wiped, also when SetKey panics.

func Wipe

func Wipe(data []byte)

Types

type EncryptedSecret

type EncryptedSecret[T any] struct {
	// contains filtered or unexported fields
}

EncryptedSecret holds the value AES-256-GCM encrypted with the package key (see SetKey); it is decrypted on every read.

EncryptedSecret is not safe for concurrent use while it is being mutated (Set, UnmarshalText, UnmarshalJSON, Destroy): Destroy wipes the ciphertext in place, so a concurrent read fails or panics. Use GuardedSecret when concurrent mutation is needed.

func NewEncryptedSecretFromEnv

func NewEncryptedSecretFromEnv(name string) *EncryptedSecret[[]byte]

NewEncryptedSecretFromEnv encrypts the value of the environment variable name and unsets it. The original value may still remain in the process environment block (e.g. /proc/self/environ on Linux) and in the immutable string returned by os.Getenv, neither of which can be wiped.

func (*EncryptedSecret[T]) Destroy

func (s *EncryptedSecret[T]) Destroy()

func (*EncryptedSecret[T]) Empty

func (s *EncryptedSecret[T]) Empty() bool

func (*EncryptedSecret[T]) Equal

func (s *EncryptedSecret[T]) Equal(sec Secret[T]) bool

func (EncryptedSecret[T]) GoString

func (s EncryptedSecret[T]) GoString() string

GoString masks the value for %#v, which bypasses String.

func (*EncryptedSecret[T]) Hash

func (s *EncryptedSecret[T]) Hash() ([32]byte, error)

Hash returns an unsalted SHA-256 hash of the plaintext. For low-entropy secrets (e.g. human-chosen passwords) it allows offline dictionary attacks and must not be exposed to untrusted parties.

func (*EncryptedSecret[T]) ID

func (s *EncryptedSecret[T]) ID() (string, error)

ID returns a short Base58 identifier derived from EncryptedSecret.Hash. See Hash for the dictionary-attack caveat.

func (EncryptedSecret[T]) MarshalJSON

func (s EncryptedSecret[T]) MarshalJSON() ([]byte, error)

MarshalJSON returns the masked value; the ciphertext is not decrypted.

func (*EncryptedSecret[T]) MarshalSecret

func (s *EncryptedSecret[T]) MarshalSecret() (text []byte, err error)

MarshalSecret returns the decrypted plaintext bytes, in the same serialization as PlainSecret.MarshalSecret. The caller owns the returned slice and should wipe it after use.

func (EncryptedSecret[T]) MarshalText

func (s EncryptedSecret[T]) MarshalText() ([]byte, error)

func (*EncryptedSecret[T]) Secret

func (s *EncryptedSecret[T]) Secret() T

func (*EncryptedSecret[T]) Set

func (s *EncryptedSecret[T]) Set(txt string) error

func (EncryptedSecret[T]) String

func (s EncryptedSecret[T]) String() string

func (*EncryptedSecret[T]) Type

func (s *EncryptedSecret[T]) Type() string

func (*EncryptedSecret[T]) UnmarshalJSON

func (s *EncryptedSecret[T]) UnmarshalJSON(data []byte) error

func (*EncryptedSecret[T]) UnmarshalText

func (s *EncryptedSecret[T]) UnmarshalText(text []byte) error

UnmarshalText parses and encrypts text; empty text clears the secret. Parse errors are replaced by an ErrInvalidValue error that does not quote the input.

type GuardedSecret

type GuardedSecret[T any] struct {
	// contains filtered or unexported fields
}

GuardedSecret stores the serialized plaintext in a memguard Enclave: mlock'd, guard-paged, excluded from swap and core dumps, and encrypted at rest using a per-process in-memory key managed entirely by memguard. No user-supplied encryption key is required.

Use GuardedSecret when you want the strongest in-process memory protection and do not need to persist or share the encrypted form. For a user-supplied key or persistence use EncryptedSecret.

GuardedSecret is safe for concurrent use.

Caveats

  • Calling memguard.Purge rotates memguard's session key, after which every existing GuardedSecret is permanently undecryptable and Secret() panics.
  • Every read (Secret, MarshalSecret, ID) briefly mlocks a page; extremely high parallel read fan-out may hit RLIMIT_MEMLOCK, on which memguard panics. Read once and reuse the value in hot paths.

Custom T types

Any custom T whose UnmarshalText/UnmarshalJSON retains the input slice must copy it — the library wipes the decrypted buffer after unmarshaling.

func NewGuardedSecret

func NewGuardedSecret[T any](val T) *GuardedSecret[T]

NewGuardedSecret seals val into a GuardedSecret. Panics if the value cannot be serialized.

func (*GuardedSecret[T]) Destroy

func (s *GuardedSecret[T]) Destroy()

Destroy drops the sealed value; the secret reads as empty afterwards. The plaintext cannot be recovered from the discarded ciphertext.

func (*GuardedSecret[T]) Empty

func (s *GuardedSecret[T]) Empty() bool

func (*GuardedSecret[T]) Equal

func (s *GuardedSecret[T]) Equal(sec Secret[T]) bool

func (*GuardedSecret[T]) GoString

func (s *GuardedSecret[T]) GoString() string

GoString masks the value for %#v, which bypasses String.

func (*GuardedSecret[T]) Hash

func (s *GuardedSecret[T]) Hash() ([32]byte, error)

Hash returns an unsalted SHA-256 hash of the plaintext. For low-entropy secrets (e.g. human-chosen passwords) it allows offline dictionary attacks and must not be exposed to untrusted parties.

func (*GuardedSecret[T]) ID

func (s *GuardedSecret[T]) ID() (string, error)

ID returns a short Base58 identifier derived from GuardedSecret.Hash. See Hash for the dictionary-attack caveat.

func (*GuardedSecret[T]) MarshalJSON

func (s *GuardedSecret[T]) MarshalJSON() ([]byte, error)

func (*GuardedSecret[T]) MarshalSecret

func (s *GuardedSecret[T]) MarshalSecret() ([]byte, error)

MarshalSecret returns a copy of the plaintext bytes from protected memory. The caller should wipe the returned slice after use.

func (*GuardedSecret[T]) MarshalText

func (s *GuardedSecret[T]) MarshalText() ([]byte, error)

func (*GuardedSecret[T]) Secret

func (s *GuardedSecret[T]) Secret() T

Secret decrypts and returns the protected value. Panics on decryption failure (tampered enclave or a purged memguard session).

func (*GuardedSecret[T]) Set

func (s *GuardedSecret[T]) Set(txt string) error

Set implements pflag.Value.

func (*GuardedSecret[T]) String

func (s *GuardedSecret[T]) String() string

String returns a fixed-width mask so that logs never reveal the value or its length.

func (*GuardedSecret[T]) Type

func (s *GuardedSecret[T]) Type() string

Type implements pflag.Value.

func (*GuardedSecret[T]) UnmarshalJSON

func (s *GuardedSecret[T]) UnmarshalJSON(data []byte) error

func (*GuardedSecret[T]) UnmarshalText

func (s *GuardedSecret[T]) UnmarshalText(text []byte) error

type PlainSecret

type PlainSecret[T any] struct {
	// contains filtered or unexported fields
}

PlainSecret holds the value unencrypted in ordinary heap memory; it only masks the value in fmt, text and JSON output.

A *jwt.Token is parsed with jwt.Parser.ParseUnverified: its signature is not checked, so verify it before trusting its claims.

PlainSecret is not safe for concurrent use while it is being mutated (Set, UnmarshalText, UnmarshalJSON, Destroy).

func (*PlainSecret[T]) Destroy

func (s *PlainSecret[T]) Destroy()

Destroy clears the value. A []byte value is wiped in place first; other types (notably strings, which are immutable) are only dropped.

func (*PlainSecret[T]) Empty

func (s *PlainSecret[T]) Empty() bool

func (*PlainSecret[T]) Equal

func (s *PlainSecret[T]) Equal(sec Secret[T]) bool

func (PlainSecret[T]) GoString

func (s PlainSecret[T]) GoString() string

GoString masks the value for %#v, which bypasses String.

func (*PlainSecret[T]) Hash

func (s *PlainSecret[T]) Hash() ([32]byte, error)

Hash returns an unsalted SHA-256 hash of the plaintext. For low-entropy secrets (e.g. human-chosen passwords) it allows offline dictionary attacks and must not be exposed to untrusted parties.

func (*PlainSecret[T]) ID

func (s *PlainSecret[T]) ID() (string, error)

ID returns a short Base58 identifier derived from PlainSecret.Hash. See Hash for the dictionary-attack caveat.

func (PlainSecret[T]) MarshalJSON

func (s PlainSecret[T]) MarshalJSON() ([]byte, error)

func (*PlainSecret[T]) MarshalSecret

func (s *PlainSecret[T]) MarshalSecret() ([]byte, error)

MarshalSecret returns the plaintext bytes. The returned buffer is a copy owned by the caller, who may wipe it after use. Intermediate string conversions are avoided because immutable string copies can never be wiped.

func (PlainSecret[T]) MarshalText

func (s PlainSecret[T]) MarshalText() (text []byte, err error)

func (*PlainSecret[T]) Secret

func (s *PlainSecret[T]) Secret() T

func (*PlainSecret[T]) Set

func (s *PlainSecret[T]) Set(txt string) error

func (PlainSecret[T]) String

func (s PlainSecret[T]) String() string

func (*PlainSecret[T]) Type

func (s *PlainSecret[T]) Type() string

func (*PlainSecret[T]) UnmarshalJSON

func (s *PlainSecret[T]) UnmarshalJSON(data []byte) error

func (*PlainSecret[T]) UnmarshalText

func (s *PlainSecret[T]) UnmarshalText(text []byte) error

UnmarshalText parses text into the secret; empty text clears it. Parse errors are replaced by an ErrInvalidValue error that does not quote the input.

type Secret

type Secret[T any] interface {
	encoding.TextMarshaler
	encoding.TextUnmarshaler
	json.Unmarshaler
	json.Marshaler
	pflag.Value

	Secret() T
	Empty() bool
	String() string
	Hash() ([32]byte, error)
	ID() (string, error)

	Equal(s Secret[T]) bool

	MarshalSecret() (text []byte, err error)
	Destroy()

	pflag.Value
}

func NewEncryptedSecret

func NewEncryptedSecret[T any](secret T) Secret[T]

func NewSecret

func NewSecret[T any](val T) Secret[T]

NewSecret wraps val. A []byte val is not copied: Destroy wipes the caller's slice.

func NewStringFlag

func NewStringFlag(val *string) Secret[[]byte]

NewStringFlag encrypts val into a new SecretStringFlag. Panics if the value cannot be encrypted.

func NewStringSecret

func NewStringSecret(val string) Secret[[]byte]

type Serializable

type Serializable interface {
	encoding.TextMarshaler
	encoding.TextUnmarshaler
}

type Singleton

type Singleton[T any] struct {
	// contains filtered or unexported fields
}

func NewSingleton

func NewSingleton[T any](init func() T) Singleton[T]

func (*Singleton[T]) Get

func (s *Singleton[T]) Get() T

type StringSecret

type StringSecret []byte

StringSecret is a string value encrypted with AES-256-GCM, using the same package key (and SetKey) as EncryptedSecret. Unlike EncryptedSecret it needs no wrapper struct: the slice itself is the ciphertext.

See EncryptedSecret for the key-management, memory-exposure and concurrency caveats that apply here too.

func (*StringSecret) Destroy

func (s *StringSecret) Destroy()

Destroy implements Secret.

func (*StringSecret) Empty

func (s *StringSecret) Empty() bool

Empty implements Secret.

func (*StringSecret) Equal

func (s *StringSecret) Equal(sec Secret[[]byte]) bool

func (StringSecret) GoString

func (s StringSecret) GoString() string

GoString masks the value for %#v, which would otherwise print the ciphertext bytes.

func (*StringSecret) Hash

func (s *StringSecret) Hash() ([32]byte, error)

Hash returns an unsalted SHA-256 hash of the plaintext. For low-entropy secrets (e.g. human-chosen passwords) it allows offline dictionary attacks and must not be exposed to untrusted parties.

func (*StringSecret) ID

func (s *StringSecret) ID() (string, error)

func (StringSecret) MarshalJSON

func (s StringSecret) MarshalJSON() ([]byte, error)

func (*StringSecret) MarshalSecret

func (s *StringSecret) MarshalSecret() (text []byte, err error)

func (StringSecret) MarshalText

func (s StringSecret) MarshalText() (text []byte, err error)

func (*StringSecret) Secret

func (s *StringSecret) Secret() []byte

func (*StringSecret) Set

func (s *StringSecret) Set(val string) error

func (StringSecret) String

func (s StringSecret) String() string

func (*StringSecret) Type

func (s *StringSecret) Type() string

func (*StringSecret) UnmarshalJSON

func (s *StringSecret) UnmarshalJSON(data []byte) error

func (*StringSecret) UnmarshalText

func (s *StringSecret) UnmarshalText(text []byte) error

UnmarshalText implements Secret.

Jump to

Keyboard shortcuts

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