go-micro.dev/v5@v5.12.0/config/secrets/box/box.go (about) 1 // Package box is an asymmetric implementation of config/secrets using nacl/box 2 package box 3 4 import ( 5 "crypto/rand" 6 7 "github.com/pkg/errors" 8 "go-micro.dev/v5/config/secrets" 9 naclbox "golang.org/x/crypto/nacl/box" 10 ) 11 12 const keyLength = 32 13 14 type box struct { 15 options secrets.Options 16 17 publicKey [keyLength]byte 18 privateKey [keyLength]byte 19 } 20 21 // NewSecrets returns a nacl-box codec. 22 func NewSecrets(opts ...secrets.Option) secrets.Secrets { 23 b := &box{} 24 for _, o := range opts { 25 o(&b.options) 26 } 27 return b 28 } 29 30 func (b *box) Init(opts ...secrets.Option) error { 31 for _, o := range opts { 32 o(&b.options) 33 } 34 if len(b.options.PrivateKey) != keyLength || len(b.options.PublicKey) != keyLength { 35 return errors.Errorf("a public key and a private key of length %d must both be provided", keyLength) 36 } 37 copy(b.privateKey[:], b.options.PrivateKey) 38 copy(b.publicKey[:], b.options.PublicKey) 39 return nil 40 } 41 42 // Options returns options. 43 func (b *box) Options() secrets.Options { 44 return b.options 45 } 46 47 // String returns nacl-box. 48 func (*box) String() string { 49 return "nacl-box" 50 } 51 52 // Encrypt encrypts a message with the sender's private key and the receipient's public key. 53 func (b *box) Encrypt(in []byte, opts ...secrets.EncryptOption) ([]byte, error) { 54 var options secrets.EncryptOptions 55 for _, o := range opts { 56 o(&options) 57 } 58 if len(options.RecipientPublicKey) != keyLength { 59 return []byte{}, errors.New("recepient's public key must be provided") 60 } 61 var recipientPublicKey [keyLength]byte 62 copy(recipientPublicKey[:], options.RecipientPublicKey) 63 var nonce [24]byte 64 if _, err := rand.Reader.Read(nonce[:]); err != nil { 65 return []byte{}, errors.Wrap(err, "couldn't obtain a random nonce from crypto/rand") 66 } 67 return naclbox.Seal(nonce[:], in, &nonce, &recipientPublicKey, &b.privateKey), nil 68 } 69 70 // Decrypt Decrypts a message with the receiver's private key and the sender's public key. 71 func (b *box) Decrypt(in []byte, opts ...secrets.DecryptOption) ([]byte, error) { 72 var options secrets.DecryptOptions 73 for _, o := range opts { 74 o(&options) 75 } 76 if len(options.SenderPublicKey) != keyLength { 77 return []byte{}, errors.New("sender's public key bust be provided") 78 } 79 var nonce [24]byte 80 var senderPublicKey [32]byte 81 copy(nonce[:], in[:24]) 82 copy(senderPublicKey[:], options.SenderPublicKey) 83 decrypted, ok := naclbox.Open(nil, in[24:], &nonce, &senderPublicKey, &b.privateKey) 84 if !ok { 85 return []byte{}, errors.New("incoming message couldn't be verified / decrypted") 86 } 87 return decrypted, nil 88 }