github.com/zntrio/harp/v2@v2.0.9/pkg/sdk/value/encryption/secretbox/helpers.go (about)

     1  // Licensed to Elasticsearch B.V. under one or more contributor
     2  // license agreements. See the NOTICE file distributed with
     3  // this work for additional information regarding copyright
     4  // ownership. Elasticsearch B.V. licenses this file to you under
     5  // the Apache License, Version 2.0 (the "License"); you may
     6  // not use this file except in compliance with the License.
     7  // You may obtain a copy of the License at
     8  //
     9  //     http://www.apache.org/licenses/LICENSE-2.0
    10  //
    11  // Unless required by applicable law or agreed to in writing,
    12  // software distributed under the License is distributed on an
    13  // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    14  // KIND, either express or implied.  See the License for the
    15  // specific language governing permissions and limitations
    16  // under the License.
    17  
    18  package secretbox
    19  
    20  import (
    21  	"crypto/rand"
    22  	"errors"
    23  	"fmt"
    24  	"io"
    25  
    26  	"golang.org/x/crypto/nacl/secretbox"
    27  )
    28  
    29  const (
    30  	keyLength   = 32
    31  	nonceLength = 24
    32  )
    33  
    34  func generateNonce() ([nonceLength]byte, error) {
    35  	var nonce [nonceLength]byte
    36  	_, err := io.ReadFull(rand.Reader, nonce[:])
    37  	return nonce, err
    38  }
    39  
    40  func encrypt(plaintext []byte, key [keyLength]byte) ([]byte, error) {
    41  	nonce, err := generateNonce()
    42  	if err != nil {
    43  		return nil, fmt.Errorf("failed to generate nonce")
    44  	}
    45  	return secretbox.Seal(nonce[:], plaintext, &nonce, &key), nil
    46  }
    47  
    48  func decrypt(ciphertext []byte, key [keyLength]byte) ([]byte, error) {
    49  	var nonce [nonceLength]byte
    50  	copy(nonce[:], ciphertext[:nonceLength])
    51  	decrypted, ok := secretbox.Open(nil, ciphertext[nonceLength:], &nonce, &key)
    52  	if !ok {
    53  		return nil, errors.New("failed to decrypt given message")
    54  	}
    55  	return decrypted, nil
    56  }