github.com/annwntech/go-micro/v2@v2.9.5/config/secrets/secrets.go (about)

     1  // Package secrets is an interface for encrypting and decrypting secrets
     2  package secrets
     3  
     4  import "context"
     5  
     6  // Secrets encrypts or decrypts arbitrary data. The data should be as small as possible
     7  type Secrets interface {
     8  	// Initialise options
     9  	Init(...Option) error
    10  	// Return the options
    11  	Options() Options
    12  	// Decrypt a value
    13  	Decrypt([]byte, ...DecryptOption) ([]byte, error)
    14  	// Encrypt a value
    15  	Encrypt([]byte, ...EncryptOption) ([]byte, error)
    16  	// Secrets implementation
    17  	String() string
    18  }
    19  
    20  type Options struct {
    21  	// Key is a symmetric key for encoding
    22  	Key []byte
    23  	// Private key for decoding
    24  	PrivateKey []byte
    25  	// Public key for encoding
    26  	PublicKey []byte
    27  	// Context for other opts
    28  	Context context.Context
    29  }
    30  
    31  // Option sets options
    32  type Option func(*Options)
    33  
    34  // Key sets the symmetric secret key
    35  func Key(k []byte) Option {
    36  	return func(o *Options) {
    37  		o.Key = make([]byte, len(k))
    38  		copy(o.Key, k)
    39  	}
    40  }
    41  
    42  // PublicKey sets the asymmetric Public Key of this codec
    43  func PublicKey(key []byte) Option {
    44  	return func(o *Options) {
    45  		o.PublicKey = make([]byte, len(key))
    46  		copy(o.PublicKey, key)
    47  	}
    48  }
    49  
    50  // PrivateKey sets the asymmetric Private Key of this codec
    51  func PrivateKey(key []byte) Option {
    52  	return func(o *Options) {
    53  		o.PrivateKey = make([]byte, len(key))
    54  		copy(o.PrivateKey, key)
    55  	}
    56  }
    57  
    58  // DecryptOptions can be passed to Secrets.Decrypt
    59  type DecryptOptions struct {
    60  	SenderPublicKey []byte
    61  }
    62  
    63  // DecryptOption sets DecryptOptions
    64  type DecryptOption func(*DecryptOptions)
    65  
    66  // SenderPublicKey is the Public Key of the Secrets that encrypted this message
    67  func SenderPublicKey(key []byte) DecryptOption {
    68  	return func(d *DecryptOptions) {
    69  		d.SenderPublicKey = make([]byte, len(key))
    70  		copy(d.SenderPublicKey, key)
    71  	}
    72  }
    73  
    74  // EncryptOptions can be passed to Secrets.Encrypt
    75  type EncryptOptions struct {
    76  	RecipientPublicKey []byte
    77  }
    78  
    79  // EncryptOption Sets EncryptOptions
    80  type EncryptOption func(*EncryptOptions)
    81  
    82  // RecipientPublicKey is the Public Key of the Secrets that will decrypt this message
    83  func RecipientPublicKey(key []byte) EncryptOption {
    84  	return func(e *EncryptOptions) {
    85  		e.RecipientPublicKey = make([]byte, len(key))
    86  		copy(e.RecipientPublicKey, key)
    87  	}
    88  }