github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/core/auth/jwt_encryption_key.go (about)

     1  /*
     2   * Copyright (C) 2019 The "MysteriumNetwork/node" Authors.
     3   *
     4   * This program is free software: you can redistribute it and/or modify
     5   * it under the terms of the GNU General Public License as published by
     6   * the Free Software Foundation, either version 3 of the License, or
     7   * (at your option) any later version.
     8   *
     9   * This program is distributed in the hope that it will be useful,
    10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12   * GNU General Public License for more details.
    13   *
    14   * You should have received a copy of the GNU General Public License
    15   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    16   */
    17  
    18  package auth
    19  
    20  import (
    21  	"crypto/rand"
    22  
    23  	"github.com/pkg/errors"
    24  )
    25  
    26  // Storage for Credentials.
    27  type Storage interface {
    28  	GetValue(bucket string, key interface{}, to interface{}) error
    29  	SetValue(bucket string, key interface{}, to interface{}) error
    30  }
    31  
    32  const encryptionKeyBucket = "jwt"
    33  const encryptionKeyName = "jwt-encryption-key"
    34  
    35  // NewJWTEncryptionKey creates and stores or re-uses an existing JWT encryption key
    36  func NewJWTEncryptionKey(storage Storage) (JWTEncryptionKey, error) {
    37  	key := JWTEncryptionKey{}
    38  	err := storage.GetValue(encryptionKeyBucket, encryptionKeyName, &key)
    39  	if err != nil {
    40  		key, err = generateRandomBytes(256)
    41  		if err != nil {
    42  			return key, errors.Wrap(err, "failed to generate JWT encryption key")
    43  		}
    44  		err := storage.SetValue(encryptionKeyBucket, encryptionKeyName, key)
    45  		if err != nil {
    46  			return key, errors.Wrap(err, "failed to store JWT encryption key")
    47  		}
    48  	}
    49  
    50  	return key, nil
    51  }
    52  
    53  func generateRandomBytes(length int) ([]byte, error) {
    54  	key := make([]byte, length)
    55  	_, err := rand.Read(key)
    56  
    57  	if err != nil {
    58  		return nil, err
    59  	}
    60  
    61  	return key, nil
    62  }