Skip to content
Snippets Groups Projects
utils.go 1.43 KiB
Newer Older
  • Learn to ignore specific revisions
  • package crypto
    
    import (
    	"crypto/rand"
    	"encoding/base64"
    
    Malte Bauch's avatar
    Malte Bauch committed
    	"fmt"
    
    
    	"github.com/google/uuid"
    
    // Key is a struct that holds a key as a byte array and as a base64 encoded
    // string and the id of the key.
    
    type Key struct {
    	// ID is the id of the key
    	ID uuid.UUID
    
    	// Key as byte array
    
    	// Key as base64 encoded string
    	KeyAsBase64 string
    
    // KSAKey is a stuct that represents a the object delivered to a requesting instance.
    type KSAKey struct {
    	// KeyID is the id of the key.
    	KeyID string `json:"key_ID"`
    	// Key is the key value as Base64.
    	Key string `json:"key"`
    }
    
    
    // Random256BitKey generates a random 256 bit key and returns it as a Key
    // struct.
    
    func Random256BitKey() (*Key, error) {
    
    	// Create a new byte array with a length of 32 bytes
    
    	b := make([]byte, 32)
    
    	// fill the byte array with random bytes
    
    	_, err := rand.Read(b)
    	if err != nil {
    		return nil, err
    	}
    
    
    	// Encode the byte array to a base64 encoded string
    
    	keyAsBase64String := base64.StdEncoding.EncodeToString(b)
    
    	return &Key{
    		ID:          uuid.New(),
    		Key:         b,
    		KeyAsBase64: keyAsBase64String,
    	}, nil
    
    Malte Bauch's avatar
    Malte Bauch committed
    
    func GetCryptoAlgorithmByName(cryptoAlgorithmName string) (CryptoAlgorithm, error) {
    	switch cryptoAlgorithmName {
    	case "AES_256_GCM":
    		return NewAES(cryptoAlgorithmName), nil
    	case "OTP":
    		return NewOTP(cryptoAlgorithmName), nil
    	default:
    		return nil, fmt.Errorf("The provided crypto algorithm name: %s is not supported.", cryptoAlgorithmName)
    	}
    }