1
0

secrets.go 2.1 KB

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